简体   繁体   中英

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

I have two microservices, the first for OAuth2 and the second for API. When I log in from the browser, everything works fine, authorization passes and redirection to my API works. But when I try to do it through Postman, I don't get access to API.

Please see this link, I've copied a lot of code from this https://www.baeldung.com/sso-spring-security-oauth2

Tech stack: Java 8, Spring Boot, Spring Web, Spring Security, OAuth2.

I tried to use different configs and many options, but so far I have returned the code to the outgoing state so that you can tell me what could be the error.

auth module:

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 module:

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";
    }
}

When I got access_token - I can't get access to API. Please see screenshots below访问令牌

不工作

The root cause of this problem was @EnableResourceServer annotation on OAuth2 application. Why? Because actually OAuth2 server can not be Resource service and Authentification service at the same time. So we need to simplify logic on the OAuth2 resource side and remove annotation below. I gonna close this question.

If anyone will have a question - please write a comment

As a general point I would focus on coding your API and using a third party authorization server. No one should be coding their own authorization server - and some of the online Java guidance is highly misleading. How will consumers get a token and call your API? The below sample message workflow may help you to think: https://authguidance.com/2017/09/26/basicspa-oauthworkflow/ Feel free to ping me follow up questions if this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM