标签:algorithm 一个 ann fastjson 实现 sign ios frame result
转自博客 https://blog.csdn.net/weixin_39102174/article/details/90411116
以上博主讲的更清除些,此博客是为了自己加深记忆。
对于前后端分离的项目来说session来判断是否登陆实现比较困难,token是比较好的方式。
大概流程:
1.用户登陆,若成功则后台生成一个token,并把此token返回给客户端浏览器
2.客户端接收到token后,每次请求都要把此token放到header中发给后段
3.后段使用拦截器判断token的正确性和实效性。
以下是具体代码:
Token工具类:
-
-
import com.auth0.jwt.JWT;
-
import com.auth0.jwt.JWTVerifier;
-
import com.auth0.jwt.algorithms.Algorithm;
-
import com.auth0.jwt.exceptions.JWTDecodeException;
-
import com.auth0.jwt.interfaces.DecodedJWT;
-
-
-
import java.util.HashMap;
-
-
-
-
-
-
-
-
private static final long EXPIRE_TIME=60 * 60 *1000;
-
-
-
-
-
private static final String TOKEN_SECRET="Token";
-
-
-
-
-
-
-
-
-
public static String sign(String useName,String userId){
-
-
-
-
-
Date date=new Date(System.currentTimeMillis()+EXPIRE_TIME);
-
-
Algorithm algorithm=Algorithm.HMAC256(TOKEN_SECRET);
-
-
Map<String,Object> header=new HashMap<>();
-
-
header.put("alg","HS256");
-
-
-
-
-
.withClaim("userName",useName)
-
.withClaim("userId",userId)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public static boolean verify(String token){
-
-
-
Algorithm algorithm=Algorithm.HMAC256(TOKEN_SECRET);
-
-
JWTVerifier verifier =JWT.require(algorithm).build();
-
-
DecodedJWT decodedJWT =verifier.verify(token);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public static String getUsername(String token) {
-
-
DecodedJWT jwt = JWT.decode(token);
-
return jwt.getClaim("userName").asString();
-
} catch (JWTDecodeException e) {
-
-
-
-
-
-
-
-
-
-
-
-
public static String getUserId(String token) {
-
-
DecodedJWT jwt = JWT.decode(token);
-
return jwt.getClaim("userId").asString();
-
} catch (JWTDecodeException e) {
-
-
-
-
-
-
-
-
拦截器:
-
-
-
import com.alibaba.fastjson.JSONObject;
-
import com.constant.TokenConstant;
-
import com.sign.TokenSign;
-
import org.springframework.stereotype.Component;
-
import org.springframework.web.servlet.HandlerInterceptor;
-
import org.springframework.web.servlet.ModelAndView;
-
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
import java.util.HashMap;
-
-
-
-
-
public class LoginInterceptor implements HandlerInterceptor {
-
-
-
-
-
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
-
-
httpServletResponse.setCharacterEncoding("UTF-8");
-
String token=httpServletRequest.getHeader("accessToken");
-
-
Map<String,Object> map=new HashMap<>();
-
map.put("data","token is null");
-
-
httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
-
-
-
boolean result= TokenSign.verify(token);
-
-
-
-
TokenConstant.updateTokenMap(token);
-
-
-
-
Map<String,Object> map=new HashMap<>();
-
map.put("data","token is null");
-
-
httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
-
-
-
-
-
-
-
-
-
-
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
-
-
-
-
-
-
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
-
-
-
-
-
-
-
-
import java.util.HashMap;
-
-
-
public class TokenConstant {
-
-
private static Map<String,String> map=new HashMap();
-
-
-
public static String getToken(){
-
-
-
-
public static void updateTokenMap(String token){
-
-
-
-
-
注册拦截器:
-
-
-
import com.interceptor.LoginInterceptor;
-
import org.springframework.beans.factory.annotation.Autowired;
-
import org.springframework.context.annotation.Configuration;
-
import org.springframework.web.servlet.config.annotation.CorsRegistry;
-
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
-
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
-
-
-
public class LoginAdapter implements WebMvcConfigurer {
-
-
-
-
-
public void addCorsMappings(CorsRegistry registry) {
-
registry.addMapping("/**")
-
.allowedHeaders("Content-Type","X-Requested-With","accept,Origin","Access-Control-Request-Method","Access-Control-Request-Headers","token")
-
-
-
-
-
-
-
-
-
-
-
private LoginInterceptor loginInterceptor;
-
-
-
-
-
public void addResourceHandlers(ResourceHandlerRegistry registry) {
-
-
-
-
-
-
-
public void addInterceptors(InterceptorRegistry registry) {
-
System.out.println("进入拦截器");
-
-
-
registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/user/login");
-
-
-
以上是后台的配置,除了登陆所有请求都会进行token验证。
前端代码概要:
前端用的VUE
-
-
-
-
<div class="welcome"><img src="/dist/static/image/welcome.png"></div>
-
-
-
-
<div class="login-inp"><label>账号</label><input type="text" placeholder="请输入账号" v-model="user.account"></div>
-
<div class="login-inp"><label>密码</label><input type="password" placeholder="请输入密码" v-model="user.password"></div>
-
-
<div class="login-inp" v-show="!loadingShow" v-on:click="ok()">
-
<input type="button" value="立即登录" />
-
-
-
-
<wv-loadmore v-show="this.loadingShow"></wv-loadmore>
-
-
-
-
-
-
-
-
import Axios from ‘axios‘
-
import { Toast } from ‘we-vue‘
-
-
-
-
-
user: {account: ‘‘, password: ‘‘},
-
-
url:this.GLOBAL.loginUrl,
-
-
-
-
-
-
-
if (!this.user.account || !this.user.password) {
-
-
-
console.log(‘param not allow null‘)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
params+=index+‘=‘+data[index]+‘&‘;
-
-
-
-
-
-
-
-
-
localStorage.setItem(‘accessToken‘, response.data);
-
this.$router.push({ path: ‘home‘ })
-
-
-
console.log(‘登陆失败:‘, response.data.message)
-
-
-
-
-
-
-
console.log(‘请求失败:‘, error)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
this.$emit(‘cancel‘, this.flowParam)
-
-
-
-
-
-
-
登陆界面最主要的是:localStorage.setItem(‘accessToken‘, response.data);把token信息存储
每次请求都放到header中:
此处简写:
-
Axios.post(this.addUrl,param,
-
{headers: {‘Content-Type‘:‘application/json;charset=UTF-8‘,‘accessToken‘:localStorage.getItem(‘accessToken‘)}},
-
-
localStorage.getItem(‘accessToken‘);获取存储在localStorage中的token信息
【转】java基于token验证之登陆验证
标签:algorithm 一个 ann fastjson 实现 sign ios frame result
原文地址:https://www.cnblogs.com/EarlyBridVic/p/12532658.html