在某些场景下(例如短信验证码、第三方应用登录等),需要实现用户免密登录功能。本文介绍了在若依框架中如何配置和实现用户免密登录的方法。
Token
,包含登录类型。Realm
中添加登录类型判断,处理不同的登录逻辑。LoginService
中添加免密码登录的方法。ruoyi
├── ruoyi-admin
│ └── src/main/java
│ └── com/ruoyi/web
│ └── controller
└──ruoyi-framework
└── src/main/java
└── com/ruoyi/framework
└── shiro
├── token
│ ├── LoginType.java
│ └── UserToken.java
├── realm
│ └── UserRealm.java
└── service
└── SysLoginService.java
Shiro
配置正确,能够识别自定义的UserToken
。package com.ruoyi.framework.shiro.token;
/**
* 登录类型枚举类
*/
public enum LoginType {
/**
* 密码登录
*/
PASSWORD("password"),
/**
* 免密码登录
*/
NOPASSWD("nopasswd");
private String desc;
LoginType(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
}
package com.ruoyi.framework.shiro.token;
import org.apache.shiro.authc.UsernamePasswordToken;
/**
* 自定义登录Token
*/
public class UserToken extends UsernamePasswordToken {
private static final long serialVersionUID = 1L;
private LoginType type;
public UserToken() {
}
public UserToken(String username, String password, LoginType type, boolean rememberMe) {
super(username, password, rememberMe);
this.type = type;
}
public UserToken(String username, LoginType type) {
super(username, "", false, null);
this.type = type;
}
public UserToken(String username, String password, LoginType type) {
super(username, password, false, null);
this.type = type;
}
public LoginType getType() {
return type;
}
public void setType(LoginType type) {
this.type = type;
}
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UserToken upToken = (UserToken) token;
LoginType type = upToken.getType();
String username = upToken.getUsername();
String password = "";
if (upToken.getPassword() != null) {
password = new String(upToken.getPassword());
}
User user = null;
try {
if (LoginType.PASSWORD.equals(type)) {
user = loginService.login(username, password);
} else if (LoginType.NOPASSWD.equals(type)) {
user = loginService.login(username);
}
} catch (Exception e) {
log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage());
throw new AuthenticationException(e.getMessage(), e);
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}
public User login(String username) {
if (StringUtils.isEmpty(username)) {
throw new UserNotExistsException();
}
User user = userService.selectUserByLoginName(username);
if (user == null) {
throw new UserNotExistsException();
}
if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
throw new UserDeleteException();
}
if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
throw new UserBlockedException();
}
recordLoginInfo(user);
return user;
}
UserToken token = new UserToken(username, LoginType.NOPASSWD);
Subject subject = SecurityUtils.getSubject();
subject.login(token);
配置完成后,用户可以通过免密码方式登录系统。具体的登录流程如下:
1. 用户输入用户名。
2. 系统识别为免密码登录类型。
3. 系统验证用户名的有效性。
4. 用户成功登录,返回用户信息。
通过上述配置,若依框架实现了用户免密登录的功能。
powered by kaifamiao