通过数据库与自定义用户进行Spring安全认证

时间:2016-06-20 07:47:19

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

我使用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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

你的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;
    }

}