簡體   English   中英

具有LDAP身份驗證的自定義權

[英]Custom authorities with LDAP authentication

我發現很少有Spring XML配置示例用於使用LDAP登錄並使用自定義方法而不是通過LDAP配置登錄用戶的權限。 不幸的是,我找不到任何帶注釋的Spring Boot示例。

在我們的示例中,有一個中央LDAP存儲庫,其中存儲了用戶的用戶名和密碼,但用戶的組不存儲在那里。

我感謝任何例子或參考。 先感謝您。

您可以在下面找到我們在項目中的最終實施。 基本流程是:

a)在身份驗證期間檢查用戶ID和角色。 如果未定義用戶或沒有應用程序的角色,請不要對用戶進行身份驗證。

b)如果用戶通過數據庫檢查,繼續使用ldap身份驗證。

c)將來自數據庫的角色與在應用程序期間使用的ldap合並。

public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter implements InitializingBean {
...
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
  .authenticationProvider(this.ldapAndDatabaseAuthenticationProvider());
}

@Bean(name="ldapAuthenticationProvider")
public AuthenticationProvider ldapAndDatabaseAuthenticationProvider(){
  LdapUserDetailsMapper userDetailsMapper = new LdapUserDetailsMapper();
  userDetailsMapper.setRoleAttributes(new String[]{"groupMembership"});

  LdapAndDatabaseAuthenticationProvider provider = 
      new LdapAndDatabaseAuthenticationProvider(this.ldapAuthenticator(), this.ldapAuthoritiesPopulator());
  provider.setUserDetailsContextMapper(userDetailsMapper);

  return provider;
}

@Bean( name = "ldapAuthoritiesPopulator" )
public LdapAndDatabaseAuthoritiesPopulator ldapAuthoritiesPopulator(){
  return new LdapAndDatabaseAuthoritiesPopulator(this.contextSource(), "");
}

@Bean( name = "ldapAuthenticator" )
public LdapAuthenticator ldapAuthenticator() {

    BindAuthenticator authenticator = new BindAuthenticator(   this.contextSource() );
  authenticator.setUserDnPatterns(new String[]{"cn={0},ou=prod,o=COMP"});

  return authenticator;
}

@Bean( name = "contextSource" )
public DefaultSpringSecurityContextSource contextSource() {

    DefaultSpringSecurityContextSource contextSource =
          new DefaultSpringSecurityContextSource( ldapUrl );
    return contextSource;
}

以下是其他角色populator(LdapAndDatabaseAuthoritiesPopulator)的實現方式。

public class LdapAndDatabaseAuthoritiesPopulator extends DefaultLdapAuthoritiesPopulator{

  public LdapAndDatabaseAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase) {
    super(contextSource, groupSearchBase);
  }

  protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user,
      String username) {
    Set<GrantedAuthority> mappedAuthorities = new HashSet<GrantedAuthority>();

    /* Add additional roles from other sources for this user*/
    /* below add is just an example of how to add a role */
    mappedAuthorities.add(
        new GrantedAuthority() { 
          private static final long serialVersionUID = 3618700057662135367L;

          @Override 
          public String getAuthority() { 
            return "ROLE_MYAPP_USER"; //this is just a temporary role we are adding as example. get the roles from database.
          } 

         @Override
         public String toString(){
          return this.getAuthority();
         }
        });


    for (GrantedAuthority granted : mappedAuthorities) {
      log.debug("Authority : {}", granted.getAuthority().toString());
    }

    return mappedAuthorities;
  }

}

下面是Custom Ldap身份驗證提供程序(LdapAndDatabaseAuthenticationProvider)實現的方式,用於檢查用戶是否具有在數據庫中定義的訪問應用程序所需的角色。 如果用戶不在數據庫中或缺少角色,則身份驗證將拋出帳戶DisabledException。

franDays還建議使用“自定義身份驗證提供程序”。 我想給他一個功勞。

public class LdapAndDatabaseAuthenticationProvider extends LdapAuthenticationProvider{

  public LdapAndDatabaseAuthenticationProvider(LdapAuthenticator authenticator, LdapAuthoritiesPopulator authoritiesPopulator) {
    super(authenticator, authoritiesPopulator);
  }

  @Override
  protected DirContextOperations doAuthentication(
      UsernamePasswordAuthenticationToken authentication) {

    log.debug("Checking if user <{}> is defined at database to use this application.", authentication.getName());

    // Here is the part we need to check in the database if user has required role to log into the application.
    // After check if user has the role, do nothing, otherwise throw exception like below example.    
    boolean canUserAuthenticate = isActiveUserExist(authentication.getName());
    log.debug("canUserAuthenticate: {}", canUserAuthenticate);

    if (!canUserAuthenticate)
      throw new DisabledException("User does not have access to Application!");

    return super.doAuthentication(authentication);
  }


  private boolean isActiveUserExist(String userId) {

  // Do your logic here are return boolean value...

  }

您可以實現自己的AuthenticationProvider。 authenticate方法將查詢LdapTemplate,並在成功嘗試后,然后從存儲它們的任何位置查詢組。 它可能如下所示:

public class CustomAuthenticationProvider implements AuthenticationProvider {

  private LdapTemplate ldapTemplate;
  private UserRepository userRepository;

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
      String username = (String) authentication.getPrincipal();
      boolean success = ldapTemplate.authenticate(...);
      if (!success) {
          throw new BadCredentialsException("Wrong username or password");
      }
      User user = userRepository.findByUsername(username); 
      if (user == null) {
          throw new BadCredentialsException("Username not known by the application");
      }
      return new CustomAuthentication(username, user.getRoles());
  }
}

我省略了LdapTemplate的初始化,因為它取決於你的情況的具體情況。 您返回的Authentication對象也需要實現一個類,並允許通過傳遞用戶名和密碼來構建實例。

如果您需要有關如何使用java config注冊auth提供程序的指導,這篇文章可能有所幫助: 使用Spring Security和Java Config的自定義身份驗證提供程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM