说明
Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密。网上关于JWT,cookie,session的讨论和比较太多了,笔者就不讨论了,直接撸代码吧- -
官网:https://jwt.io/
JWT工作流程图:
步骤
1 引入JJWT
JJWT是JWT的第三方开源的一个实现库,使用JJWT比自己再实现JWT会方便很多
github:https://github.com/jwtk/jjwt
maven:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec ,BASE64编码需要 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt ,JJWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
2 编写启动类
package test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import test.filter.JwtFilter;
// @SpringBootApplication声明让spring boot自动给程序进行必要的配置
@SpringBootApplication
public class SpringBootApp {
//过滤器
@Bean
public FilterRegistrationBean jwtFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/api/*"); //设置过滤的url
return registrationBean;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
3 配置全局变量
pac