Spring boot 使用 Google OAuth2 验证 Rest API 以及如何使用 Postman 进行测试

问题描述 投票:0回答:1

我已经创建了 Spring 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”:{ “令牌值”: 但是,它不适用于 POSTMAN。

请有人帮助我使用 POSTMAN 测试 POST API。

spring-boot rest postman google-oauth spring-security-oauth2
1个回答
0
投票

我也遇到了这个问题,刚刚解决了。希望这也对你有用。我尝试从 Spring Security 示例中获取一些信息,我认为这很有帮助:https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/oauth2 /资源服务器/你好安全 我想您需要在代码中添加这一行,尽管我还不完全知道它为什么有效。

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

这是我修改过的代码,现在可以在邮递员上使用:

@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();
    }
}

在应用程序属性中:

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
© www.soinside.com 2019 - 2024. All rights reserved.