html ssm写用户登陆验证,ssm 使用token校验登录的实现

背景

token的意思是“令牌”,是服务端生成的一串字符串,作为客户端进行请求的一个标识。

当用户第一次登录后,服务器生成一个token并将此token返回给客户端,以后客户端只需带上这个token前来请求数据即可,无需再次带上用户名和密码。

简单token的组成;uid(用户唯一的身份标识)、time(当前时间的时间戳)、sign(签名,token的前几位以哈希算法压缩成的一定长度的十六进制字符串。为防止token泄露)

使用场景

token 还能起到反爬虫的作用,当然爬虫也是有突破的方法的,尽管如此还是能减少一部分爬虫访问服务器的所带来的负载。相对的爬虫技术门槛变高了。

使用session也能达到用户验证的目的 、但是session 是消耗服务器的内存,在对性能要求较高的项目中 ,开发中该技术相较于token已经过时

补充

token主要使用于在广大的安卓开发中

使用springmvc 中拦截器实现

使用方法

在maven ssm项目中pom.xml 配置 中引用jar包

703e27200178f723ece07062d8011ec1.png

com.auth0

java-jwt

3.3.0

创建JwtUtil 工具类

package xyz.amewin.util;

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.io.UnsupportedEncodingException;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

/**

* Java web token 工具类

*

* @author qiaokun

* @date 2018/08/10

*/

public class JwtUtil {

/**

* 过期时间一天,

* TODO 正式运行时修改为15分钟

*/

private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

/**

* token私钥

*/

private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";

/**

* 校验token是否正确

*

* @param token 密钥

* @return 是否正确

*/

public static boolean verify(String token) {

try {

Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

JWTVerifier verifier = JWT.require(algorithm)

.build();

DecodedJWT jwt = verifier.verify(token);

return true;

} catch (Exception exception) {

return false;

}

}

/**

* 获得token中的信息无需secret解密也能获得

*

* @return token中包含的用户名

*/

public static String getUsername(String token) {

try {

DecodedJWT jwt = JWT.decode(token);

return jwt.getClaim("loginName").asString();

} catch (JWTDecodeException e) {

return null;

}

}

/**

* 获取登陆用户ID

* @param token

* @return

*/

public static String getUserId(String token) {

try {

DecodedJWT jwt = JWT.decode(token);

return jwt.getClaim("userId").asString();

} catch (JWTDecodeException e) {

return null;

}

}

/**

* 生成签名,15min后过期

*

* @param username 用户名

* @return 加密的token

*/

public static String sign(String username,String userId) {

try {

// 过期时间

Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);

// 私钥及加密算法

Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

// 设置头部信息

Map header = new HashMap<>(2);

header.put("typ", "JWT");

header.put("alg", "HS256");

// 附带username,userId信息,生成签名

return JWT.create()

.withHeader(header)

.withClaim("loginName", username)

.withClaim("userId",userId)

.withExpiresAt(date)

.sign(algorithm);

} catch (UnsupportedEncodingException e) {

return null;

}

}

}

创建TokenInterceptor 拦截器

package xyz.amewin.interceptor;

import com.alibaba.fastjson.JSONObject;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

import xyz.amewin.util.ApiResponse;

import xyz.amewin.util.Contant;

import xyz.amewin.util.JwtUtil;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.HashMap;

import java.util.Map;

/**

* @author Amewin

* @date 2020/4/17 22:42

* 此处拦截器

*/

public class TokenInterceptor implements HandlerInterceptor {

/**

* 拦截器和过滤器的区别

* 1.拦截器针对访问控制器进行拦截

* 及 @RequestMapping(value = {"/test"})

* 简而言说就是访问方法的url

* 应用:可以作为权限的判断,

* 2.过滤器则是针对全局的请求

* 包括:css/js/html/jpg/png/git/...

* 及静态文件

* 20200417 23:13

*/

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

System.out.println("执行方法之前执行这步操作!");

response.setCharacterEncoding("utf-8");

Cookie cookie=getCookieByName(request,"_COOKIE_NAME");

//如果已经登录,不拦截

if (null != cookie) {

//验证token是否正确

boolean result = JwtUtil.verify(cookie.getValue());

if (!result) {

return false;

}

return true;

}

//如果没有登录,则跳转到登录界面

else {

//重定向 第一种 调用控制器 方法

response.sendRedirect(request.getContextPath() + "/login");

//重定向 第二种 重定向方法

// request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response);

// System.out.println(request.getContextPath());

return false;

/**

* 以下是为了登录成功后返回到刚刚的操作,不跳到主界面

* 实现:通过将请求URL保存到session的beforePath中,然后在登录时判断beforePath是否为空

*/

}

}

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

}

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

}

/**

* 根据名字获取cookie

*

* @param request

* @param name cookie名字

* @return

*/

public static Cookie getCookieByName(HttpServletRequest request, String name) {

Map cookieMap = ReadCookieMap(request);

if (cookieMap.containsKey(name)) {

Cookie cookie = cookieMap.get(name);

return cookie;

} else {

return null;

}

}

/**

* 将cookie封装到Map里面

*

* @param request

* @return

*/

private static Map ReadCookieMap(HttpServletRequest request) {

Map cookieMap = new HashMap();

Cookie[] cookies = request.getCookies();

if (null != cookies) {

for (Cookie cookie : cookies) {

cookieMap.put(cookie.getName(), cookie);

}

}

return cookieMap;

}

/**

* 返回信息给客户端

*

* @param response

* @param out

* @param apiResponse

*/

private void responseMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out, ApiResponse apiResponse) throws IOException {

response.setContentType("application/json; charset=utf-8");

out.print(JSONObject.toJSONString(apiResponse));

out.flush();

out.close();

}

}

spring-mvc.xml配置拦截器:

e67ca1a65fa982d428f3904c0511a572.png

在控制器中使用

//查询数据库,登录

PwUser pwUser = loginService.jsonLogin(username, password);

if (pwUser != null) {

json.setSuccess(true);

json.setMsg("登录成功!");

String token = JwtUtil.sign(pwUser.getUsernuber(), pwUser.getUserid().toString());

if (token != null) {

Cookie cookie = new Cookie("_COOKIE_NAME", token);

cookie.setMaxAge(3600);//设置token有效时间

cookie.setPath("/");

response.addCookie(cookie);

}else{

json.setMsg("密码或账号错误!");

}

} else {

json.setMsg("密码或账号错误!");

}

最后一点要web.xml 中配置加载spring-mvc拦截器

dispatcherServlet

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:spring-mvc.xml

1

到此这篇关于ssm 使用token校验登录的实现的文章就介绍到这了,更多相关ssm token校验登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值