JWT 和 JJWT 的区别?别再傻傻分不清了。。(2)

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

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

@Configuration

public 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> 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) claims.get(“roles”)).contains(role);

}

}

index.html

<!doctype html>

JSON Web Token / AngularJS / Spring Boot example

{{greeting}}

Please log in (tom and sally are valid names)

Username:

Error:

{{error.data.message}}

Success! Welcome {{userName}}

(logout)

{{userName}} is a
User
Admin
Foo

app.js

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

appModule.controller(‘MainCtrl’, [‘mainService’,‘ s c o p e ′ , ′ scope',' 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;

});

}

};

});

运行应用

效果

原文链接:https://blog.csdn.net/change_on/article/details/76279441

版权声明:本文为CSDN博主「J_小浩子」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

近期热文推荐:

1.1,000+ 道 Java面试题及答案整理(2021最新版)

最后

金三银四到了,送上一个小福利!

image.png

image.png

专题+大厂.jpg
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

效果

原文链接:https://blog.csdn.net/change_on/article/details/76279441

版权声明:本文为CSDN博主「J_小浩子」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

近期热文推荐:

1.1,000+ 道 Java面试题及答案整理(2021最新版)

最后

金三银四到了,送上一个小福利!

[外链图片转存中…(img-MQRdvXbs-1714699765468)]

[外链图片转存中…(img-CCIO1Opz-1714699765468)]

[外链图片转存中…(img-UHOCEt5h-1714699765468)]
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

  • 29
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值