【问题标题】:Performing authentication via spring security oauth2通过 spring security oauth2 执行身份验证
【发布时间】:2017-03-20 07:28:36
【问题描述】:

我在我的 Spring Boot 应用程序中配置了 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);
        }
    }
}

【问题讨论】:

  • 您的身份验证服务和用户详细信息服务在哪里?
  • @jorrin,我没有 AuthenticationService,是的,我有 userDetailsS​​ervice。实际上,在这种情况下,我不明白也找不到任何文档如何使用 spring security oauth2 访问登录请求。

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


【解决方案1】:

你应该有这样的东西:

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

}

【讨论】:

  • 嗯。但是spring security已经实现了AuthenticationProvider。为什么我不能使用它? (当我在我的应用程序中创建基本安全性(弹簧安全性)时,它使用弹簧身份验证提供程序。
  • 我没有。我没有实现这一点。我弄错了:当我使用spring security basic时,我使用了authenticationManager。我知道 Spring Security 有 AuthenticationProvider 的实现。为什么我不能使用其中之一? docs.spring.io/spring-security/site/docs/current/apidocs/org/…
  • projects.spring.io/spring-security-oauth/docs/oauth2.html 我在这里没有读到关于实现 AuthenticationProvider 的内容
猜你喜欢
  • 1970-01-01
  • 2012-03-06
  • 2013-02-23
  • 2017-10-28
  • 2014-09-15
  • 2019-01-28
  • 2015-04-27
  • 2013-06-12
  • 1970-01-01
相关资源
最近更新 更多