JWT前后端分离,交互流程
1.客户端通过用户名、密码请求服务器端登录
2.服务器验证用户名、密码通过后、生成token返回到客户端
3.客户端拿到token后存储到客户端本地,h5可存储到本地localstorage中
4.客户端所有请求需要登录后、才允许发送的请求、需要在header头添加token
5.服务器从header头拿到token解析、解析成功后执行业务逻辑、解析失败返回状态403、客户端获取403状态后需跳转登录页面重新登录
集成步骤
1.pom.xml添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
2.增加相关Java配置
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private TokenUtil tokenUtil;
@Override
public void configure(WebSecurity web) throws Exception {
// Filters will not get executed for the resources
web.ignoring().antMatchers("/", "/resources/**", "/static/**", "/public/**", "/webui/**", "/h2-console/**"
, "/configuration/**", "/swagger-ui/**", "/swagger-resources/**", "/api-docs", "/api-docs/**", "/v2/api-docs/**"
, "/*.html", "/**/*.html" ,"/**/*.css","/**/*.js","/**/*.png","/**/*.jpg", "/**/*.gif", "/**/*.svg", "/**/*.ico", "/**/*.ttf","/**/*.woff","/**/*.otf");
}
//If Security is not working check application.properties if it is set to ignore
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().and()
.anonymous().and()
// Disable Cross site references
.csrf().disable()
// Add CORS Filter
.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)
// Custom Token based authentication based on the header previously given to the client
.addFilterBefore(new VerifyTokenFilter(tokenUtil), UsernamePasswordAuthenticationFilter.class)
// custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
.authorizeRequests()
.anyRequest().authenticated()
;
}
}
@Service
@Slf4j
public class TokenUtil {
//private static final long VALIDITY_TIME_MS = 10 * 24 * 60 * 60 * 1000;// 10 days Validity
// 2 hours validity
private static final long VALIDITY_TIME_MS = 2 * 60 * 60 * 1000;
private static final String AUTH_HEADER_NAME = "Authorization";
public static final String REDIS_TOKEN_KEY = "redis_token_key!@#@#@%%^&";