0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

如何才能保证JWT安全

Android编程精选 来源:CSDN博客 作者:J_小浩子 2021-09-29 15:09 次阅读

jwt是什么?

JWTs是JSON对象的编码表示。JSON对象由零或多个名称/值对组成,其中名称为字符串,值为任意JSON值。JWT有助于在clear(例如在URL中)发送这样的信息,可以被信任为不可读(即加密的)、不可修改的(即签名)和URL - safe(即Base64编码的)。

jwt的组成

Header: 标题包含了令牌的元数据,并且在最小包含签名和/或加密算法的类型

Claims: Claims包含您想要签署的任何信息

JSON Web Signature (JWS): 在header中指定的使用该算法的数字签名和声明

例如:

Header:

{

“alg”: “HS256”,

“typ”: “JWT”

}

Claims:

{

sub”: “1234567890”,

“name”: “John Doe”,

“admin”: true

}

Signature:

base64UrlEncode(Header) + “。” + base64UrlEncode(Claims),

加密生成的token:

如何保证 JWT 安全

有很多库可以帮助您创建和验证JWT,但是当使用JWT时,仍然可以做一些事情来限制您的安全风险。在您信任JWT中的任何信息之前,请始终验证签名。这应该是给定的。

换句话说,如果您正在传递一个秘密签名密钥到验证签名的方法,并且签名算法被设置为“none”,那么它应该失败验证。

确保签名的秘密签名,用于计算和验证签名。秘密签名密钥只能由发行者和消费者访问,不能在这两方之外访问。

不要在JWT中包含任何敏感数据。这些令牌通常是用来防止操作(未加密)的,因此索赔中的数据可以很容易地解码和读取。

如果您担心重播攻击,包括一个nonce(jti索赔)、过期时间(exp索赔)和创建时间(iat索赔)。这些在JWT规范中定义得很好。

jwt的框架:JJWT

JJWT是一个提供端到端的JWT创建和验证的Java库。永远免费和开源(Apache License,版本2.0),JJWT很容易使用和理解。它被设计成一个以建筑为中心的流畅界面,隐藏了它的大部分复杂性。

JJWT的目标是最容易使用和理解用于在JVM上创建和验证JSON Web令牌(JWTs)的库。

JJWT是基于JWT、JWS、JWE、JWK和JWA RFC规范的Java实现。

JJWT还添加了一些不属于规范的便利扩展,比如JWT压缩和索赔强制。

规范兼容:

创建和解析明文压缩JWTs

创建、解析和验证所有标准JWS算法的数字签名紧凑JWTs(又称JWSs):

HS256: HMAC using SHA-256

HS384: HMAC using SHA-384

HS512: HMAC using SHA-512

RS256: RSASSA-PKCS-v1_5 using SHA-256

RS384: RSASSA-PKCS-v1_5 using SHA-384

RS512: RSASSA-PKCS-v1_5 using SHA-512

PS256: RSASSA-PSS using SHA-256 and MGF1 with SHA-256

PS384: RSASSA-PSS using SHA-384 and MGF1 with SHA-384

PS512: RSASSA-PSS using SHA-512 and MGF1 with SHA-512

ES256: ECDSA using P-256 and SHA-256

ES384: ECDSA using P-384 and SHA-384

ES512: ECDSA using P-521 and SHA-512

这里以github上的demo演示,理解原理,集成到自己项目中即可。

应用采用 spring boot + angular + jwt

结构图

Maven 引进 : pom.xml

《project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”》

《modelVersion》4.0.0《/modelVersion》

《groupId》com.nibado.example《/groupId》

《artifactId》jwt-angular-spring《/artifactId》

《version》0.0.2-SNAPSHOT《/version》

《properties》

《maven.compiler.source》1.8《/maven.compiler.source》

《maven.compiler.target》1.8《/maven.compiler.target》

《commons.io.version》2.4《/commons.io.version》

《jjwt.version》0.6.0《/jjwt.version》

《junit.version》4.12《/junit.version》

《spring.boot.version》1.5.3.RELEASE《/spring.boot.version》

《/properties》

《build》

《plugins》

《plugin》

《groupId》org.springframework.boot《/groupId》

《artifactId》spring-boot-maven-plugin《/artifactId》

《version》${spring.boot.version}《/version》

《executions》

《execution》

《goals》

《goal》repackage《/goal》

《/goals》

《/execution》

《/executions》

《/plugin》

《/plugins》

《/build》

《dependencies》

《dependency》

《groupId》org.springframework.boot《/groupId》

《artifactId》spring-boot-starter-web《/artifactId》

《version》${spring.boot.version}《/version》

《/dependency》

《dependency》

