通过spring security oauth2

时间:2017-03-20 07:28:37

标签: java spring spring-boot spring-security oauth-2.0

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

@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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你应该有这样的东西:

@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);
}

}

并将其注册到您的SecurityConfig

 @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();
}

}