Spring Security OAuth2 不适用于承载授权(Rest api 请求)

时间:2021-03-22 09:21:13

标签: java spring spring-boot spring-security spring-security-oauth2

我有两个微服务,第一个用于 OAuth2,第二个用于 API。当我从浏览器登录时,一切正常,授权通过并重定向到我的 API 工作。 但是当我尝试通过 Postman(rest) 执行此操作时,我无法访问 API。

OAuth2-服务器: OAuth2 微服务作为 OAuth2-Server 和 Resource-Server 的源代码:

@Configuration
@EnableAuthorizationServer
@EnableResourceServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
   @Autowired
   private UserDetailsService userDetailsService;

   @Autowired
   private BCryptPasswordEncoder passwordEncoder;

   @Autowired
   private AuthenticationManager authenticationManager;

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

   @Override
   public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
       endpoints
               .authenticationManager(authenticationManager)
               .userDetailsService(userDetailsService);
   }

   @Override
   public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
       clients.inMemory()
               .withClient("SampleClientId")
               .secret(passwordEncoder.encode("secret"))
               .authorizedGrantTypes("authorization_code", "password", "client_credentials")
               .scopes("user_info")
               .autoApprove(true)
               .accessTokenValiditySeconds(3600)
       ;
   }
}
@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceBean()).passwordEncoder(passwordEncoder());
    }

    @Override
    @Bean(name = "userDetailsService")
    public UserDetailsService userDetailsServiceBean()
            throws Exception {
        return super.userDetailsServiceBean();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

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

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

    @RequestMapping("/user/me")
    public Principal user(Principal principal) {
        System.out.println(principal);
        return principal;
    }
}

客户端 sso: 客户端微服务使用 AuthorizationServer 进行检测的源码:

@Configuration
@EnableOAuth2Sso
@EnableWebSecurity
public class UiSecurityConfig 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 UserController {

    @RequestMapping("/test")
    @ResponseBody
    public String user() {
        return "hiii";
    }
}
server:
    port: 8082

security:
  oauth2:
    client:
      clientId: SampleClientId
      clientSecret: secret
      accessTokenUri: http://localhost:8080/oauth/token
      userAuthorizationUri: http://localhost:8080/oauth/authorize
    resource:
      userInfoUri: http://localhost:8080/user/me   

Create access token

enter image description here

0 个答案:

没有答案