簡體   English   中英

Spring Security 不適用於授權:來自 OAuth2 的不記名令牌

[英]Spring Security is not working with Authorization: Bearer token from OAuth2

我有兩個微服務,第一個用於 OAuth2,第二個用於 API。 當我從瀏覽器登錄時,一切正常,授權通過並重定向到我的 API 工作。 但是當我嘗試通過 Postman 執行此操作時,我無法訪問 API。

請看這個鏈接,我從這個https://www.baeldung.com/sso-spring-security-oauth2復制了很多代碼

技術棧:Java 8、Spring Boot、Spring Web、Spring Security、OAuth2。

我嘗試使用不同的配置和許多選項,但到目前為止我已將代碼返回到傳出狀態,以便您可以告訴我可能是什么錯誤。

認證模塊:

server:
  port: 8081
  servlet:
    context-path: /auth
@SpringBootApplication
@EnableResourceServer
public class AuthApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(AuthApplication.class, args);
    }

}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                   .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
               .withClient("my-client")
               .secret(passwordEncoder.encode("secret"))
               .authorizedGrantTypes("authorization_code", "client_credentials")
               .scopes("user_info", "read", "write", "trust")
               .autoApprove(true)
               .accessTokenValiditySeconds(5000)
               .redirectUris("http://localhost:8080/api/login");
    }
}
@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
            .antMatchers("/login", "/oauth/authorize")
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("john")
            .password(passwordEncoder().encode("john"))
            .roles("USER");
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}

接口模塊:

server:
  servlet:
    context-path: /api
security:
  oauth2:
    client:
      clientId: my-client
      clientSecret: secret
      accessTokenUri: http://localhost:8081/auth/oauth/token
      userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
    resource:
      userInfoUri: http://localhost:8081/auth/user/me

@Configuration
@EnableOAuth2Sso
@EnableWebSecurity
public class OAuthConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/login**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .logout().permitAll()
            .and()
            .httpBasic().disable();
    }
}
@RestController
public class DashboardController {

    @GetMapping("/demo")
    public String demo() {
        return "Hello";
    }
}

當我獲得 access_token 時 - 我無法訪問 API。 請看下面的截圖訪問令牌

不工作

此問題的根本原因是 OAuth2 應用程序上的 @EnableResourceServer 注釋。 為什么? 因為實際上 OAuth2 服務器不能同時是資源服務和身份驗證服務。 所以我們需要簡化OAuth2資源端的邏輯,去掉下面的注解。 我要關閉這個問題。

如果有人有問題 - 請寫評論

一般來說,我會專注於編寫 API 並使用第三方授權服務器。 任何人都不應該編寫自己的授權服務器 - 一些在線 Java 指南具有很強的誤導性。 消費者將如何獲得令牌並調用您的 API? 以下示例消息工作流程可能會幫助您思考: https: //authguidance.com/2017/09/26/basicspa-oauthworkflow/ 如果這有幫助,請隨時 ping 我的后續問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM