Skip to content

Commit

Permalink
SpringBoot2.0 整合 JWT 框架,解决Token跨域验证问题
Browse files Browse the repository at this point in the history
  • Loading branch information
cicadasmile committed Jul 10, 2019
1 parent a60dcb7 commit 36413ab
Show file tree
Hide file tree
Showing 9 changed files with 252 additions and 1 deletion.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@
<a href="https://mp.weixin.qq.com/s?__biz=MzU4Njg0MzYwNw==&mid=2247483895&idx=1&sn=4fdc2a307b49a66c37c22c7de62aa323&chksm=fdf4554fca83dc5935e3f36c541a5e03cedd440e14eafa1a577b52f047d98b79b9af891f7330&token=989276463&lang=zh_CN#rd">
7、SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用</a><br/>

<a href="">
<a href="https://mp.weixin.qq.com/s?__biz=MzU4Njg0MzYwNw==&mid=2247483905&idx=1&sn=f15ecc1ab3065c24854a02741db0aa0c&chksm=fdf456b9ca83dfaf937f370981432f98d2c5d7d0c7638df6206ffd22c2db79b7924c19e90931&token=935482848&lang=zh_CN#rd">
8、SpringBoot2.0 整合 ElasticSearch框架,实现高性能搜索引擎</a><br/>

<a href="">
9、SpringBoot2.0 整合 JWT 框架,解决Token跨域验证问题</a><br/>

持续更新中...

## 项目简介
Expand Down
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
<module>ware-dubbo-parent</module>
<!-- ElasticSearch 搜索框架 -->
<module>ware-elastic-search</module>
<!-- JWT TOKEN 验证 -->
<module>ware-jwt-token</module>
</modules>

<!-- 依赖版本管理 -->
Expand Down
48 changes: 48 additions & 0 deletions ware-jwt-token/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starters</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jwt.token</groupId>
<artifactId>ware-jwt-token</artifactId>
<packaging>jar</packaging>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
</dependencies>

<!-- 项目构建 -->
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
11 changes: 11 additions & 0 deletions ware-jwt-token/src/main/java/com/jwt/token/JwtApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.jwt.token;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JwtApplication {
public static void main(String[] args) {
SpringApplication.run(JwtApplication.class,args) ;
}
}
66 changes: 66 additions & 0 deletions ware-jwt-token/src/main/java/com/jwt/token/config/JwtConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.jwt.token.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;

@ConfigurationProperties(prefix = "config.jwt")
@Component
public class JwtConfig {
/*
* 根据身份ID标识,生成Token
*/
public String getToken (String identityId){
Date nowDate = new Date();
//过期时间
Date expireDate = new Date(nowDate.getTime() + expire * 1000);
return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setSubject(identityId)
.setIssuedAt(nowDate)
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
/*
* 获取 Token 中注册信息
*/
public Claims getTokenClaim (String token) {
try {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/*
* Token 是否过期验证
*/
public boolean isTokenExpired (Date expirationTime) {
return expirationTime.before(new Date());
}
private String secret;
private long expire;
private String header;
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public long getExpire() {
return expire;
}
public void setExpire(long expire) {
this.expire = expire;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
}
20 changes: 20 additions & 0 deletions ware-jwt-token/src/main/java/com/jwt/token/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.jwt.token.config;

import com.jwt.token.interceptor.TokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 拦截器注册
*/
@Resource
private TokenInterceptor tokenInterceptor ;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tokenInterceptor).addPathPatterns("/**");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.jwt.token.controller;

import com.jwt.token.config.JwtConfig;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class TokenController {
@Resource
private JwtConfig jwtConfig ;
/*
* 返参格式
* {
* "userName": "ID123",
* "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.
* eyJzdWIiOiJJRDEyM3B3MTIzIiwiaWF0Ijox.
* SqqaZfG_g2OMijyN5eG0bPmkIQaqMRFlUvny"
* }
*/
// 拦截器直接放行,返回Token
@PostMapping("/login")
public Map<String,String> login (@RequestParam("userName") String userName,
@RequestParam("passWord") String passWord){
Map<String,String> result = new HashMap<>() ;
// 省略数据源校验
String token = jwtConfig.getToken(userName+passWord) ;
if (!StringUtils.isEmpty(token)) {
result.put("token",token) ;
}
result.put("userName",userName) ;
return result ;
}
// 需要 Token 验证的接口
@PostMapping("/info")
public String info (){
return "info" ;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.jwt.token.interceptor;

import com.jwt.token.config.JwtConfig;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Token 拦截器
*/
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {
@Resource
private JwtConfig jwtConfig ;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
// 地址过滤
String uri = request.getRequestURI() ;
if (uri.contains("/login")){
return true ;
}
// Token 验证
String token = request.getHeader(jwtConfig.getHeader());
if(StringUtils.isEmpty(token)){
token = request.getParameter(jwtConfig.getHeader());
}
if(StringUtils.isEmpty(token)){
throw new Exception(jwtConfig.getHeader()+ "不能为空");
}
Claims claims = jwtConfig.getTokenClaim(token);
if(claims == null || jwtConfig.isTokenExpired(claims.getExpiration())){
throw new Exception(jwtConfig.getHeader() + "失效,请重新登录");
}
//设置 identityId 用户身份ID
request.setAttribute("identityId", claims.getSubject());
return true;
}
}
13 changes: 13 additions & 0 deletions ware-jwt-token/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
server:
port: 7009
spring:
application:
name: ware-jwt-token
config:
jwt:
# 加密密钥
secret: iwqjhda8232bjgh432[cicada-smile]
# token有效时长
expire: 3600
# header 名称
header: token

0 comments on commit 36413ab

Please sign in to comment.