其他分享
首页 > 其他分享> > jwt 实现移动端token认证

jwt 实现移动端token认证

作者:互联网

登录成功 创建token
String token = JwtUtils.create(customer.getCompanyId(), customer.getId(), mobile);

需要认证的接口加上认证注解

@Auth
@RequestMapping("save")
@ResponseBody

@Auth注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Auth {
boolean login() default true;

String code() default "";

String name() default "";

int version() default 0;

ViewEnum response() default ViewEnum.JSON;
}

编写认证类继承父类拦截器

public class AuthExec extends AuthInterceptor {

private static Logger log = LoggerFactory.getLogger(AuthExec.class);


@Override
public boolean exec(HttpServletRequest request, HttpServletResponse response, Method method) {

if (StringUtils.isNotEmpty(SessionConstant.ACCESS_CONTROL)) {
if ("0".equalsIgnoreCase(SessionConstant.ACCESS_CONTROL)) {
throw Ex.build(UpdateExCode.AccessControl);
} else if ("-1".equalsIgnoreCase(SessionConstant.ACCESS_CONTROL)) {
throw Ex.build(UpdateExCode.ExAccessControl);
}
}
String tokenStr = request.getHeader("token");// 从 http 请求头中取出 token
Token token = null;
if (StringUtils.isNotBlank(tokenStr)) {
// log.error(request.getRequestURI() + " token:" + tokenStr);
token = JwtUtils.get(tokenStr);
}
//如果存在Auth注解就进入判断校验token值
if (method.isAnnotationPresent(Auth.class)) {
Auth auth = method.getAnnotation(Auth.class);
if (auth.login()) {
if (StringUtils.isEmpty(tokenStr)) {
throw Ex.build(CnEx.No_Login);
}

if (token == null || token.getCompanyId() == null || token.getCustomerId() == null || StringUtils.isBlank(token.getMobile())) {
throw Ex.build(CnEx.No_Permission);
}
if (token.getDate().before(new Date())) {
throw Ex.build(CnEx.No_Login);
}

}
}
if (token != null) {
JwtUtils.set(token);
}
return true;
}

}

父类认证拦截器
public abstract class AuthInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Annotation[] annos = method.getAnnotations();
if (annos == null || annos.length == 0) {
return true;
}
exec(request, response, method);
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
}

public abstract boolean exec(HttpServletRequest request, HttpServletResponse response, Method method);


}

jwt工具类JwtUtils

public class JwtUtils {

private static ThreadLocal<Token> threadLocal = new ThreadLocal<>();


public static Token get() {
return threadLocal.get();
}


public static void set(Token token) {
threadLocal.set(token);
}


//过期时间设置(24h)
private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

//私钥设置(随便乱写的)
private static final String TOKEN_SECRET = "5xcJVrXNyQSwK1l2RS9nw";

public static String getToken(Token token) {
//过期时间和加密算法设置
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

//头部信息
Map<String, Object> header = new HashMap<>(2);
header.put("typ", "JWT");
header.put("alg", "HS256");

return JWT.create()
.withHeader(header)
.withClaim("companyId", token.getCompanyId())
.withClaim("customerId", token.getCustomerId())
.withClaim("mobile", token.getMobile())
.withClaim("date", token.getDate())
.withExpiresAt(date)
.sign(algorithm);

}

public static Token get(String token) {
DecodedJWT jwt = JWT.decode(token);
Token tk = new Token();
tk.setCompanyId(jwt.getClaim("companyId").asInt());
tk.setCustomerId(jwt.getClaim("customerId").asInt());
tk.setMobile(jwt.getClaim("mobile").asString());
tk.setDate(jwt.getExpiresAt());
return tk;
}

public static String create(Integer companyId,Integer customerId, String mobile) {
//这里是传入的是token对象,决定token的内容
Token tk = new Token(companyId,customerId, mobile,new Date());
//获取时间用
//交给上面的实现类得到token
return getToken(tk);
}

}

token 对象

public class Token {

private Integer companyId;

private Integer customerId;

private String mobile;

private Date date;

public Token() {
}

public Token(Integer companyId, Integer customerId, String mobile, Date date) {
this.companyId = companyId;
this.customerId = customerId;
this.mobile = mobile;
this.date = date;
}

public Integer getCompanyId() {
return companyId;
}

public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}

public Integer getCustomerId() {
return customerId;
}

public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}
}

 

标签:String,companyId,mobile,jwt,Token,认证,token,public
来源: https://www.cnblogs.com/feizai-java/p/16197583.html