spring-security-oauth2 2.0.7刷新令牌UserDetailsS​​ervice配置 - UserDetailsS​​ervice是必需的

时间:2015-05-26 09:20:13

标签: spring spring-security spring-security-oauth2 spring-security-ldap

请问有关spring-security-oauth2 2.0.7的配置问题。 我正在使用LDAP通过GlobalAuthenticationConfigurerAdapter进行身份验证:

@SpringBootApplication
@Controller
@SessionAttributes("authorizationRequest")
public class AuthorizationServer extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(AuthorizationServer.class, args);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/oauth/confirm_access").setViewName("authorize");
    }

    @Configuration
    public static class JwtConfiguration {

        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            KeyPair keyPair = new KeyStoreKeyFactory(
                    new ClassPathResource("keystore.jks"), "foobar".toCharArray())
                    .getKeyPair("test");
            converter.setKeyPair(keyPair);
            return converter;
        }

        @Bean
        public JwtTokenStore jwtTokenStore(){
            return new JwtTokenStore(jwtAccessTokenConverter());
        }
    }


    @Configuration
    @EnableAuthorizationServer
    public static class OAuth2Config extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {

        private static final String ENV_OAUTH = "authentication.oauth.";
        private static final String PROP_CLIENTID = "clientid";
        private static final String PROP_SECRET = "secret";
        private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

        private RelaxedPropertyResolver propertyResolver;

        @Inject
        private AuthenticationManager authenticationManager;

        @Inject
        private JwtAccessTokenConverter jwtAccessTokenConverter;

        @Inject
        private JwtTokenStore jwtTokenStore;

        @Inject
        private UserDetailsService userDetailsService;

        @Override
        public void setEnvironment(Environment environment) {
            this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(jwtTokenStore);
            tokenServices.setAuthenticationManager(authenticationManager);
            return tokenServices;
        }


        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.authenticationManager(authenticationManager).tokenStore(jwtTokenStore).accessTokenConverter(
                    jwtAccessTokenConverter).userDetailsService(userDetailsService);
        }

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

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory()
                    .withClient(propertyResolver.getProperty(PROP_CLIENTID))
                    .scopes("read", "write")
                    .authorities(AuthoritiesConstants.ADMIN, AuthoritiesConstants.USER)
                    .authorizedGrantTypes("authorization_code", "refresh_token", "password")
                    .secret(propertyResolver.getProperty(PROP_SECRET))
                    .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
        }
    }

    @Configuration
    @Order(-10)
    protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .formLogin().loginPage("/login").permitAll()
                    .and()
                    .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
                    .and()
                    .authorizeRequests().anyRequest().authenticated();
        }

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

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

    @Configuration
    protected static class AuthenticationConfiguration extends
            GlobalAuthenticationConfigurerAdapter {

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth
                    .ldapAuthentication()
                    .userDnPatterns("uid={0},ou=people")
                    .groupSearchBase("ou=groups")
                    .contextSource().ldif("classpath:test-server.ldif");
        }
    }
}

虽然刷新令牌与spring-security-oauth2的2.0.6版一起工作正常,但它不再适用于版本2.0.7。 在阅读here时,应该设置在尝试在刷新期间获取新访问令牌时使用的AuthenticationManager

据我了解,这与spring-security-oauth2的following更改有关。

我很遗憾无法正确设置它。

org.springframework.security.oauth2.provider.token.DefaultTokenServices#setAuthenticationManager
调用

并注入AuthenticationManager。我不确定我是否理解LdapUserDetailsService将如何被注入。我唯一看到的是,在令牌刷新调用期间尝试重新验证用户时将调用PreAuthenticatedAuthenticationProvider

有人可以告诉我如何做到吗?

ps:我得到的例外情况如下:

p.PreAuthenticatedAuthenticationProvider : PreAuthenticated authentication request: org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken@5775: Principal: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@441d5545: Principal: bob; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER
o.s.s.o.provider.endpoint.TokenEndpoint  : Handling error: IllegalStateException, UserDetailsService is required.

3 个答案:

答案 0 :(得分:5)

当我使用自定义AuthenticationProvider而不是UserDetailsService实现来实现具有JWT令牌的OAuth2服务器时,我遇到了类似的问题,以解决登录身份验证问题。

但是最近我发现,如果你希望refresh_token正常工作,Spring引发的错误是正确的。对于AuthenticationProvider实现,无法使用refresh_token刷新令牌,因为在这种实现中,如果密码正确,则必须解决,但刷新令牌不具备该信息。但是,UserDetailsService与密码无关。

spring-security-oauth2版本2.0.6可以工作,因为从不检查用户授权,只检查刷新令牌是否有效(使用私钥签名),但是,如果用户在之后从系统中删除了首次登录,使用刷新令牌,已删除的用户将无限时间访问您的系统,这是一个很大的安全问题。

请查看我报告的问题:https://github.com/spring-projects/spring-security-oauth/issues/813

答案 1 :(得分:4)

OAuth的所需内容是使用与身份验证器相同的查询创建LdapUserDetailsService并将其注入AuthorizationServerEndpointsConfigurer。我认为没有任何支持在UserDetailService样式中创建@Configuration(可能值得在JIRA中为此打开一张票),但看起来你可以用XML来做。

答案 2 :(得分:4)

根据Dave Syer的建议,我创建了一个自定义LdapUserDetailsService。 可以在以下tag下找到工作解决方案。

应用程序上下文

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:property-placeholder location="application.yml"/>

    <bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
        <constructor-arg value="${authentication.ldap.url}" />
    </bean>

    <bean id="userSearch" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
        <constructor-arg index="0" value="${authentication.ldap.userSearchBase}" />
        <constructor-arg index="1" value="uid={0}" />
        <constructor-arg index="2" ref="contextSource"/>
    </bean>

    <bean id="ldapAuthoritiesPopulator" class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
        <constructor-arg index="0" ref="contextSource"/>
        <constructor-arg index="1" value="${authentication.ldap.groupSearchBase}"/>
        <property name="groupSearchFilter" value="${authentication.ldap.groupSearchFilter}"/>
    </bean>

    <bean id="myUserDetailsService"
          class="org.springframework.security.ldap.userdetails.LdapUserDetailsService">
        <constructor-arg index="0" ref="userSearch"/>
        <constructor-arg index="1" ref="ldapAuthoritiesPopulator"/>
    </bean>

</beans>

属性

authentication:
 ldap:
  url: ldap://127.0.0.1:33389/dc=springframework,dc=org
  userSearchBase:
  userDnPatterns: uid={0},ou=people
  groupSearchBase: ou=groups
  groupSearchFilter: (uniqueMember={0})