【问题标题】:Spring security authentication through database with custom user使用自定义用户通过数据库进行 Spring 安全认证
【发布时间】:2016-10-21 09:18:10
【问题描述】:

我正在使用 Spring 安全性和注释通过数据库和 Ldap 对用户进行身份验证。 详细地说,由于 Ldap 不允许检索属性,我通过 Ldap 搜索检查用户(唯一代码)和密码是否正确,然后使用我的数据库加载权限。因此,我数据库中的所有用户都存在于 Ldap 中,但如果用户存在于 Ldap 中而不是我的数据库中,我将显示一个特定页面。 这是实际代码:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
@PropertySource(value = { "classpath:application.properties" })
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    AuthenticationConfiguration authenticationConfiguration;

    @Configuration
    protected static class AuthenticationConfiguration implements
    AuthenticationProvider {

        @Autowired
        private UserServices userServices;
        @Autowired
        LdapServices ldapServices;

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
            String name = authentication.getName();
            String password = authentication.getCredentials().toString();
            boolean isFind = ldapServices.ldapSearch(name, password);                           
            if (isFind){
                com.domain.User user = userServices.getByUsersEnabled(name);
                if (user!=null)
                    authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getRole().getRole()));          
                return new UsernamePasswordAuthenticationToken(name, password, authorities);
            }           
            else return null;
        }


        @Override
        public boolean supports(Class<?> authentication) {
            return authentication.equals(UsernamePasswordAuthenticationToken.class);
        }
    }

    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationConfiguration);
        }

...web services authentication

我有一个简单的用户,我想添加一些信息,例如姓名和电子邮件。我读到我必须实现UserDetailsService 接口的UserDetailsloadUserByUsername,但是如何将loadUserByUsername 与我的代码合并?通过这种方式,我可以显示姓名而不是用户代码。谢谢

【问题讨论】:

    标签: java spring spring-mvc authentication spring-security


    【解决方案1】:

    我将return new UsernamePasswordAuthenticationToken(name, password, authorities); 更改为return new UsernamePasswordAuthenticationToken(user, password, authorities);,并在我的HTML 页面中使用sec:authentication="principal.name" 来检索名称参数

    【讨论】:

      【解决方案2】:

      我也遇到了一些类似问题,然后我发现了一篇很棒的文章帮助我完成了它。 文章在这里:spring-ldap-custom-authorities

      我希望它有所帮助。基本上,您必须在 LDAP 服务器上进行身份验证过程,并且您必须创建一个“CustomLdapAuthoritiesPopulator”,以便稍后获取用户详细信息。

      你必须在你的 XML 上有这样的东西:

      <beans:bean id="ldapAuthProvider"
          class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
          <beans:constructor-arg>
              <beans:bean
                  class="org.springframework.security.ldap.authentication.BindAuthenticator">
                  <beans:constructor-arg ref="contextSource" />
                  <beans:property name="userSearch" ref="userSearch" />
              </beans:bean>
          </beans:constructor-arg>
          <beans:constructor-arg>
              <!-- User roles -->
              <beans:bean class="com.company.package.CustomLdapAuthoritiesPopulator" />
          </beans:constructor-arg>
      </beans:bean>
      

      稍后在您的 CustomLdapAuthoritiesPopulator 上,您将处理用户角色。像这样的:

      @Service("myAuthPopulator")
      public class CustomLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {
          @Transactional(readOnly=true)
          @Override
          public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
      
              Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
              try {
      
                  User user = userService.findUserByUsername(username);
      
                  if (user == null) {
                     // User doesn't exist in the database
                  } else {
      
                     // user exists
      
                      //get roles
                      Set<UserRole> userRoles = user.getUserRoles();
      
                      //add roles
                      for (UserRole userRole : userRoles) {
                          authorities.add(new SimpleGrantedAuthority(userRole.getRole()));
                      }
      
                      return authorities;
                  }
              } catch(Exception e) {
                  //exception
              }
              return authorities;
          }
      
      }
      

      【讨论】:

      • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
      • 嗨@ProkashSarkar,感谢您的回复。我已经编辑了答案并添加了一些代码。我想现在好多了。
      猜你喜欢
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2019-06-25
      相关资源
      最近更新 更多