modify: 修改shiro

This commit is contained in:
wuy 2019-10-15 17:19:46 +08:00
parent 054e5a28f4
commit ca7981de33
19 changed files with 289 additions and 47 deletions

View File

@ -4,8 +4,10 @@ import com.diboot.core.config.BaseConfig;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Status;
import com.diboot.example.enums.UserTypeEnum;
import com.diboot.shiro.config.AuthType;
import com.diboot.shiro.entity.SysUser;
import com.diboot.shiro.entity.TokenAccountInfo;
import com.diboot.shiro.jwt.BaseJwtAuthenticationToken;
import com.diboot.shiro.service.AuthWayService;
import com.diboot.shiro.service.SysUserService;
@ -54,7 +56,7 @@ public class AuthTokenController {
@PostMapping("/register")
public JsonResult register(@RequestBody SysUser sysUser, HttpServletRequest request, HttpServletResponse response) throws Exception {
String password = sysUser.getPassword();
boolean register = sysUserService.register(sysUser);
boolean register = sysUserService.register(sysUser, UserTypeEnum.SYS_USER);
if (register) {
//注册成功后自动登陆:注册后密码被加密重新设置为不加密的密码然后进行登陆
sysUser.setPassword(password);
@ -74,12 +76,12 @@ public class AuthTokenController {
public JsonResult login(@RequestBody SysUser sysUser, HttpServletRequest request, HttpServletResponse response) throws Exception{
String errorMsg = "登录失败";
try{
BaseJwtAuthenticationToken authToken = new BaseJwtAuthenticationToken(authWayServiceMap, sysUser.getUsername(), sysUser.getPassword(), AuthType.USERNAME_PASSWORD);
BaseJwtAuthenticationToken authToken = new BaseJwtAuthenticationToken(authWayServiceMap, sysUser.getUsername(), sysUser.getPassword(), AuthType.USERNAME_PASSWORD, UserTypeEnum.SYS_USER);
Subject subject = SecurityUtils.getSubject();
subject.login(authToken);
if (subject.isAuthenticated()){
logger.debug("申请token成功authtoken="+authToken.getCredentials());
logger.debug("申请token成功authtoken={}", authToken.getCredentials());
String token = (String)authToken.getCredentials();
// 跳转到首页
return new JsonResult(token, "Token申请成功");
@ -123,14 +125,14 @@ public class AuthTokenController {
HttpServletRequest request) throws Exception{
String openid = "";
if (JwtHelper.isRequestTokenEffective(request)){
String account = JwtHelper.getAccountFromToken(JwtHelper.getRequestToken(request));
if (account == null){
TokenAccountInfo account = JwtHelper.getAccountFromToken(JwtHelper.getRequestToken(request));
if (V.isEmpty(account)){
// 如果有code并且token已过期则使用code获取openid
if (V.isEmpty(code)){
return new JsonResult(Status.FAIL_INVALID_TOKEN, new String[]{"token已过期"});
}
} else {
openid = account;
openid = account.getAccount();
}
}
@ -156,7 +158,7 @@ public class AuthTokenController {
}
// 设置token
BaseJwtAuthenticationToken authToken = new BaseJwtAuthenticationToken(authWayServiceMap, openid, AuthType.WX_MP);
BaseJwtAuthenticationToken authToken = new BaseJwtAuthenticationToken(authWayServiceMap, openid, AuthType.WX_MP, UserTypeEnum.WX_MP_USER);
// 获取当前的Subject
Subject subject = SecurityUtils.getSubject();
String token = null;

View File

@ -19,10 +19,12 @@ import com.diboot.shiro.authz.annotation.AuthorizationPrefix;
import com.diboot.shiro.authz.annotation.AuthorizationWrapper;
import com.diboot.shiro.entity.Permission;
import com.diboot.shiro.entity.Role;
import com.diboot.shiro.entity.TokenAccountInfo;
import com.diboot.shiro.service.PermissionService;
import com.diboot.shiro.service.RoleService;
import com.diboot.shiro.util.JwtHelper;
import com.diboot.shiro.vo.RoleVO;
import com.sun.tools.internal.ws.wscompile.AuthInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -208,14 +210,15 @@ public class SysUserController extends BaseCrudRestController {
return new JsonResult(Status.FAIL_OPERATION, new String[]{"获取数据失败"});
}
String username = JwtHelper.getAccountFromToken(token);
if (V.isEmpty(username)){
TokenAccountInfo account = JwtHelper.getAccountFromToken(token);
if (V.isEmpty(account)){
return new JsonResult(Status.FAIL_OPERATION, new String[]{"获取数据失败"});
}
QueryWrapper<SysUser> query = new QueryWrapper<>();
query.lambda()
.eq(SysUser::getUsername, username);
.eq(SysUser::getUsername, account.getAccount())
.eq(SysUser::getUserType, account.getUserType());
List<SysUser> userList = sysUserService.getEntityList(query);
if (V.isEmpty(userList)){
return new JsonResult(Status.FAIL_OPERATION, new String[]{"获取数据失败"});

View File

@ -0,0 +1,41 @@
package com.diboot.example.enums;
import com.diboot.shiro.enums.IUserType;
/**
* 系统用户枚举类
*
* @author : wee
* @version : v2.0
* @Date 2019-10-14 18:15
*/
public enum UserTypeEnum implements IUserType {
SYS_USER("MS_USER", "系统用户"),
WX_MP_USER("WX_MP", "服务号用户"),
;
/**
* 用户类型
*/
private String type;
/**
* 描述
*/
private String description;
UserTypeEnum(String type, String description) {
this.type = type;
this.description = description;
}
@Override
public String getType() {
return this.type;
}
public String getDescription() {
return this.description;
}}

View File

@ -4,10 +4,12 @@ import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Status;
import com.diboot.shiro.config.AuthType;
import com.diboot.shiro.entity.TokenAccountInfo;
import com.diboot.shiro.jwt.BaseJwtAuthenticationToken;
import com.diboot.shiro.service.AuthWayService;
import com.diboot.shiro.util.JwtHelper;
import com.diboot.shiro.wx.cp.config.WxCpConfig;
import com.diboot.shiro.wx.cp.enums.UserTypeEnum;
import com.diboot.shiro.wx.cp.service.impl.WxCpServiceExtImpl;
import me.chanjar.weixin.common.api.WxConsts;
import org.apache.shiro.SecurityUtils;
@ -59,14 +61,14 @@ public class CpAuthTokenController {
public JsonResult applyTokenByOAuth2cp(@RequestParam("code") String code, HttpServletRequest request) throws Exception{
String userId = "";
if (JwtHelper.isRequestTokenEffective(request)){
String account = JwtHelper.getAccountFromToken(JwtHelper.getRequestToken(request));
if (account == null){
TokenAccountInfo account = JwtHelper.getAccountFromToken(JwtHelper.getRequestToken(request));
if (V.isEmpty(account)){
// 如果有code并且token已过期则使用code获取userId
if (V.isEmpty(code)){
return new JsonResult(Status.FAIL_INVALID_TOKEN, new String[]{"token已过期"});
}
} else {
userId = account;
userId = account.getAccount();
}
}
@ -86,7 +88,7 @@ public class CpAuthTokenController {
}
// 设置token
BaseJwtAuthenticationToken authToken = new BaseJwtAuthenticationToken(authWayServiceMap, userId, AuthType.WX_CP);
BaseJwtAuthenticationToken authToken = new BaseJwtAuthenticationToken(authWayServiceMap, userId, AuthType.WX_CP, UserTypeEnum.WX_CP_USER);
// 获取当前的Subject
Subject subject = SecurityUtils.getSubject();
String token = null;

View File

@ -0,0 +1,40 @@
package com.diboot.shiro.wx.cp.enums;
import com.diboot.shiro.enums.IUserType;
/**
* 系统用户枚举类
*
* @author : wee
* @version : v2.0
* @Date 2019-10-14 18:15
*/
public enum UserTypeEnum implements IUserType {
WX_CP_USER("WX_CP", "企业号用户"),
;
/**
* 用户类型
*/
private String type;
/**
* 描述
*/
private String description;
UserTypeEnum(String type, String description) {
this.type = type;
this.description = description;
}
@Override
public String getType() {
return this.type;
}
public String getDescription() {
return this.description;
}}

View File

@ -1,9 +1,12 @@
package com.diboot.shiro.wx.cp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.diboot.core.entity.BaseEntity;
import com.diboot.core.util.V;
import com.diboot.shiro.config.AuthType;
import com.diboot.shiro.enums.IUserType;
import com.diboot.shiro.jwt.BaseJwtAuthenticationToken;
import com.diboot.shiro.service.AuthWayService;
import com.diboot.shiro.wx.cp.entity.WxCpMember;
@ -41,11 +44,9 @@ public class WxCpAuthWayServiceImpl implements AuthWayService {
@Override
public BaseEntity getUser() {
QueryWrapper<WxCpMember> query = new QueryWrapper();
query.lambda()
LambdaQueryWrapper<WxCpMember> queryWrapper = Wrappers.<WxCpMember>lambdaQuery()
.eq(WxCpMember::getUserId, token.getAccount());
List<WxCpMember> wxCpMemberList = wxCpMemberService.getEntityList(query);
List<WxCpMember> wxCpMemberList = wxCpMemberService.getEntityList(queryWrapper);
if (V.isEmpty(wxCpMemberList)){
return null;
}

View File

@ -2,6 +2,7 @@ package com.diboot.shiro.wx.mp.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.diboot.core.entity.BaseEntity;
import com.diboot.shiro.entity.SysUser;
import lombok.Data;
/***
@ -17,4 +18,13 @@ public class WxMpMember extends BaseEntity {
@TableField
private String openid;
/**
* 绑定用户的认证
*/
@TableField
private Long sysUserId;
@TableField(exist = false)
private SysUser sysUser;
}

View File

@ -1,11 +1,18 @@
package com.diboot.shiro.wx.mp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.diboot.core.entity.BaseEntity;
import com.diboot.core.util.V;
import com.diboot.core.vo.Status;
import com.diboot.shiro.config.AuthType;
import com.diboot.shiro.entity.SysUser;
import com.diboot.shiro.enums.IUserType;
import com.diboot.shiro.exception.ShiroCustomException;
import com.diboot.shiro.jwt.BaseJwtAuthenticationToken;
import com.diboot.shiro.service.AuthWayService;
import com.diboot.shiro.service.SysUserService;
import com.diboot.shiro.wx.mp.entity.WxMpMember;
import com.diboot.shiro.wx.mp.service.WxMpMemberService;
import org.springframework.beans.factory.annotation.Autowired;
@ -25,6 +32,9 @@ public class WxMpAuthWayServiceImpl implements AuthWayService {
@Autowired
private WxMpMemberService wxMpMemberService;
@Autowired
private SysUserService sysUserService;
private AuthType authType = AuthType.WX_MP;
private BaseJwtAuthenticationToken token;
@ -41,15 +51,21 @@ public class WxMpAuthWayServiceImpl implements AuthWayService {
@Override
public BaseEntity getUser() {
QueryWrapper<WxMpMember> query = new QueryWrapper();
query.lambda()
LambdaQueryWrapper<WxMpMember> query = Wrappers.<WxMpMember>lambdaQuery()
.eq(WxMpMember::getOpenid, token.getAccount());
List<WxMpMember> wxMpMemberList = wxMpMemberService.getEntityList(query);
if (V.isEmpty(wxMpMemberList)){
return null;
}
return wxMpMemberList.get(0);
WxMpMember wxMpMember = wxMpMemberList.get(0);
//绑定账户
if (V.notEmpty(wxMpMember.getSysUserId())) {
SysUser sysUser = sysUserService.getEntity(wxMpMember.getSysUserId());
if (V.isEmpty(sysUser)) {
throw new ShiroCustomException(Status.FAIL_NO_PERMISSION, "绑定用户后登陆");
}
}
return wxMpMember;
}
@Override

View File

@ -4,6 +4,7 @@ import com.diboot.core.util.V;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@ -22,7 +23,10 @@ public class StorageListener implements ApplicationListener<ContextRefreshedEven
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (V.isEmpty(event.getApplicationContext().getParent())) {
//容器加载多次需要判断根容器父级是不是为空或者祖父级别为空的时候
ApplicationContext parent = event.getApplicationContext().getParent();
if (V.isEmpty(parent) ||
(V.notEmpty(parent) && V.isEmpty(parent.getParent()))){
authorizationStorage.autoStorage(event.getApplicationContext());
}
}

View File

@ -20,18 +20,42 @@ public class SysUser extends BaseEntity {
@TableField
private Long departmentId;
/**
* 用户名
*/
@TableField
private String username;
/**
* 密码
*/
@TableField
private String password;
/**
* 性别
*/
@TableField
private String gender;
/**
* 加密盐
*/
@TableField
private String salt;
/**
* 用户类型
*/
@TableField
private String userType = "MS";
/**
* 用户id
*/
@TableField
private Long userId;
@TableField(exist = false)
private List<Role> roleList;

View File

@ -0,0 +1,28 @@
package com.diboot.shiro.entity;
import lombok.*;
import java.io.Serializable;
/**
* token中的用户信息
* @author : wee
* @version : v2.0
* @Date 2019-10-14 18:31
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TokenAccountInfo implements Serializable {
private static final long serialVersionUID = 8134572626042791766L;
/**
* 账号
*/
private String account;
/**
* 用户类型
*/
private String userType;
}

View File

@ -0,0 +1,19 @@
package com.diboot.shiro.enums;
/**
* 用户类型枚举接口
*
* @author : wee
* @version : v2.0
* @Date 2019-10-14 17:05
*/
public interface IUserType {
/**
* 用户类型
* @return
*/
String getType();
}

View File

@ -4,6 +4,7 @@ import com.diboot.core.util.JSON;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Status;
import com.diboot.shiro.entity.TokenAccountInfo;
import com.diboot.shiro.util.JwtHelper;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
@ -36,13 +37,13 @@ public class BaseJwtAuthenticationFilter extends BasicHttpAuthenticationFilter {
// 获取Token
String accessToken = JwtHelper.getRequestToken(httpRequest);
if (V.isEmpty(accessToken)) {
logger.warn("Token为空url="+httpRequest.getRequestURL());
logger.warn("Token为空url={}", httpRequest.getRequestURL());
return false;
}
//获取username
String account = JwtHelper.getAccountFromToken(accessToken);
TokenAccountInfo account = JwtHelper.getAccountFromToken(accessToken);
if(V.notEmpty(account)){
logger.debug("Token认证成功account="+account);
logger.debug("Token认证成功account={}", account.toString());
return true;
}
logger.debug("Token认证失败");

View File

@ -1,7 +1,10 @@
package com.diboot.shiro.jwt;
import com.diboot.core.util.JSON;
import com.diboot.core.util.V;
import com.diboot.shiro.config.AuthType;
import com.diboot.shiro.entity.TokenAccountInfo;
import com.diboot.shiro.enums.IUserType;
import com.diboot.shiro.service.AuthWayService;
import com.diboot.shiro.util.JwtHelper;
import org.apache.shiro.authc.AuthenticationToken;
@ -9,6 +12,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
@ -30,6 +34,11 @@ public class BaseJwtAuthenticationToken implements AuthenticationToken {
/**登录使用方式*/
private AuthType authType;
/**
* 用户类型枚举
*/
private IUserType iUserType;
/**authz token*/
private String authtoken;
@ -55,44 +64,54 @@ public class BaseJwtAuthenticationToken implements AuthenticationToken {
/***
* 用户名码形式的授权
* @param authWayServiceMap //所有认证业务service
* @param account
* @param password
* @param iUserType //用户类型
*/
public BaseJwtAuthenticationToken(Map<String, AuthWayService> authWayServiceMap, String account, String password){
public BaseJwtAuthenticationToken(Map<String, AuthWayService> authWayServiceMap, String account, String password, IUserType iUserType){
this.authWayServiceMap = authWayServiceMap;
this.account = account;
this.password = password;
// 设置为默认登录方式
this.authType = AuthType.USERNAME_PASSWORD;
this.iUserType = iUserType;
this.initJwtAuthenticationToken(account, signKey, false);
}
/***
* 以用户名密码这类形式的其他类型授权
* @param authWayServiceMap //所有认证业务service map
* @param account
* @param password
* @param authType
* @param authType //具体认证业务类型
* @param iUserType
*/
public BaseJwtAuthenticationToken(Map<String, AuthWayService> authWayServiceMap, String account, String password, AuthType authType){
public BaseJwtAuthenticationToken(Map<String, AuthWayService> authWayServiceMap,
String account, String password, AuthType authType, IUserType iUserType){
this.authWayServiceMap = authWayServiceMap;
this.account = account;
this.password = password;
this.authType = authType;
this.iUserType = iUserType;
this.initJwtAuthenticationToken(account, signKey, getAuthWayService().isPreliminaryVerified());
}
/***
* 其他授权种类的适配构造函数
* @param authWayServiceMap
* @param account
* @param authType
* @param iUserType
*/
public BaseJwtAuthenticationToken(Map<String, AuthWayService> authWayServiceMap, String account, AuthType authType){
public BaseJwtAuthenticationToken(Map<String, AuthWayService> authWayServiceMap,
String account, AuthType authType, IUserType iUserType){
this.authWayServiceMap = authWayServiceMap;
this.account = account;
this.authType = authType;
this.iUserType = iUserType;
this.initJwtAuthenticationToken(account, signKey, getAuthWayService().isPreliminaryVerified());
}
@ -120,7 +139,8 @@ public class BaseJwtAuthenticationToken implements AuthenticationToken {
if(this.account != null){
Long expiresInMinutes = this.getAuthWayService().getExpiresInMinutes();
this.expiresInMinutes = V.notEmpty(expiresInMinutes) ? expiresInMinutes : this.expiresInMinutes;
this.authtoken = JwtHelper.generateToken(this.account, this.signKey, this.expiresInMinutes);
String user = JSON.stringify(new TokenAccountInfo(this.account, this.iUserType.getType()));
this.authtoken = JwtHelper.generateToken(user, this.signKey, this.expiresInMinutes);
}
}
@ -204,4 +224,12 @@ public class BaseJwtAuthenticationToken implements AuthenticationToken {
public void setAuthWayServiceMap(Map<String, AuthWayService> authWayServiceMap) {
this.authWayServiceMap = authWayServiceMap;
}
public IUserType getIUserType() {
return iUserType;
}
public void setIUserType(IUserType iUserType) {
this.iUserType = iUserType;
}
}

View File

@ -2,6 +2,7 @@ package com.diboot.shiro.service;
import com.diboot.core.entity.BaseEntity;
import com.diboot.shiro.config.AuthType;
import com.diboot.shiro.enums.IUserType;
import com.diboot.shiro.jwt.BaseJwtAuthenticationToken;
/***
@ -25,7 +26,7 @@ public interface AuthWayService {
void initByToken(BaseJwtAuthenticationToken token);
/***
* 获取用户信息
* 根据用户类型获取用户信息
* @return
*/
BaseEntity getUser();

View File

@ -2,6 +2,7 @@ package com.diboot.shiro.service;
import com.diboot.core.service.BaseService;
import com.diboot.shiro.entity.SysUser;
import com.diboot.shiro.enums.IUserType;
/**
* 用户相关Service
@ -14,9 +15,10 @@ public interface SysUserService extends BaseService<SysUser> {
/**
* 注册用户
* @param sysUser
* @param iUserType 用户类型
* @return
* @throws Exception
*/
boolean register(SysUser sysUser) throws Exception;
boolean register(SysUser sysUser, IUserType iUserType) throws Exception;
}

View File

@ -6,6 +6,7 @@ import com.diboot.core.service.impl.BaseServiceImpl;
import com.diboot.core.util.V;
import com.diboot.core.vo.Status;
import com.diboot.shiro.entity.SysUser;
import com.diboot.shiro.enums.IUserType;
import com.diboot.shiro.exception.ShiroCustomException;
import com.diboot.shiro.mapper.SysUserMapper;
import com.diboot.shiro.service.SysUserService;
@ -31,13 +32,15 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser>
* @throws Exception
*/
@Override
public boolean register(SysUser sysUser) throws Exception {
public boolean register(SysUser sysUser, IUserType iUserType) throws Exception {
if (V.isEmpty(sysUser.getUsername()) || V.isEmpty(sysUser.getPassword())) {
throw new ShiroCustomException(Status.FAIL_INVALID_PARAM, "用户名密码不能为空!");
}
LambdaQueryWrapper<SysUser> wrapper = Wrappers.<SysUser>lambdaQuery()
.eq(SysUser::getUsername, sysUser.getUsername());
.eq(SysUser::getUsername, sysUser.getUsername())
.eq(SysUser::getUserType, iUserType.getType())
;
SysUser dbSysUser = getOne(wrapper);
//校验数据库中数据是否已经存在
if (V.notEmpty(dbSysUser)) {

View File

@ -1,17 +1,23 @@
package com.diboot.shiro.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.diboot.core.entity.BaseEntity;
import com.diboot.core.util.V;
import com.diboot.shiro.config.AuthType;
import com.diboot.shiro.entity.SysUser;
import com.diboot.shiro.enums.IUserType;
import com.diboot.shiro.jwt.BaseJwtAuthenticationToken;
import com.diboot.shiro.service.AuthWayService;
import com.diboot.shiro.service.SysUserService;
import com.diboot.shiro.util.AuthHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
/***
@ -23,6 +29,8 @@ import java.util.List;
@Service
public class UsernamePasswordAuthWayServiceImpl implements AuthWayService {
private final Logger logger = LoggerFactory.getLogger(UsernamePasswordAuthWayServiceImpl.class);
@Autowired
private SysUserService sysUserService;
@ -42,9 +50,10 @@ public class UsernamePasswordAuthWayServiceImpl implements AuthWayService {
@Override
public BaseEntity getUser() {
QueryWrapper<SysUser> query = new QueryWrapper();
query.lambda()
.eq(SysUser::getUsername, token.getAccount());
logger.debug("【获取用户】==>当前 登陆用户:{}-{}", token.getAccount(), token.getIUserType().getType());
LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery()
.eq(SysUser::getUsername, token.getAccount())
.eq(SysUser::getUserType, token.getIUserType().getType());
List<SysUser> userList = sysUserService.getEntityList(query);
if (V.isEmpty(userList)){
return null;

View File

@ -1,7 +1,9 @@
package com.diboot.shiro.util;
import com.diboot.core.config.BaseConfig;
import com.diboot.core.util.JSON;
import com.diboot.core.util.V;
import com.diboot.shiro.entity.TokenAccountInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@ -30,12 +32,18 @@ public class JwtHelper {
private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256;
/***
* 从token中获取用户名
* 从token中获取用户名 + 用户类型
* <br>
* 返回格式
* <code>{username:xxx, userType:xxx}</code>
* @param token
* @return
*/
public static String getAccountFromToken(String token){
return getAccountFromToken(token, SIGN_KEY);
public static TokenAccountInfo getAccountFromToken(String token){
// {}
String accountFromToken = getAccountFromToken(token, SIGN_KEY);
TokenAccountInfo tokenAccountInfo = JSON.toJavaObject(accountFromToken, TokenAccountInfo.class);
return tokenAccountInfo;
}
/***
@ -50,15 +58,15 @@ public class JwtHelper {
// 校验过期时间
if(claims.getExpiration().getTime() >= System.currentTimeMillis()){
username = claims.getSubject();
logger.debug("token有效username=" + username);
logger.debug("token有效用户信息={}", username);
}
else{
logger.warn("token已过期:" + token);
logger.warn("token已过期:{}", token);
username = null;
}
}
catch (Exception e) {
logger.warn("解析token异常无效的token:" + token);
logger.warn("解析token异常无效的token:{}", token);
username = null;
}
return username;
@ -86,7 +94,7 @@ public class JwtHelper {
public static boolean isRequestTokenEffective(HttpServletRequest request){
String authToken = getRequestToken(request);
if(V.notEmpty(authToken)){
String account = getAccountFromToken(authToken);
TokenAccountInfo account = getAccountFromToken(authToken);
return V.notEmpty(account);
}
return false;
@ -122,7 +130,7 @@ public class JwtHelper {
* @param expiresInMinutes
* @return
*/
public static String generateToken(String user, String issuer, SignatureAlgorithm signAlgorithm, String signKey, long expiresInMinutes) {
public static String generateToken(String user,String issuer, SignatureAlgorithm signAlgorithm, String signKey, long expiresInMinutes) {
Date currentTime = generateCurrentDate();
Date expiration = generateExpirationDate(currentTime, expiresInMinutes);
String jwsToken = Jwts.builder()