spring-boot-starter-web
${spring.boot.version}
commons-io
commons-io
${commons.io.version}
io.jsonwebtoken
jjwt
${jjwt.version}
junit
junit
${junit.version}
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>
{{greeting}}
Please log in (tom and sally are valid names)
Username:
Error:
{{error.data.message}}
Success! Welcome {{userName}}
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;
});
}
};
});
最后
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Java开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
return response.data;
});
}
};
});
最后
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-TnhioVk0-1715790321916)]
[外链图片转存中…(img-ttuhX9e4-1715790321917)]
[外链图片转存中…(img-I72phRBZ-1715790321917)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Java开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!