16

如何将以下自定义添加UserDetailsService到此Spring OAuth2 示例中

默认值user和默认值在应用程序的文件中password定义。 application.propertiesauthserver

但是,我想将以下自定义添加UserDetailsService应用程序demo包中以authserver进行测试:

package demo;

import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

@Service
class Users implements UserDetailsManager {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password;
        List<GrantedAuthority> auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
        if (username.equals("Samwise")) {
            auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_HOBBIT");
            password = "TheShire";
        }
        else if (username.equals("Frodo")){
            auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_HOBBIT");
            password = "MyRing";
        }
        else{throw new UsernameNotFoundException("Username was not found. ");}
        return new org.springframework.security.core.userdetails.User(username, password, auth);
    }

    @Override
    public void createUser(UserDetails user) {// TODO Auto-generated method stub
    }

    @Override
    public void updateUser(UserDetails user) {// TODO Auto-generated method stub
    }

    @Override
    public void deleteUser(String username) {// TODO Auto-generated method stub
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean userExists(String username) {
        // TODO Auto-generated method stub
        return false;
    }
}

如您所见,这UserDetailsService还不autowired是,它故意使用不安全的密码,因为它只是为了测试目的而设计的。

需要对GitHub 示例应用程序进行哪些特定更改,以便用户可以username=Samwise使用password=TheShireusername=Frodo使用登录password=MyRing 是否需要对AuthserverApplication.java其他地方或其他地方进行更改?


建议:


Spring OAuth2 开发人员指南说要使用a全局GlobalAuthenticationManagerConfigurer配置 a UserDetailsService。然而,谷歌搜索这些名字产生的结果并不那么有用。

此外,使用内部 spring security INSTEAD OF OAuth 的不同应用程序使用以下语法来连接UserDetailsService,但我不确定如何将其语法调整为当前 OP:

@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {

    @Autowired
    private Users users;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(users);
    }
}

我尝试使用@Autowire内部OAuth2AuthorizationConfig连接UsersAuthorizationServerEndpointsConfigurer如下:

@Autowired//THIS IS A TEST
private Users users;//THIS IS A TEST

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
   endpoints.authenticationManager(authenticationManager)
        .accessTokenConverter(jwtAccessTokenConverter())
        .userDetailsService(users)//DetailsService)//THIS LINE IS A TEST
        ;
}

但是 Spring Boot 日志显示Samwise找不到用户,这意味着UserDetailsService没有成功连接。以下是 Spring Boot 日志的相关摘录:

2016-04-20 15:34:39.998 DEBUG 5535 --- [nio-9999-exec-9] o.s.s.a.dao.DaoAuthenticationProvider    :  
        User 'Samwise' not found
2016-04-20 15:34:39.998 DEBUG 5535 --- [nio-9999-exec-9]   
        w.a.UsernamePasswordAuthenticationFilter :  
        Authentication request failed:  
        org.springframework.security.authentication.BadCredentialsException:  
        Bad credentials

我还能尝试什么?

4

4 回答 4

7

在使用 Spring Security 开发我的 oauth 服务器时,我遇到了类似的问题。我的情况略有不同,因为我想添加一个UserDetailsService来验证刷新令牌,但我认为我的解决方案也会对您有所帮助。

像你一样,我首先尝试指定UserDetailsService使用AuthorizationServerEndpointsConfigurer,但这不起作用。我不确定这是错误还是设计使然,但UserDetailsService需要按顺序设置,AuthenticationManager以便各种 oauth2 类找到它。这对我有用:

@Configuration
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  Users userDetailsService;

  @Autowired
  public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    // other stuff to configure your security
  }

}

我认为如果您从第 73 行开始更改以下内容,它可能对您有用:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.parentAuthenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
}

您当然还需要在@Autowired Users userDetailsService;某处添加WebSecurityConfigurerAdapter

我想提的其他事情:

  1. 这可能是特定于版本的,我在 spring-security-oauth2 2.0.12
  2. 我无法引用任何资料来说明为什么会这样,我什至不确定我的解决方案是真正的解决方案还是 hack。
  3. 指南GlobalAuthenticationManagerConfigurer中提到的几乎可以肯定是一个错字,我在 Spring 中的任何内容的源代码中都找不到该字符串。
于 2017-04-06T04:56:10.827 回答
5

