在Spring Security中使用配置文件名称或电子邮件登录 [英] Logging in with either profile name or email in Spring Security

查看:280
本文介绍了在Spring Security中使用配置文件名称或电子邮件登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户bean,包含userName,profileName,email等字段。

我在我的应用程序中实现了Spring Security。在登录表单中,我希望用户输入profileName或email&他应该可以同时登录。但它看起来像配置只适用于userName。我使用hibernate从数据库中获取用户详细信息。
下面是我的代码



FormLogin.jsp

  < form name ='f'action =< c:url value ='j_spring_security_check'/> 
method ='POST'>

< table>
< tr>
< td>电子邮件/简介名称< / td>
< td>< input type ='text'name ='j_username'value =''>
< / td>
< / tr>
< tr>
< td>密码:< / td>
< td>< input type ='password'name ='j_password'/>
< / td>
< / tr>
< tr>
< td colspan ='2'>< input name =submittype =submit
value =submit/>
< / td>
< / tr>
< tr>
< td colspan ='2'>< input name =resettype =reset/>
< / td>
< / tr>
< / table>

< / form>

CustomUserDetailsS​​ervice类中的loadByUserName方法

  public UserDetails loadUserByUsername(String name)抛出UsernameNotFoundException,DataAccessException 
{

//返回从db $ b获取的用户列表的get(0) $ b User domainUser = userDAO.getUser(name);
logger.info(在loadUserByUsername方法中从数据库中提取的用户+ domainUser);

设置<角色> roles = domainUser.getRole();
logger.info(用户的角色+角色);


设定<授权授权> authority = new HashSet<>(); (角色角色:角色)
{
authorities.add(new SimpleGrantedAuthority(role.getRole()));
logger.info(role+ role +role.getRole()+(role.getRole()));
}

返回新的org.springframework.security.core.userdetails.User(
domainUser.getName(),
domainUser.getPassword(),
)domainUser.isEnabled(),
domainUser.isAccountNonExpired(),
domainUser.isCredentialsNonExpired(),
domainUser.isAccountNonLocked(),
authorities);

来自db的查询

  @SuppressWarnings(unchecked)
public User getUser(String name){

List< User> userList = new ArrayList< User>();
Query query = sessionFactory.getCurrentSession()。createQuery(from User u where u.name =:name);
query.setParameter(name,name);
userList = query.list();
if(userList.size()> 0)
return userList.get(0);
else
返回null;
}

任何人都可以帮助解决这个问题吗?

spring-security.xml

 < http auto-config =true> 
< intercept-url pattern =/ forms / welcome *access =ROLE_ADMIN/>
<! - 下面的配置将显示用于认证的自定义表单 - >
authentication-failure-url =/ forms / loginfailed/>
< logout logout-success-url =/ forms / logout/>
<! - < http-basic /> - >
< / http>


< authentication-manager>
< authentication-provider user-service-ref =myUserDetailService>
< / authentication-provider>
< / authentication-manager>


解决方案

您不会发布您的安全配置。我假设你已经在 DaoAuthenticationProvider 中设置了一个标准配置,你已经可以用用户名登录了。

我看到这种特殊情况只有一个修改,允许使用用户名或电子邮件登录。在您的hibernate查询中添加一个谓词,以便通过电子邮件查询用户。我假设你的实体有一个来自用户的属性 email

  u其中u.name =:name或u.email =:name


I have a user bean with fields like userName, profileName, email etc.

I am implementing Spring Security in my application. In the login form I want the user to enter either profileName or email & he should be able to login with both. But it seems like the configuration only works for userName. I am fetching the user details from database using hibernate. Below is my code

FormLogin.jsp

<form name='f' action="<c:url value='j_spring_security_check' />"
        method='POST'>

        <table>
            <tr>
                <td>Email/ProfileName</td>
                <td><input type='text' name='j_username' value=''>
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='j_password' />
                </td>
            </tr>
            <tr>
                <td colspan='2'><input name="submit" type="submit"
                    value="submit" />
                </td>
            </tr>
            <tr>
                <td colspan='2'><input name="reset" type="reset" />
                </td>
            </tr>
        </table>

    </form> 

loadByUserName method in CustomUserDetailsService class

public UserDetails loadUserByUsername(String name)throws UsernameNotFoundException, DataAccessException 
    {

        //returns the get(0) of the user list obtained from the db
        User domainUser = userDAO.getUser(name);
        logger.info("User fetched from database in loadUserByUsername method " + domainUser);

        Set<Roles> roles = domainUser.getRole();
        logger.info("roles of the user"+ roles);


        Set<GrantedAuthority> authorities = new HashSet<>();
        for(Roles role:roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRole()));
            logger.info("role" +role+" role.getRole()"+(role.getRole()));
        }

        return new org.springframework.security.core.userdetails.User(
                domainUser.getName(),
                domainUser.getPassword(),
                domainUser.isEnabled(),
                domainUser.isAccountNonExpired(),
                domainUser.isCredentialsNonExpired(),
                domainUser.isAccountNonLocked(),
                authorities);
}

Query from the db

@SuppressWarnings("unchecked")
    public User getUser(String name){

        List<User> userList = new ArrayList<User>(); 
        Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.name = :name");
        query.setParameter("name", name);
        userList = query.list();  
        if (userList.size() > 0)  
            return userList.get(0);  
        else  
            return null; 
    }

Can anyone help in fixing this?

spring-security.xml

<http auto-config="true">
        <intercept-url pattern="/forms/welcome*" access="ROLE_ADMIN" />
        <!-- Below config will display the custom form for authentication -->
        <form-login login-page="/forms/login" default-target-url="/forms/welcome"
            authentication-failure-url="/forms/loginfailed" />
        <logout logout-success-url="/forms/logout" />
    <!--    <http-basic /> -->
    </http> 


    <authentication-manager>
        <authentication-provider user-service-ref="myUserDetailService">
          </authentication-provider>
    </authentication-manager>

解决方案

You don't post your security configuration. I assume that you have setup a standard configuration with DaoAuthenticationProvider in place and you are already able to login with username.

I this particular case I see only one modification to allow login with either username or email. Add a or predicate to your hibernate query that queries for user by email too. I assume that your entity has a property email.

"from User u where u.name = :name or u.email = :name"

这篇关于在Spring Security中使用配置文件名称或电子邮件登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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