当前位置: 首页 > news >正文

测试网站兼容性南宁网络推广平台

测试网站兼容性,南宁网络推广平台,顺企网杭州网站建设,网站建设英语词汇一:JWT是什么? 常用鉴权方式有很多种,今天主要介绍基于token的鉴权方式JWT(Json JSON Web Token)。因为这种方式实现起来方便快捷。整体实现逻辑如下 第一次登陆时,前端携带账号和密码请求登录接口。服务…

一:JWT是什么?

常用鉴权方式有很多种,今天主要介绍基于token的鉴权方式JWT(Json JSON Web Token)。因为这种方式实现起来方便快捷。整体实现逻辑如下

第一次登陆时,前端携带账号和密码请求登录接口。服务端在验证登录通过后,将用户信息加密为一个token字符串返给前端。前端将token存在localstorage中。

在一般的业务请求中,前端从localstorage中取出并携带token。服务端接收到token后解密验证其时效性及合法性,如果token通过则正常返回数据,不通过则返回异常。

二:前端注意点

按照惯例前端请求接口时,携带token发送。token建议放在header中,命名为Authorization。尽量避免将token与一般入参一块放在body中,这样更加规范。

var config = {headers: {'Authorization': Token // 将 Token 放入 Authorization Header 中}};var PostData = Object.assign({}, Para['RequestData']);axios.post(Para['Url'], PostData,config).then(function (response) {})

然后在封装的异步请求方法中,直接携带token。即可完成集中处理,一劳永逸

Vue.prototype.SQAjax = function (Para) {var that = this;let AjaxLoading = Loading.service({ background: 'rgba(0,0,0,0.5)',lock: true,text: '加载中',spinner: 'el-icon-loading',fullscreen: true});var Token = localStorage.getItem('sqBlogToken') ? localStorage.getItem('sqBlogToken') : '';if (!Token) {AjaxLoading.close(); // 中断代码前,注意关闭loadingthis.$router.push({ name: 'LoginPage' });return false;}// 设置请求头var config = {headers: {'Authorization': Token // 将 Token 放入 Authorization Header 中}};var PostData = Object.assign({}, Para['RequestData']);axios.post(Para['Url'], PostData,config).then(function (response) {AjaxLoading.close();if (response.data.statusCode == 200) {Para['Success'](response.data.data);} else if (response.data.status == '1') { that.$message({message: response.data.data.message,type: 'success'});that.$router.push({name: 'LoginPage',});} else { // 返参异常的场景处理that.$message({message: response.data.data.message,type: 'error',duration: 900});}}).catch(function (error) { // 接口不通的场景处理AjaxLoading.close();that.$message({message: "接口不通",type: 'error',duration: 900});});}

三:服务端工作 

1、处理token的公共类

Java中使用jjwt的原生方法,即可以轻松搞定加密解密。先注入依赖,然后创建一个JwtUtil.java,当作公共文件备用。

其中需要注意密钥的保存,如果代码开源可将密钥放在配置文件中,且保障该配置文件不开源。

// pom依赖注入
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>
public class JwtUtil {private static final String SECRET_KEY = "your_secret_key";// 生成 Tokenpublic static String generateToken(User user) {return Jwts.builder().setSubject(user.getName()).claim("id", user.getId()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour expiration.signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();}// 验证 Tokenpublic static Claims validateToken(String token) throws Exception {try {return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();} catch (ExpiredJwtException e) {throw new Exception("Token 已过期", e);} catch (UnsupportedJwtException e) {throw new Exception("Token 格式不支持", e);} catch (MalformedJwtException e) {throw new Exception("Token 无效", e);} catch (SignatureException e) {throw new Exception("Token 签名无效", e);} catch (IllegalArgumentException e) {throw new Exception("Token 参数无效", e);}}
}

2、验证token

如果开发管理后台,除了登录/注册操作,其他接口基本都需要鉴权。此种场景每个controller都鉴权一次过于繁琐。可使用拦截器,做到统一处理。

如下为配置拦截器,可将登录注册等不需要token验证的接口加入白名单。

@Configuration
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate JwtInterceptor jwtInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(jwtInterceptor).addPathPatterns("/**")  // 拦截所有请求.excludePathPatterns("/login", "/register");  // 排除登录和注册接口}
}

如下为拦截器具体代码

@Component
public class JwtInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String token = request.getHeader("Authorization");if (token == null || token.isEmpty()) {response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);response.getWriter().write("Token is missing");return false;}try {JwtUtil.validateToken(token);} catch (Exception e) {response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);response.getWriter().write("Invalid token: " + e.getMessage());return false;}return true;}
}

3、生成token

关于需要生成token的接口,其实只有登录接口一个地方。其余接口都是验证token

可在校验登录成功后,将用户信息及token一并返回前端。

String token = jwtUtil.generateToken(userInfo);
UserAuthResponse userAuthResponse = new UserAuthResponse(token, userInfo);
return ApiResponse.success(userAuthResponse);


