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

t3irkdon  于 7个月前  发布在  Spring
关注(0)|答案(1)|浏览(88)

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

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

字符串
已创建配置-

public class OAuthConfig extends WebSecurityConfigurerAdapter {    
    @Override
    public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().antMatcher("/**")
    .authorizeRequests()
    .antMatchers("/")
    .permitAll()
    .anyRequest()
    .authenticated().and().oauth2Login().and().oauth2Client();
    }
    }

=========================

    @GetMapping(value = "/hello", produces = "application/json")
    public Principal getHello(Principal principal) {
    return principal;
    }


在使用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我想你需要在你的代码中添加这一行,虽然我还不知道为什么它会起作用。

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

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

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    String jwkSetUri;

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeHttpRequests(
                        auth -> {
                        auth.anyRequest().authenticated();
                        }
                ).oauth2Login(withDefaults())
                .oauth2ResourceServer((oauth2) -> oauth2.jwt(withDefaults()));
        return httpSecurity.build();
    }
    @Bean
    JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
    }
}


在application.properties:

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

相关问题