当前位置: 代码网 > it编程>编程语言>Java > Spring Security中用户名和密码的验证完整流程

Spring Security中用户名和密码的验证完整流程

2025年06月27日 Java 我要评论
首先创建了一个usernamepasswordauthenticationtoken对象,这是spring security中用于表示基于用户名和密码的认证请求的一个类。这个对象被初始化时,接收了两个

首先创建了一个usernamepasswordauthenticationtoken对象,这是spring security中用于表示基于用户名和密码的认证请求的一个类。这个对象被初始化时,接收了两个参数:username(用户名)和password(密码)。这两个参数代表了用户尝试登录时提供的凭证。

接下来,通过调用authenticationmanager的authenticate方法,并传入前面创建的authenticationtoken对象,来执行认证过程。authenticationmanager是spring security中的一个核心接口,它负责处理认证请求。在调用authenticate方法时,spring security会基于配置的安全策略(比如从数据库、ldap服务器或其他认证源中检索用户信息,并验证提供的密码是否正确)来验证用户提供的凭证是否有效
如果认证成功,authenticate方法会返回一个填充了用户权限等详细信息的authentication对象。这个对象代表了认证成功后的用户会话,包含了用户的身份信息、权限、是否已记住我(remember-me)等详细信息。

如果认证失败,authenticate方法会抛出一个authenticationexception异常,这通常意味着提供的用户名或密码不正确,或者用户账户处于锁定、禁用等状态。

  /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public string login(string username, string password, string code, string uuid)
    {
        // 验证码校验
        validatecaptcha(username, code, uuid);
        // 登录前置校验
        loginprecheck(username, password);
        // 用户验证
        authentication authentication = null;
        try
        {
            usernamepasswordauthenticationtoken authenticationtoken = new usernamepasswordauthenticationtoken(username, password);
            authenticationcontextholder.setcontext(authenticationtoken);
            // 该方法会去调用userdetailsserviceimpl.loaduserbyusername
            authentication = authenticationmanager.authenticate(authenticationtoken);
        }
        catch (exception e)
        {
            if (e instanceof badcredentialsexception)
            {
                asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_fail, messageutils.message("user.password.not.match")));
                throw new userpasswordnotmatchexception();
            }
            else
            {
                asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_fail, e.getmessage()));
                throw new serviceexception(e.getmessage());
            }
        }
        finally
        {
            //清理认证上下文,确保线程上下文中的认证信息被清除,避免潜在的内存泄漏或安全问题
            authenticationcontextholder.clearcontext();
        }
        asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_success, messageutils.message("user.login.success")));
        //从认证成功的authentication对象中获取principal,并将其强制转换为loginuser对象。loginuser是一个自定义类,通常包含用户的基本信息和权限信息
        loginuser loginuser = (loginuser) authentication.getprincipal();
         //调用recordlogininfo方法记录用户的登录信息,例如登录时间、ip地址等
        recordlogininfo(loginuser.getuserid());
        // 生成token,为用户生成一个token,并返回该token。token通常用于后续的用户身份验证和授权
        return tokenservice.createtoken(loginuser);
    }

验证码校验方法

 /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validatecaptcha(string username, string code, string uuid)
    {
        boolean captchaenabled = configservice.selectcaptchaenabled();
        if (captchaenabled)
        {
            string verifykey = cacheconstants.captcha_code_key + stringutils.nvl(uuid, "");
            string captcha = rediscache.getcacheobject(verifykey);
            if (captcha == null)
            {
                asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_fail, messageutils.message("user.jcaptcha.expire")));
                throw new captchaexpireexception();
            }
            rediscache.deleteobject(verifykey);
            if (!code.equalsignorecase(captcha))
            {
                asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_fail, messageutils.message("user.jcaptcha.error")));
                throw new captchaexception();
            }
        }
    }

用户名和密码校验代码

 /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginprecheck(string username, string password)
    {
        // 用户名或密码为空 错误
        if (stringutils.isempty(username) || stringutils.isempty(password))
        {
            asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_fail, messageutils.message("not.null")));
            throw new usernotexistsexception();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < userconstants.password_min_length
                || password.length() > userconstants.password_max_length)
        {
            asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_fail, messageutils.message("user.password.not.match")));
            throw new userpasswordnotmatchexception();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < userconstants.username_min_length
                || username.length() > userconstants.username_max_length)
        {
            asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_fail, messageutils.message("user.password.not.match")));
            throw new userpasswordnotmatchexception();
        }
        // ip黑名单校验
        string blackstr = configservice.selectconfigbykey("sys.login.blackiplist");
        if (iputils.ismatchedip(blackstr, iputils.getipaddr()))
        {
            asyncmanager.me().execute(asyncfactory.recordlogininfor(username, constants.login_fail, messageutils.message("login.blocked")));
            throw new blacklistexception();
        }
    }

记录登录信息代码

 /**
     * 记录登录信息
     *
     * @param userid 用户id
     */
    public void recordlogininfo(long userid)
    {
        sysuser sysuser = new sysuser();
        sysuser.setuserid(userid);
        sysuser.setloginip(iputils.getipaddr());
        sysuser.setlogindate(dateutils.getnowdate());
        userservice.updateuserprofile(sysuser);
    }

userdetailsserviceimpl实现类的代码,userdetailsservice是java自带的类,userdetailsserviceimpl继承userdetailsservice的loaduserbyusername方法 

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@service
public class userdetailsserviceimpl implements userdetailsservice
{
    private static final logger log = loggerfactory.getlogger(userdetailsserviceimpl.class);
    @autowired
    private isysuserservice userservice;
    @autowired
    private syspasswordservice passwordservice;
    @autowired
    private syspermissionservice permissionservice;
    @override
    public userdetails loaduserbyusername(string username) throws usernamenotfoundexception
    {
        sysuser user = userservice.selectuserbyusername(username);
        if (stringutils.isnull(user))
        {
            log.info("登录用户:{} 不存在.", username);
            throw new serviceexception(messageutils.message("user.not.exists"));
        }
        else if (userstatus.deleted.getcode().equals(user.getdelflag()))
        {
            log.info("登录用户:{} 已被删除.", username);
            throw new serviceexception(messageutils.message("user.password.delete"));
        }
        else if (userstatus.disable.getcode().equals(user.getstatus()))
        {
            log.info("登录用户:{} 已被停用.", username);
            throw new serviceexception(messageutils.message("user.blocked"));
        }
        passwordservice.validate(user);
        return createloginuser(user);
    }
    public userdetails createloginuser(sysuser user)
    {
        return new loginuser(user.getuserid(), user.getdeptid(), user, permissionservice.getmenupermission(user));
    }
}

到此这篇关于在spring security中,用户名和密码的验证流程的文章就介绍到这了,更多相关spring security用户名和密码验证内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com