Spring Boot Sping Boot Authenticate Rest API using Google OAuth2以及如何使用Postman进行测试

t3irkdon  于 2023-11-17  发布在  Spring
关注(0)|答案(1)|浏览(175)

我已经创建了Sping Boot Rest API并使用Google OAuth2进行身份验证。
我正在使用浏览器测试GET API,它工作正常。但是,我需要测试POST API,我正在使用POSTMAN并获得未连接的HTML响应。
pom.xml --包含依赖项。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-oauth2-client</artifactId>
  4. </dependency>

字符串
已创建配置-

  1. public class OAuthConfig extends WebSecurityConfigurerAdapter {
  2. @Override
  3. public void configure(HttpSecurity http) throws Exception {
  4. http.csrf().disable().antMatcher("/**")
  5. .authorizeRequests()
  6. .antMatchers("/")
  7. .permitAll()
  8. .anyRequest()
  9. .authenticated().and().oauth2Login().and().oauth2Client();
  10. }
  11. }
  12. =========================
  13. @GetMapping(value = "/hello", produces = "application/json")
  14. public Principal getHello(Principal principal) {
  15. return principal;
  16. }


在使用gmail用户名和密码进行身份验证后,此休息点在浏览器中工作正常。主体在浏览器上呈现JOSN对象。在点击URL http:localhost:8081/hello“idToken”:{“tokenValue”:但是,它不适用于POSTMAN。
请有人帮我测试后API使用POSTMAN。

b1uwtaje

b1uwtaje1#

我也遇到了这个问题,我刚刚解决了它。希望这对你也有用。我试图从spring安全示例中获得一些信息,我认为这是有帮助的:https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/oauth2/resource-server/hello-security我想你需要在你的代码中添加这一行,虽然我还不知道为什么它会起作用。

  1. .oauth2ResourceServer((oauth2) -> oauth2.jwt(withDefaults()))

字符串
下面是我修改后的代码,现在可以在postman上工作了:

  1. @Configuration
  2. @EnableWebSecurity
  3. public class SpringSecurityConfig {
  4. @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
  5. String jwkSetUri;
  6. @Bean
  7. SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
  8. httpSecurity.authorizeHttpRequests(
  9. auth -> {
  10. auth.anyRequest().authenticated();
  11. }
  12. ).oauth2Login(withDefaults())
  13. .oauth2ResourceServer((oauth2) -> oauth2.jwt(withDefaults()));
  14. return httpSecurity.build();
  15. }
  16. @Bean
  17. JwtDecoder jwtDecoder() {
  18. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
  19. }
  20. }


在application.properties:

  1. spring.security.oauth2.client.registration.google.client-id=<your-id>
  2. spring.security.oauth2.client.registration.google.client-secret=<your-secret>
  3. spring.security.oauth2.resourceserver.jwt.jwk-set- uri=https://www.googleapis.com/oauth2/v3/certs

展开查看全部

相关问题