spring-security-oauth2 2.0.7刷新令牌UserDetailsS​​ervice配置-需要UserDetailsS​​ervice [英] spring-security-oauth2 2.0.7 refresh token UserDetailsService Configuration - UserDetailsService is required

查看:93
本文介绍了spring-security-oauth2 2.0.7刷新令牌UserDetailsS​​ervice配置-需要UserDetailsS​​ervice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would have one question regarding the configuration of spring-security-oauth2 2.0.7 please. I am doing the Authentication using LDAP via a 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版本中不再可用. 如在此处所述,应将AuthenticationManager设置为尝试在刷新期间获取新的访问令牌时使用.

While the refresh token works fine with the release 2.0.6 of spring-security-oauth2, it does not work anymore with the version 2.0.7. As read here, one should set the AuthenticationManager to be used when trying to get a new access token during the refresh.

据我了解,这与 更改spring-security-oauth2.

As far as I understand, this has something to do with the following change of spring-security-oauth2.

很遗憾,我没有正确设置它.

I unfortunately did not manage to set it up properly.

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

调用

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

is called and gets an AuthenticationManager injected. I an not sure I understand how the LdapUserDetailsService is then going to be injected. The only thing I see is that the PreAuthenticatedAuthenticationProvider is going to be called while trying to re-authenticate the user during the token refresh call.

有人可以建议我如何做吗?

Can anyone advise me on how to do it please?

ps:我得到的异常如下:

ps: The exception I am getting is the following:

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.

推荐答案

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

As advised by Dave Syer, I created a custom LdapUserDetailsService. The working solution can be found under the following 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})

这篇关于spring-security-oauth2 2.0.7刷新令牌UserDetailsS​​ervice配置-需要UserDetailsS​​ervice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