1.客户端Token方案
1.1 实现思路
简单客户端token校验.vsdx(57 KB)
客户端
服务端
用户
1.发起请求
2.登录验证
3.验证登陆账户是否
正确,正确则生成
token,redis满存并返
4响应结果
5.验证登陆是否成功
6登陆失败,系统汽宋-
循环
7.携带token请求接口
8.过滤器验证token是
否正确,正确允许接
口,请求否错误提
系统维末
1.2 实现细节
参考:https://www.cnblogs.com/dalaoyang/p/11783225.html
2.JWT + Security
●RFC7519
●JWT
JWT很大程度上还是个新技术,通过使用HMAC(Hash-based Message Authentication Code)计算信息摘要,也可以用RSA公私钥中的私钥进行签名。这个根据业务场景进行选择。
2.1 pom依赖
在/login进行登录并获得Token。剩余接口做token验签,这里我们需要将spring-boot-starter-security加入pom.xml。加入后,我们的Spring Boot项目将需要提供身份验证,相关的pom.xml如下:
至此我们剩余所有的路由都需要身份验证。我们将引入一个安全设置类WebSecurityConfig,这个类需要从WebSecurityConfigurerAdapter类继承。
2.2 安全设置类WebSecurityConfig
先放两个基本类,一个负责存储用户名密码,另一个是一个权限类型,负责存储权限和角色。
2.3 权限类型及角色类
2.4 用户名密码类
在上面的安全设置类中,我们设置所有人都能访问/和POST方式访问/login,其他的任何路由都需要进行认证。然后将所有访问/login的请求,都交给JWTLoginFilter过滤器来处理。稍后我们会创建这个过滤器和其他这里需要的JWTAuthenticationFilter和CustomAuthenticationProvider两个类。
2.5 JWT生成及验签类
这个类就两个static方法,一个负责生成JWT,一个负责认证JWT最后生成验证令牌。注释已经写得很清楚了,这里不多说了。
下面来看自定义验证组件,这里简单写了,这个类就是提供密码验证功能,在实际使用时换成自己相应的验证逻辑,从数据库中取出、比对、赋予用户相应权限。
2.6 自定义验证组件类
2.7 接口类
下面实现JWTLoginFilter 这个Filter比较简单,除了构造函数需要重写三个方法。
●attemptAuthentication - 登录时需要验证时候调用
●successfulAuthentication - 验证成功后调用
●unsuccessfulAuthentication - 验证失败后调用,这里直接灌入500错误返回,由于同一JSON返回,HTTP就都返回200了
2.8 JWTLoginFilter
Java
运行代码复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.framework.client.dto.response.JSONResultDTO;
import com.test.framework.web.domain.vo.AccountCredentials;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
public JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(
HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException, IOException, ServletException {
// JSON反序列化成 AccountCredentials
AccountCredentials creds = new ObjectMapper().readValue(req.getInputStream(), AccountCredentials.class);
// 返回一个验证令牌
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword()
)
);
}
@Override
protected void successfulAuthentication(
HttpServletRequest req,
HttpServletResponse res, FilterChain chain,
Authentication auth) throws IOException, ServletException {
TokenAuthenticationService.addAuthentication(res, auth.getName());
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().println(JSONResult.fillResultString(500, "Internal Server Error!!!", JSONObject.NULL));
}
}
再完成最后一个类JWTAuthenticationFilter,这也是个拦截器,它拦截所有需要JWT的请求,然后调用TokenAuthenticationService类的静态方法去做JWT验证。
2.9 拦截器JWTAuthenticationFilter
Java
运行代码复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
class JWTAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
Authentication authentication = TokenAuthenticationService
.getAuthentication((HttpServletRequest)request);
SecurityContextHolder.getContext()
.setAuthentication(authentication);
filterChain.doFilter(request,response);
}
}
现在代码就写完了,整个Spring Security结合JWT基本就差不多了,下面我们来测试下,并说下整体流程。
开始测试,先运行整个项目,这里介绍下过程:
●先程序启动 - main函数
●注册验证组件 - WebSecurityConfig 类 configure(AuthenticationManagerBuilder auth)方法,这里我们注册了自定义验证组件
●设置验证规则 - WebSecurityConfig 类 configure(HttpSecurity http)方法,这里设置了各种路由访问规则
●初始化过滤组件 - JWTLoginFilter 和 JWTAuthenticationFilter 类会初始化