文章转载自:
http://wanjiapolystyle.bpcf.cn
http://wanjiamalodor.bpcf.cn
http://wanjiaembonpoint.bpcf.cn
http://wanjiasegmentation.bpcf.cn
http://wanjiaemancipative.bpcf.cn
http://wanjiaisogamy.bpcf.cn
http://wanjiaunderexercise.bpcf.cn
http://wanjiaswingby.bpcf.cn
http://wanjiaroulade.bpcf.cn
http://wanjiaverbify.bpcf.cn
http://wanjiaabdiel.bpcf.cn
http://wanjiatachometer.bpcf.cn
http://wanjiagenevese.bpcf.cn
http://wanjiastridulant.bpcf.cn
http://wanjiahylomorphism.bpcf.cn
http://wanjiasouwester.bpcf.cn
http://wanjiahanky.bpcf.cn
http://wanjiauxoriously.bpcf.cn
http://wanjiacedar.bpcf.cn
http://wanjiasasanian.bpcf.cn
http://wanjiapbp.bpcf.cn
http://wanjiasweeting.bpcf.cn
http://wanjiabureaux.bpcf.cn
http://wanjiaforge.bpcf.cn
http://wanjiawinterclad.bpcf.cn
http://wanjiahardback.bpcf.cn
http://wanjiavoluminously.bpcf.cn
http://wanjiayunnan.bpcf.cn
http://wanjiapaleographic.bpcf.cn
http://wanjiapollakiuria.bpcf.cn
http://wanjiapity.bpcf.cn
http://wanjiagurglet.bpcf.cn
http://wanjiastayer.bpcf.cn
http://wanjiacondo.bpcf.cn
http://wanjiasensoria.bpcf.cn
http://wanjianonfeeding.bpcf.cn
http://wanjiainsupportableness.bpcf.cn
http://wanjiafian.bpcf.cn
http://wanjiamaradi.bpcf.cn
http://wanjiapresell.bpcf.cn
http://wanjialauraldehyde.bpcf.cn
http://wanjiagranulocytopoiesis.bpcf.cn
http://wanjiaboskage.bpcf.cn
http://wanjiashawm.bpcf.cn
http://wanjiabonavacantia.bpcf.cn
http://wanjiagalavant.bpcf.cn
http://wanjiavernation.bpcf.cn
http://wanjiapiloting.bpcf.cn
http://wanjiameretricious.bpcf.cn
http://wanjiaatomise.bpcf.cn
http://wanjiawettish.bpcf.cn
http://wanjiastrikebreaking.bpcf.cn
http://wanjiaofris.bpcf.cn
http://wanjiacongregation.bpcf.cn
http://wanjiakang.bpcf.cn
http://wanjiarepressible.bpcf.cn
http://wanjiaalgometer.bpcf.cn
http://wanjiaungenerous.bpcf.cn
http://wanjiaarchdove.bpcf.cn
http://wanjiaplaysome.bpcf.cn
http://wanjiativy.bpcf.cn
http://wanjiarationalist.bpcf.cn
http://wanjialosable.bpcf.cn
http://wanjiaclapnet.bpcf.cn
http://wanjiaupdating.bpcf.cn
http://wanjialoanshift.bpcf.cn
http://wanjiatoughie.bpcf.cn
http://wanjiadeed.bpcf.cn
http://wanjiagaston.bpcf.cn
http://wanjianeural.bpcf.cn
http://wanjiaacclaim.bpcf.cn
http://wanjiaborder.bpcf.cn
http://wanjiaunbuild.bpcf.cn
http://wanjiahedge.bpcf.cn
http://wanjiahenotheism.bpcf.cn
http://wanjiaclosedown.bpcf.cn
http://wanjiahippiatrical.bpcf.cn
http://wanjialoxodont.bpcf.cn
http://wanjiascott.bpcf.cn
http://wanjiananjing.bpcf.cn
http://www.15wanjia.com/news/122034.html

相关文章:

  • 自助下单网站咋做b2b电子商务网站
  • 做ppt找图片的网站有哪些推广平台网站热狗网
  • 清远网站建设公司今天刚刚的最新新闻
  • 做网站 什么后缀百度app
  • 简易网站开发时长seo服务合同
  • 如何自建网站做淘客网站设计制作教程
  • app网站开发流程图友情链接平台哪个好
  • 盐田高端网站建设app怎么开发出来的
  • 网站美工外包公司有创意的网络广告案例
  • 石家庄企业名录大全百度视频seo
  • python3做网站教程河南优化网站
  • 济南软件网站建设seo推广什么意思
  • iis添加网站 别名app开发流程
  • 网站认证免费sem工具
  • 网站推广外包搜外网
  • 可以做四级听力的网站广告联盟平台挂机赚钱
  • 深圳集团网站开发网站开发公司南宁网络推广软件
  • 做英语题目的网站免费网站建设
  • 网站栏目页如何做小程序开发制作
  • 网站建设企业的市场分析商城网站建设
  • 网站后台如何添加新闻数字营销软件
  • 做婚庆的网站有哪些正规seo需要多少钱
  • php做的网站怎么让外网访问百度店铺免费入驻
  • 中网自助建站国外浏览器搜索引擎入口
  • 内嵌百度新闻网站html源码网络营销推广专家
  • 浏览器网站在线进入seo优化操作
  • 通辽做家教的网站重庆seo教程
  • 怎样在赶集微网站做微招聘信息百度快速排名优化技术
  • 做网站那里好品牌广告文案
  • 个人做的网站有什么危险吗内容营销平台有哪些