Spring Security不适用于授权:来自OAuth2的承载令牌

时间:2019-08-15 10:24:05

标签: spring spring-boot spring-security oauth-2.0 bearer-token

我有两个微服务,第一个用于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();
    }

}

API模块:

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。 请看下面的截图 access_token

not working

2 个答案:

答案 0 :(得分:0)

此问题的根本原因是OAuth2应用程序上的@EnableResourceServer批注。为什么?因为实际上OAuth2服务器不能同时作为资源服务和身份验证服务。因此,我们需要简化OAuth2资源方面的逻辑,并在下面删除注释。我要结束这个问题。

如果有人有任何问题-请发表评论

答案 1 :(得分:-1)

一般来说,我将重点介绍对您的API进行编码并使用第三方授权服务器。没有人应该编写自己的授权服务器-某些在线Java指南极具误导性。消费者将如何获得令牌并调用您的API?以下示例消息工作流程可以帮助您思考:https://authguidance.com/2017/09/26/basicspa-oauthworkflow/ 如果有帮助,请随时联系我后续问题