通过弹簧安全 oauth2 执行身份验证



我在 Spring 启动应用程序中配置 oauth2(资源服务器和身份验证服务器(,但现在如何执行身份验证?如何使用我在身份验证服务器中描述的授权?注册新用户后如何执行自动登录?

@Configuration
public class OAuth2ServerConfig {
    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Inject
        private Http401UnauthorizedEntryPoint authenticationEntryPoint;
        @Inject
        private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .exceptionHandling()
                    .authenticationEntryPoint(authenticationEntryPoint)
                    .and()
                    .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessHandler(ajaxLogoutSuccessHandler)
                    .and()
                    .csrf()
                    .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/authorize"))
                    .disable()
                    .headers()
                    .frameOptions().disable()
                    .and()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests()
                    .antMatchers("/admin").hasAnyAuthority("ADMIN");
        }
    }
    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
        private static final String CLIENTID = "app";
        private static final String PROP_SECRET = "secret";
        private static final Integer TOKEN_VALIDITY_SECONDS = -1;
        @Inject
        private OAuth2AccessTokenRepository oAuth2AccessTokenRepository;
        @Inject
        private OAuth2RefreshTokenRepository oAuth2RefreshTokenRepository;
        @Bean
        public TokenStore tokenStore() {
            return new MongoDBTokenStore(oAuth2AccessTokenRepository, oAuth2RefreshTokenRepository);
        }
        @Inject
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                throws Exception {
            endpoints
                    .tokenStore(tokenStore())
                    .authenticationManager(authenticationManager);
        }
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients
                    .inMemory()
                    .withClient(CLIENTID)
                    .scopes("read", "write")
                    .authorities("USER", "ADMIN")
                    .authorizedGrantTypes("password", "refresh_token")
                    .secret(PROP_SECRET)
                    .accessTokenValiditySeconds(TOKEN_VALIDITY_SECONDS);
        }
    }
}

你应该有这样的东西:

@Component
public class CustomAuthenticationProvider
  implements AuthenticationProvider {
    @Override
public Authentication authenticate(Authentication authentication) 
  throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    if (shouldAuthenticateAgainstThirdPartySystem()) {
        // use the credentials
        // and authenticate against the third-party system
        return new UsernamePasswordAuthenticationToken(
          name, password, new ArrayList<>());
    } else {
        return null;
    }
}
@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(
      UsernamePasswordAuthenticationToken.class);
}

}

并将其注册到您的安全配置

 @Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomAuthenticationProvider authProvider;
    @Override
protected void configure(
  AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated()
        .and()
        .httpBasic();
}

}

最新更新