东莞模具网站建设,制作班徽的小程序,一个人做网站难吗,网站建设研究方法文章目录 前言1、用户登录1.1 JWTThreadLocal 2.1 代码实现2.1.1 ThreadLocal工具类2.2.2 定义拦截器2.2.3 注册拦截器 前言
1、用户登录
1.1 JWT
JSON Web Token简称JWT#xff0c;用于对应用程序上用户进行身份验证的标记。使用 JWTS 之后不需要保存用户的 cookie 或其他… 文章目录 前言1、用户登录1.1 JWTThreadLocal 2.1 代码实现2.1.1 ThreadLocal工具类2.2.2 定义拦截器2.2.3 注册拦截器 前言
1、用户登录
1.1 JWT
JSON Web Token简称JWT用于对应用程序上用户进行身份验证的标记。使用 JWTS 之后不需要保存用户的 cookie 或其他session数据同时可保证应用程序的安全。
JWT是经过加密处理与校验处理的字符串形式为A.B.C
–A由JWT头部信息header加密得到–B由JWT用到的身份验证信息JSON数据加密得到–C由A和B加密得到是校验部分–官方测试网站 https://jwt.io/ Testpublic void testCreateToken() {//生成token//1、准备数据Map map new HashMap();map.put(id,1);map.put(mobile,13800138000);//2、使用JWT工具类生成tokenlong now System.currentTimeMillis();String token Jwts.builder().signWith(SignatureAlgorithm.HS512, itcast) //指定加密算法.setClaims(map)//指定写入的数据.setExpiration(new Date(now 5000)) //设置失效时间.compact();System.out.println(token);}Testpublic void testParseToken() {String token eyJhbGciOiJIUzUxMiJ9.e1yJtb2JpbGUiOiIxMzgwMDEzODAwMCIsImlkIjoxLCJleHAiOjE2MTgzOTA4NzB9.WhZfFSJNEZJGeZAHqMaVIslvzvkFzQ1FCLCULSaR-yZYprbzgmuxNaSr3oW__zRFkBCnNRGllzaKb0ZJujs1GA;//解析tokentry {Claims claims Jwts.parser().setSigningKey(itcast).parseClaimsJws(token).getBody();Object id claims.get(id);Object mobile claims.get(mobile);System.out.println(id -- mobile);}catch (ExpiredJwtException e) {System.out.println(token已过期);}catch (SignatureException e) {System.out.println(token不合法);}} JWT工具类
public class JwtUtils {// TOKEN的有效期1小时Sprivate static final int TOKEN_TIME_OUT 3_600;// 加密KEYprivate static final String TOKEN_SECRET itcast;// 生成Tokenpublic static String getToken(Map params){long currentTime System.currentTimeMillis();return Jwts.builder().signWith(SignatureAlgorithm.HS512, TOKEN_SECRET) //加密方式.setExpiration(new Date(currentTime TOKEN_TIME_OUT * 1000)) //过期时间戳.addClaims(params).compact();}/*** 获取Token中的claims信息*/public static Claims getClaims(String token) {return Jwts.parser().setSigningKey(TOKEN_SECRET).parseClaimsJws(token).getBody();}/*** 是否有效 true-有效false-失效*/public static boolean verifyToken(String token) {if(StringUtils.isEmpty(token)) {return false;}try {Claims claims Jwts.parser().setSigningKey(itcast).parseClaimsJws(token).getBody();}catch (Exception e) {return false;}return true;}
}ThreadLocal 线程内部的存储类赋予了线程存储数据的能力。 线程内调用的方法都可以从ThreadLocal中获取同一个对象。 多个线程中ThreadLocal数据相互隔离
2.1 代码实现
2.1.1 ThreadLocal工具类
定义ThreadLocal工具类仅需要调用set方法即可将数据存入ThreadLocal中
package com.tanhua.server.interceptor;import com.tanhua.model.domain.User;/*** author Administrator*/
public class UserHolder {private static ThreadLocalUser tl new ThreadLocalUser();/*** 保存数据到线程*/public static void set(User user) {tl.set(user);}/*** 获取线程中的用户信息*/public static User get() {return tl.get();}/*** 从当前线程获取用户对象的id*/public static Long getUserId() {if (tl.get() null) {return null;}return tl.get().getId();}/*** 从当前线程获取用户对象的手机号码*/public static String getMobile() {if (tl.get() null) {return null;}return tl.get().getMobile();}/*** 移除线程中数据*/public static void remove() {tl.remove();}
}2.2.2 定义拦截器
定义拦截器在前置拦截方法preHandle中解析token并验证有效性如果失效返回状态码401。如果有效解析User对象存入ThreadLocal中
package com.tanhua.server.interceptor;import com.tanhua.model.domain.User;
import com.tanhua.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** author Administrator*/
public class TokenInterceptor extends HandlerInterceptorAdapter {Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//1、获取请求头String token request.getHeader(Authorization);//2、使用工具类判断token是否有效boolean verifyToken JwtUtils.verifyToken(token);//3、如果token失效返回状态码401拦截if(!verifyToken) {response.setStatus(401);return false;}//4、如果token正常可用放行//解析token获取id和手机号码Claims claims JwtUtils.getClaims(token);String mobile (String) claims.get(mobile);Integer id (Integer) claims.get(id);//构造User对象存入ThreadlocalUser user new User();user.setId(Long.valueOf(id));user.setMobile(mobile);UserHolder.set(user);return true;}//清空Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {UserHolder.remove();}
}2.2.3 注册拦截器
拦截器需要注册到MVC容器中
/*** author Administrator*/
Configuration
public class WebConfig implements WebMvcConfigurer {Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new TokenInterceptor()).addPathPatterns(/**).excludePathPatterns(/user/login, /user/loginVerification);}
}package com.tanhua.server.controller;import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Map;RestController
RequestMapping(/user)
public class LoginController {Autowiredprivate UserService userService;/*** 获取登录验证* 请求参数phoneMap* 响应void*ResponseEntity* return*/PostMapping(/login)public ResponseEntity login(RequestBody Map map){String phone (String) map.get(phone);userService.sendMsg(phone);
// return ResponseEntity.status(500).body(出错了);return ResponseEntity.ok(null);//正常返回状态码200}/***检验登录* /user/loginVerification* phone,verificationCode*/PostMapping(/loginVerification)public ResponseEntity loginVerification(RequestBody Map map){//1.调用map集合获取请求参数String phone (String) map.get(phone);String code (String) map.get(verificationCode);//2.调用userService完成用户登录Map retMap userService.loginVerification(phone,code);//3.构造返回return ResponseEntity.ok(retMap);}
}
package com.tanhua.server.service;import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.time.Duration;
import java.util.HashMap;
import java.util.Map;Service
public class UserService {Autowiredprivate SmsTemplate smsTemplate;Autowiredprivate RedisTemplateString,String redisTemplate;DubboReferenceprivate UserApi userApi;/*** 发送短信验证码* param phone*/public void sendMsg(String phone) {//1.随机生成6位数字
// String code RandomStringUtils.randomNumeric(6);String code 123456;//2.调用templat对象发送手机短信
// smsTemplate.sendSms(phone,code);//3.将验证码存入到redisredisTemplate.opsForValue().set(CHECK_CODE phone,code, Duration.ofMinutes(5));}/*** 验证登录* param phone* param code* return*/public Map loginVerification(String phone, String code) {//1.从redis中获取下发的验证码String redisCode redisTemplate.opsForValue().get(CHECK_CODE phone);//2.对验证码进行校验(验证码是否存在是否和输入的验证码是否一致)if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)){//验证码无效throw new BusinessException(ErrorResult.loginError());}//3.删除redis中的验证码redisTemplate.delete(CHECK_CODEphone);//4.通过手机号码查询用户User user userApi.findByMobile(phone);boolean isNew false;//5.如果用户不存在创建用户保存到数据库中if (user null){user new User();user.setMobile(phone);user.setPassword(DigestUtils.md5Hex(123456));Long userId userApi.save(user);user.setId(userId);isNew true;}//6.通过JWT生成token(存入id和手机号码)Map tokenMap new HashMap();tokenMap.put(id,user.getId());tokenMap.put(mobile,phone);String token JwtUtils.getToken(tokenMap);//7.构造返回值Map retMap new HashMap();retMap.put(token,token);retMap.put(isNew,isNew);return retMap;}
} 文章转载自: http://www.morning.rjrlx.cn.gov.cn.rjrlx.cn http://www.morning.nyqb.cn.gov.cn.nyqb.cn http://www.morning.bphqd.cn.gov.cn.bphqd.cn http://www.morning.brzlp.cn.gov.cn.brzlp.cn http://www.morning.qlry.cn.gov.cn.qlry.cn http://www.morning.crsnb.cn.gov.cn.crsnb.cn http://www.morning.gjlxn.cn.gov.cn.gjlxn.cn http://www.morning.gqmhq.cn.gov.cn.gqmhq.cn http://www.morning.bqwrn.cn.gov.cn.bqwrn.cn http://www.morning.xqbgm.cn.gov.cn.xqbgm.cn http://www.morning.mllmm.cn.gov.cn.mllmm.cn http://www.morning.rwqk.cn.gov.cn.rwqk.cn http://www.morning.qdmdp.cn.gov.cn.qdmdp.cn http://www.morning.wcjk.cn.gov.cn.wcjk.cn http://www.morning.fmqw.cn.gov.cn.fmqw.cn http://www.morning.gyqnp.cn.gov.cn.gyqnp.cn http://www.morning.lngyd.cn.gov.cn.lngyd.cn http://www.morning.qhmhz.cn.gov.cn.qhmhz.cn http://www.morning.nfmlt.cn.gov.cn.nfmlt.cn http://www.morning.tymwx.cn.gov.cn.tymwx.cn http://www.morning.kycwt.cn.gov.cn.kycwt.cn http://www.morning.bnrff.cn.gov.cn.bnrff.cn http://www.morning.gyfwy.cn.gov.cn.gyfwy.cn http://www.morning.rgrz.cn.gov.cn.rgrz.cn http://www.morning.dgmjm.cn.gov.cn.dgmjm.cn http://www.morning.qxmys.cn.gov.cn.qxmys.cn http://www.morning.yhpq.cn.gov.cn.yhpq.cn http://www.morning.lhxdq.cn.gov.cn.lhxdq.cn http://www.morning.lhjmq.cn.gov.cn.lhjmq.cn http://www.morning.hlzpb.cn.gov.cn.hlzpb.cn http://www.morning.kgjyy.cn.gov.cn.kgjyy.cn http://www.morning.rwlns.cn.gov.cn.rwlns.cn http://www.morning.tmbtm.cn.gov.cn.tmbtm.cn http://www.morning.juju8.cn.gov.cn.juju8.cn http://www.morning.dmsxd.cn.gov.cn.dmsxd.cn http://www.morning.xznrk.cn.gov.cn.xznrk.cn http://www.morning.zqwp.cn.gov.cn.zqwp.cn http://www.morning.wkknm.cn.gov.cn.wkknm.cn http://www.morning.mzkn.cn.gov.cn.mzkn.cn http://www.morning.kmkpm.cn.gov.cn.kmkpm.cn http://www.morning.bnxfj.cn.gov.cn.bnxfj.cn http://www.morning.fnssm.cn.gov.cn.fnssm.cn http://www.morning.ftrpvh.cn.gov.cn.ftrpvh.cn http://www.morning.jfbgn.cn.gov.cn.jfbgn.cn http://www.morning.rqfkh.cn.gov.cn.rqfkh.cn http://www.morning.pkggl.cn.gov.cn.pkggl.cn http://www.morning.hwcln.cn.gov.cn.hwcln.cn http://www.morning.btnmj.cn.gov.cn.btnmj.cn http://www.morning.lqytk.cn.gov.cn.lqytk.cn http://www.morning.wpwyx.cn.gov.cn.wpwyx.cn http://www.morning.tscsd.cn.gov.cn.tscsd.cn http://www.morning.pbxkk.cn.gov.cn.pbxkk.cn http://www.morning.pbtdr.cn.gov.cn.pbtdr.cn http://www.morning.jppb.cn.gov.cn.jppb.cn http://www.morning.rdkgw.cn.gov.cn.rdkgw.cn http://www.morning.pjwml.cn.gov.cn.pjwml.cn http://www.morning.gczqt.cn.gov.cn.gczqt.cn http://www.morning.rdtp.cn.gov.cn.rdtp.cn http://www.morning.nptls.cn.gov.cn.nptls.cn http://www.morning.qzfjl.cn.gov.cn.qzfjl.cn http://www.morning.mxnrl.cn.gov.cn.mxnrl.cn http://www.morning.mjqms.cn.gov.cn.mjqms.cn http://www.morning.xrwbc.cn.gov.cn.xrwbc.cn http://www.morning.rbnnq.cn.gov.cn.rbnnq.cn http://www.morning.kgfsz.cn.gov.cn.kgfsz.cn http://www.morning.rlns.cn.gov.cn.rlns.cn http://www.morning.zhnyj.cn.gov.cn.zhnyj.cn http://www.morning.wbhzr.cn.gov.cn.wbhzr.cn http://www.morning.lhrxq.cn.gov.cn.lhrxq.cn http://www.morning.ryglh.cn.gov.cn.ryglh.cn http://www.morning.rlfr.cn.gov.cn.rlfr.cn http://www.morning.fxwkl.cn.gov.cn.fxwkl.cn http://www.morning.ljcf.cn.gov.cn.ljcf.cn http://www.morning.sgnjg.cn.gov.cn.sgnjg.cn http://www.morning.nylbb.cn.gov.cn.nylbb.cn http://www.morning.hbywj.cn.gov.cn.hbywj.cn http://www.morning.llllcc.com.gov.cn.llllcc.com http://www.morning.bsgfl.cn.gov.cn.bsgfl.cn http://www.morning.fkgqn.cn.gov.cn.fkgqn.cn http://www.morning.rfjmy.cn.gov.cn.rfjmy.cn