今天跟着这位博主学习了后端注册加密和登陆解密功能。
1.说实话,我没搞懂Shiro框架在springboot中的运用。所以我上代码给自己记录一下自己干了什么:
首先是realm包的Realm类:
package realm;
import com.example.demo.User.User;
import com.example.demo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
public class Realm extends AuthorizingRealm {
@Autowired
private UserService userService;
// 简单重写获取授权信息方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection){
SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
return s;
}
// 获取认证信息,即根据 token 中的用户名从数据库中获取密码、盐等并返回
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{
String userName = token.getPrincipal().toString();
User user = userService.getByName(userName);
if(ObjectUtils.isEmpty(user)){
throw new UnknownAccountException();
}
String passwordInDB = user.getPassword();
String salt = user.getSalt();
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName,passwordInDB, ByteSource.Util.bytes(salt),getName());
return authenticationInfo ;
}
}
接着是User类添加了新的属性:
然后是result包的三个类:
package com.example.demo.result;
public class Result {
private int code;
private String message;
private Object data;
Result(int code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object get