《groupId》commons-io《/groupId》

《artifactId》commons-io《/artifactId》

《version》${commons.io.version}《/version》

《/dependency》

《dependency》

《groupId》io.jsonwebtoken《/groupId》

《artifactId》jjwt《/artifactId》

《version》${jjwt.version}《/version》

《/dependency》

《dependency》

《groupId》junit《/groupId》

《artifactId》junit《/artifactId》

《version》${junit.version}《/version》

《/dependency》

《/dependencies》《/project》

WebApplication.java

package com.nibado.example.jwtangspr;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.boot.web.servlet.FilterRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

@EnableAutoConfiguration@ComponentScan@Configurationpublic class WebApplication {

//过滤器

@Bean

public FilterRegistrationBean jwtFilter() {

final FilterRegistrationBean registrationBean = new FilterRegistrationBean();

registrationBean.setFilter(new JwtFilter());

registrationBean.addUrlPatterns(“/api/*”);

return registrationBean;

}

public static void main(final String[] args) throws Exception {

SpringApplication.run(WebApplication.class, args);

}

}

JwtFilter.java

package com.nibado.example.jwtangspr;

import java.io.IOException;

import javax.servlet.FilterChain;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.filter.GenericFilterBean;

import io.jsonwebtoken.Claims;

import io.jsonwebtoken.Jwts;

import io.jsonwebtoken.SignatureException;

public class JwtFilter extends GenericFilterBean {

@Override

public void doFilter(final ServletRequest req,

final ServletResponse res,

final FilterChain chain) throws IOException, ServletException {

final HttpServletRequest request = (HttpServletRequest) req;

//客户端将token封装在请求头中,格式为(Bearer后加空格):Authorization:Bearer +token

final String authHeader = request.getHeader(“Authorization”);

if (authHeader == null || !authHeader.startsWith(“Bearer ”)) {

throw new ServletException(“Missing or invalid Authorization header.”);

}

//去除Bearer 后部分

final String token = authHeader.substring(7);

try {

//解密token,拿到里面的对象claims

final Claims claims = Jwts.parser().setSigningKey(“secretkey”)

.parseClaimsJws(token).getBody();

//将对象传递给下一个请求

request.setAttribute(“claims”, claims);

}

catch (final SignatureException e) {

throw new ServletException(“Invalid token.”);

}

chain.doFilter(req, res);

}

}

UserController.java

package com.nibado.example.jwtangspr;

import java.util.Arrays;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import javax.servlet.ServletException;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import io.jsonwebtoken.Jwts;

import io.jsonwebtoken.SignatureAlgorithm;

@RestController@RequestMapping(“/user”)

public class UserController {

//这里模拟数据库

private final Map《String, List《String》》 userDb = new HashMap《》();

@SuppressWarnings(“unused”)

private static class UserLogin {

public String name;

public String password;

}

public UserController() {

userDb.put(“tom”, Arrays.asList(“user”));

userDb.put(“wen”, Arrays.asList(“user”, “admin”));

}

/*以上是模拟数据库,并往数据库插入tom和sally两条记录*/

@RequestMapping(value = “login”, method = RequestMethod.POST)

public LoginResponse login(@RequestBody final UserLogin login)

throws ServletException {

if (login.name == null || !userDb.containsKey(login.name)) {

throw new ServletException(“Invalid login”);

}

//加密生成token

return new LoginResponse(Jwts.builder().setSubject(login.name)

.claim(“roles”, userDb.get(login.name)).setIssuedAt(new Date())

.signWith(SignatureAlgorithm.HS256, “secretkey”).compact());

}

@SuppressWarnings(“unused”)

private static class LoginResponse {

public String token;

public LoginResponse(final String token) {

this.token = token;

}

}

}

ApiController.java

package com.nibado.example.jwtangspr;

import io.jsonwebtoken.Claims;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

@RestController@RequestMapping(“/api”)

public class ApiController {

@SuppressWarnings(“unchecked”)

@RequestMapping(value = “role/{role}”, method = RequestMethod.GET)

public Boolean login(@PathVariable final String role,

final HttpServletRequest request) throws ServletException {

final Claims claims = (Claims) request.getAttribute(“claims”);

return ((List《String》) claims.get(“roles”)).contains(role);

}

}

index.html

《!doctype html》《html ng-app=“myApp”》《head》

《meta charset=“utf-8”/》

《meta http-equiv=“X-UA-Compatible” content=“IE=edge,chrome=1”/》

《title》JSON Web Token / AngularJS / Spring Boot example《/title》

《meta name=“description” content=“”》

《meta name=“viewport” content=“width=device-width”》

《link rel=“stylesheet” href=“libs/bootstrap/css/bootstrap.css”》

《script src=“libs/jquery/jquery.js”》《/script》

《script src=“libs/bootstrap/js/bootstrap.js”》《/script》

《script src=“libs/angular/angular.js”》《/script》

《script src=“app.js”》《/script》《/head》《body》《div class=“container” ng-controller=‘MainCtrl’》

《h1》{{greeting}}《/h1》

《div ng-show=“!loggedIn()”》

Please log in (tom and sally are valid names)《/br》

《form ng-submit=“login()”》

Username: 《input type=“text” ng-model=“userName”/》《span》《input type=“submit” value=“Login”/》

《/form》

《/div》

《div class=“alert alert-danger” role=“alert” ng-show=“error.data.message”》

《span class=“glyphicon glyphicon-exclamation-sign” aria-hidden=“true”》《/span》

《span class=“sr-only”》Error:《/span》

{{error.data.message}}

《/div》

《div ng-show=“loggedIn()”》

《div class=“row”》

《div class=“col-md-6”》

《h3》《span class=“label label-success”》Success!《/span》 Welcome {{userName}}《/h3》

《a href ng-click=“logout()”》(logout)《/a》

《/div》

《div class=“col-md-4”》

《div class=“row header”》

《div class=“col-sm-4”》{{userName}} is a《/div》

《/div》

《div class=“row”》

《div class=“col-sm-2”》User《/div》

《div class=“col-sm-2”》《span class=“glyphicon glyphicon-ok” aria-hidden=“true” ng-show=“roleUser”》《/span》《/div》

《/div》

《div class=“row”》

《div class=“col-sm-2”》Admin《/div》

《div class=“col-sm-2”》《span class=“glyphicon glyphicon-ok” aria-hidden=“true” ng-show=“roleAdmin”》《/span》《/div》

《/div》

《div class=“row”》

《div class=“col-sm-2”》Foo《/div》

《div class=“col-sm-2”》《span class=“glyphicon glyphicon-ok” aria-hidden=“true” ng-show=“roleFoo”》《/span》《/div》

《/div》

《/div》

《/div》

《/div》《/div》《/body》《/html》

app.js

var appModule = angular.module(‘myApp’, []);

appModule.controller(‘MainCtrl’, [‘mainService’,‘$scope’,‘$http’,

function(mainService, $scope, $http) {

$scope.greeting = ‘Welcome to the JSON Web Token / AngularJR / Spring example!’;

$scope.token = null;

$scope.error = null;

$scope.roleUser = false;

$scope.roleAdmin = false;

$scope.roleFoo = false;

$scope.login = function() {

$scope.error = null;

mainService.login($scope.userName).then(function(token) {

$scope.token = token;

$http.defaults.headers.common.Authorization = ‘Bearer ’ + token;

$scope.checkRoles();

},

function(error){

$scope.error = error

$scope.userName = ‘’;

});

}

$scope.checkRoles = function() {

mainService.hasRole(‘user’).then(function(user) {$scope.roleUser = user});

mainService.hasRole(‘admin’).then(function(admin) {$scope.roleAdmin = admin});

mainService.hasRole(‘foo’).then(function(foo) {$scope.roleFoo = foo});

}

$scope.logout = function() {

$scope.userName = ‘’;

$scope.token = null;

$http.defaults.headers.common.Authorization = ‘’;

}

$scope.loggedIn = function() {

return $scope.token !== null;

}

} ]);

appModule.service(‘mainService’, function($http) {

return {

login : function(username) {

return $http.post(‘/user/login’, {name: username}).then(function(response) {

return response.data.token;

});

},

hasRole : function(role) {

return $http.get(‘/api/role/’ + role).then(function(response){

console.log(response);

return response.data;

});

}

};

});

责任编辑:haq

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 文件
    +关注

    关注

    1

    文章

    540

    浏览量

    24400
  • JSON
    +关注

    关注

    0

    文章

    111

    浏览量

    6813

原文标题:还在直接用JWT做鉴权?JJWT真香

文章出处:【微信号:AndroidPush,微信公众号:Android编程精选】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    究竟FPC上的焊盘间距做多大才能保证阻焊桥

    都说PCB上焊盘间距做到8mil,保证绿油桥是没有问题,为什么FPC也是同样的设计, PCBA锡膏印刷后连锡短路,是焊接厂工艺能力不足,还是FPC设计出了问题,请走进今天的案例分析,一起为您揭谜。
    的头像 发表于 04-07 10:33 796次阅读
    究竟FPC上的焊盘间距做多大<b class='flag-5'>才能</b><b class='flag-5'>保证</b>阻焊桥

    请问NFC数据传输如何保证数据安全

    NFC数据传输如何保证数据安全
    发表于 04-07 06:18

    什么是JWTJWT由哪些部分组成?JWT如何进行用户认证?

    JWT(JSON Web Token)是一个开放的行业标准(RFC 7519),自身包含了身份验证所需要的所有信息,因此我们的服务器不需要存储用户Session信息。
    的头像 发表于 02-25 09:44 333次阅读
    什么是<b class='flag-5'>JWT</b>?<b class='flag-5'>JWT</b>由哪些部分组成?<b class='flag-5'>JWT</b>如何进行用户认证?

    JWT渗透姿势一篇通

    Signature是使用指定算法对Header和Payload进行签名生成的,用于验证JWT的完整性和真实性,Signature的生成方式通常是将Header和Payload连接起来然后使用指定算法对其进行签名
    的头像 发表于 11-13 16:04 657次阅读
    <b class='flag-5'>JWT</b>渗透姿势一篇通

    差分信号进入ADC芯片,怎样才能保证两差分信号自动均衡呢?

    差分信号进入ADC芯片,怎样才能保证两差分信号自动均衡呢? 差分信号进入ADC芯片时,为了保证两差分信号自动均衡,可以采取以下措施: 1. 去除共模干扰:共模干扰是指差分信号的两个输入端引入的信号
    的头像 发表于 11-09 09:55 779次阅读

    后端JWT接口认证的操作流程

    为了反爬或限流节流,后端编写接口时,大部分 API 都会进行权限认证,只有认证通过,即:数据正常及未过期才会返回数据,否则直接报错 本篇文章以 Django 为例,聊聊后端 JWT 接口认证的操作
    的头像 发表于 10-31 11:20 303次阅读

    电路如何进行降额设计?如何才能保证电路的稳定性?

    电路如何进行降额设计?降额设计应该怎么做?如何才能保证电路的稳定性? 电路设计中,降额设计是非常常见的一个设计策略。它主要是为了在设计过程中,根据实际需求和限制条件,将电路的功率、电流等参数进行适当
    的头像 发表于 10-30 09:46 1086次阅读

    Tbox如何做防护来保证数据安全

    Tbox如何做防护来保证数据安全呢?
    发表于 10-16 06:48

    JWT的认证流程

    今天带大家来认识一下JWTJWT简介 JWT(Json Web Token)是为了在网络应用环境间传递声明而执行的一种基于 Json 的开放标准。JWT 的声明一般被用来在身份提供
    的头像 发表于 10-08 15:01 673次阅读
    <b class='flag-5'>JWT</b>的认证流程

    亚马逊云科技:数据安全无忧,才能释放价值

    然而许多企业在实践中也发现,安全合规与数据应用之间经常会存在彼此矛盾的关系。合规团队需要保证敏感数据能被有效识别并得到合理的保护和存储;数据+业务团队需要在确保数据安全的前提下进行高效协作;运营和
    的头像 发表于 09-28 17:13 1049次阅读

    jwt冒泡排序的原理

    jwt简介 冒泡排序: (Bubble Sort)是一种简单的交换排序。之所以叫做冒泡排序,因为我们可以把每个元素当成一个小气泡,根据气泡大小,一步一步移动到队伍的一端,最后形成一定对的顺序。 冒泡
    的头像 发表于 09-25 16:33 313次阅读
    <b class='flag-5'>jwt</b>冒泡排序的原理

    如何保证我们的数据安全

    的解决方案。但事实上,数据加密对于向你的领导团队、你的客户、你的投资者和其他有价值的利益相关者保证你将安全放在首位,以及你的组织已经采取了符合行业最佳实践的措施来防止数据泄露、泄漏或错
    的头像 发表于 07-31 17:41 790次阅读
    如何<b class='flag-5'>保证</b>我们的数据<b class='flag-5'>安全</b>

    用NANO100系列的UART传入数据唤醒功能,在掉电模式接收数据要怎么处理才能保证完整?

    请教下,我用NANO100系列的UART传入数据唤醒功能,在掉电模式接收数据要怎么处理才能保证完整?
    发表于 06-27 07:02

    RISC-V如何保证高权限模式程序及外设的安全性?

    RISC-V有机器模式、监管模式和用户模块,但无论在哪个模式下当TRAP发生时都会转到机器模式,是不是也就意味着在用户模式下进入中断服务程序也会拥有机器模式的权限,那我们如何保证高权限模式程序及外设的安全性?
    发表于 05-26 08:11

    安全启动需要多长时间才能给出结果?

    安全启动需要多长时间才能给出结果?示例:S32k144 引导加载程序 128k。
    发表于 05-11 07:38