我遇到了同样的问题,最初的解决方案与 Manan Mehta 发布的解决方案相同。就在最近,spring security 和 spring oauth2 的某些版本组合导致尝试刷新令牌,从而导致 HTTP 500 错误UserDetailsService is required在我的日志中说明。

相关的堆栈跟踪如下所示:

java.lang.IllegalStateException: UserDetailsService is required.
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$UserDetailsServiceDelegator.loadUserByUsername(WebSecurityConfigurerAdapter.java:463)
at org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper.loadUserDetails(UserDetailsByNameServiceWrapper.java:68)
at org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider.authenticate(PreAuthenticatedAuthenticationProvider.java:103)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.oauth2.provider.token.DefaultTokenServices.refreshAccessToken(DefaultTokenServices.java:150)

您可以在底部看到DefaultTokenServices正在尝试刷新令牌。然后它会调用一个AuthenticationManager重新验证(以防用户撤销权限或用户被删除等),但这就是一切都解开的地方。您会在堆栈跟踪的顶部看到,这UserDetailsServiceDelegator就是调用loadUserByUsername而不是 my beautiful 的原因UserDetailsService。即使在我的内部我WebSecurityConfigurerAdapter设置了UserDetailsService,还有另外两个WebSecurityConfigurerAdapters。一个用于 theResourceServerConfiguration和一个用于 theAuthorizationServerSecurityConfiguration并且那些配置永远不会得到UserDetailsService我设置的。

在通过 Spring Security 一路追踪以拼凑正在发生的事情时,我发现有一个“本地”AuthenticationManagerBuilder和一个“全局” AuthenticationManagerBuilder,我们需要在全局版本上设置它,以便将这些信息传递给其他这些构建器上下文。

因此,我想出的解决方案是以与其他上下文获取全局版本相同的方式获取“全局”版本。在我的里面我WebSecurityConfigurerAdapter有以下内容:

@Autowired
public void setApplicationContext(ApplicationContext context) {
    super.setApplicationContext(context);
    AuthenticationManagerBuilder globalAuthBuilder = context
            .getBean(AuthenticationManagerBuilder.class);
    try {
        globalAuthBuilder.userDetailsService(userDetailsService);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这奏效了。其他上下文现在有了我的UserDetailsService. 我把这个留给将来偶然发现这个雷区的任何勇敢的士兵。

于 2018-08-23T20:13:41.747 回答
4

我的要求是从 oauth2 电子邮件属性的后面获取一个数据库对象。我发现了这个问题,因为我假设我需要创建一个自定义用户详细信息服务。实际上,我需要实现 OidcUser 界面并挂钩到该过程。

最初我认为它是 OAuth2UserService,但我已经设置了我的 AWS Cognito 身份验证提供程序,以便它是开放的 id 连接..

//inside WebSecurityConfigurerAdapter

http
.oauth2Login()
.userInfoEndpoint()
.oidcUserService(new CustomOidcUserServiceImpl());

...

public class CustomOidcUserServiceImpl implements OAuth2UserService<OidcUserRequest, OidcUser> {

    private OidcUserService oidcUserService = new OidcUserService();

    @Override
    public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
        OidcUser oidcUser = oidcUserService.loadUser(userRequest);
        return new CustomUserPrincipal(oidcUser);
    }
}

...

public class CustomUserPrincipal implements OidcUser {

    private OidcUser oidcUser;

    //forward all calls onto the included oidcUser
}

定制服务是任何定制逻辑可以去的地方。我计划在我的接口上实现UserDetails接口,CustomUserPrincipal以便我可以有不同的实时和测试身份验证机制,以促进自动化 ui 测试。

于 2019-10-08T09:29:27.583 回答
1

对于任何人UserDetailsService is required在执行刷新令牌时出错,并且您确认您已经拥有UserDetailsServicebean。

尝试添加这个:

@Configuration
public class GlobalSecurityConfig extends GlobalAuthenticationConfigurerAdapter {
    private UserDetailsService userDetailsService;

    public GlobalSecurityConfig(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}

这是我的尝试和错误,可能不适合你。

顺便说一句,如果你放弃“猜测”哪个bean会被spring选择,你可以自己扩展AuthorizationServerConfigurerAdapterWebSecurityConfigurerAdapter配置所有东西,但我认为它失去了spring autoconfig的力量。如果我只需要自定义一些配置,为什么我需要配置所有内容?

于 2019-06-17T08:00:05.157 回答