分布式认证即用户只需要登录一次就可以访问所有互相信任的子系统。在每台服务中都有一个 session 但是各个 session 之间时无法共享资源的,所以 session 不能作为单点登录的解决方案。单点登录一般分为两个部分:
♞ 用户认证
:这一环节主要是用户向认证服务发起认证请求,认证服务给用户返回一个成功的令牌 token,主要在认证服务中完成,注意认证服务只能有一个。
♞ 身份校验
:这一环节是用户携带 token 去访问其他服务时,在其他服务中要对 token 的真伪进行检验,主要在资源服务中完成,资源服务可以有很多个。
从分布式认证流程中,我们不难发现,这中间起最关键作用的就是 token,token 的安全与否,直接关系到系统的健壮性,本篇我们选择使用 JWT 来实现 token 的生成和校验。
JWT(JSON Web Token)是一个十分优秀的分布式认证解决方案,JWT 是一套开放的标准(RFC 7519),它定义了一种紧凑且自 URL 安全的方式,以 JSON 对象的方式在各方之间安全地进行信息传输。由于此信息是经过数字签名的,因此是可以被验证和信任的。可以使用密钥(secret)使用HMAC算法或者使用 RSA 或 ECDSA 的公有/私有密钥对 JWT 进行签名。JWT 生成的 token 由三部分组成:
♞ 头部
:主要设置一些规范信息,签名部分的编码格式就在头部中声明
♞ 载荷
:token 中存放有效信息的部分,比如用户名,用户角色,过期时间等,但是不要放密码,会泄露
♞ 签名
:将头部与载荷分别采用 base64 编码后,用.
相连,再加入盐,最后使用头部声明的编码类型进行编码,就得到了签名
虽然可以对 JWT 进行加密用来在各方之间提供保密性,但我们还是重点关注下签名的令牌(token)本身,签名的令牌可以验证其中包含的声明的完整性,而加密的令牌则将这些声明在其他方的面前进行隐藏,以提供安全性。当使用公钥/私钥对对令牌进行签名时,签名还可以证明只有持有私钥的一方才是对其进行签名的一方。
RSA 是 1977 年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA 就是他们三人姓氏开头字母拼在一起组成的。RSA 公开密钥密码体制是一种使用不同的加密密钥与解密密钥,由已知加密密钥推导出解密密钥在计算上是不可行的密码体制 。
在公开密钥密码体制中,加密密钥(即公钥 PK)是公开信息,而解密密钥(即私钥 SK)是需要保密的。虽然私钥是由公钥决定的,但却不能根据公钥计算出私钥 。正是基于这种理论,1978 年出现了著名的 RSA 算法,它通常是先生成一对 RSA 密钥,其中之一是私钥,由用户保存;另一个为公钥,可对外公开,甚至可在网络服务器中注册。
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.9version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-loggingartifactId>
<version>2.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>joda-timegroupId>
<artifactId>joda-timeartifactId>
<version>2.9.9version>
dependency>
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description Json 工具类
*/
public class JsonUtils {
public static final ObjectMapper mapper = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
public static String toString(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("json序列化出错:" + obj, e);
return null;
}
}
public static <T> T toBean(String json, Class<T> tClass) {
try {
return mapper.readValue(json, tClass);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <E> List<E> toList(String json, Class<E> eClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <T> T nativeRead(String json, TypeReference<T> type) {
try {
return mapper.readValue(json, type);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
}
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description 载荷类,token 中存放有效信息
*/
@Data
public class Payload<T> {
private String id;
private T userInfo;
private Date expiration;
}
<dependency>
<groupId>io.jsonwebtokengroupId>
<artifactId>jjwt-apiartifactId>
<version>0.10.7version>
dependency>
<dependency>
<groupId>io.jsonwebtokengroupId>
<artifactId>jjwt-implartifactId>
<version>0.10.7version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>io.jsonwebtokengroupId>
<artifactId>jjwt-jacksonartifactId>
<version>0.10.7version>
<scope>runtimescope>
dependency>
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description JWT 工具类
*/
public class JwtUtils {
private static final String JWT_PAYLOAD_USER_KEY = "user";
/**
* 私钥加密token
*
* @param userInfo 载荷中的数据
* @param privateKey 私钥
* @param expire 过期时间,单位分钟
* @return JWT
*/
public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusMinutes(expire).toDate())
.signWith(privateKey)
.compact();
}
/**
* 私钥加密token
*
* @param userInfo 载荷中的数据
* @param privateKey 私钥
* @param expire 过期时间,单位秒
* @return JWT
*/
public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.signWith(privateKey)
.compact();
}
/**
* 公钥解析token
*
* @param token 用户请求中的token
* @param publicKey 公钥
* @return Jws
*/
private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
private static String createJTI() {
return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
*/
public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload<T> claims = new Payload<>();
claims.setId(body.getId());
claims.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
claims.setExpiration(body.getExpiration());
return claims;
}
/**
* 获取token中的载荷信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
*/
public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload<T> claims = new Payload<>();
claims.setId(body.getId());
claims.setExpiration(body.getExpiration());
return claims;
}
}
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description RSA 工具类
*/
public class RsaUtils {
private static final int DEFAULT_KEY_SIZE = 2048;
/**
* 从文件中读取公钥
*
* @param filename 公钥保存路径,相对于classpath
* @return 公钥对象
* @throws Exception
*/
public static PublicKey getPublicKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPublicKey(bytes);
}
/**
* 从文件中读取密钥
*
* @param filename 私钥保存路径,相对于classpath
* @return 私钥对象
* @throws Exception
*/
public static PrivateKey getPrivateKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPrivateKey(bytes);
}
/**
* 获取公钥
*
* @param bytes 公钥的字节形式
* @return
* @throws Exception
*/
private static PublicKey getPublicKey(byte[] bytes) throws Exception {
bytes = Base64.getDecoder().decode(bytes);
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
/**
* 获取密钥
*
* @param bytes 私钥的字节形式
* @return
* @throws Exception
*/
private static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
bytes = Base64.getDecoder().decode(bytes);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(spec);
}
/**
* 根据密文,生存rsa公钥和私钥,并写入指定文件
*
* @param publicKeyFilename 公钥文件路径
* @param privateKeyFilename 私钥文件路径
* @param secret 生成密钥的密文
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret, int keySize)
throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 获取公钥并写出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
publicKeyBytes = Base64.getEncoder().encode(publicKeyBytes);
writeFile(publicKeyFilename, publicKeyBytes);
// 获取私钥并写出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
privateKeyBytes = Base64.getEncoder().encode(privateKeyBytes);
writeFile(privateKeyFilename, privateKeyBytes);
}
private static byte[] readFile(String fileName) throws Exception {
return Files.readAllBytes(new File(fileName).toPath());
}
private static void writeFile(String destPath, byte[] bytes) throws IOException {
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
Files.write(dest.toPath(), bytes);
}
}
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/20
* @description 测试 RsaUtils
*/
public class RsaTest {
// 指定公钥和私钥的路径
private String publicKeyFile = "C:\\Users\\softw\\Desktop\\key\\pub_key";
private String privateKeyFile = "C:\\Users\\softw\\Desktop\\key\\pri_key";
/**
* 测试生成密钥
* @author Demo_Null
* @date 2020/10/20
* @param
* @return void
**/
@Test
public void generateKey() throws Exception {
RsaUtils.generateKey(publicKeyFile, privateKeyFile, "Demo_Null", 2048);
}
/**
* 测试获取公钥
* @author Demo_Null
* @date 2020/10/20
* @param
* @return void
**/
@Test
public void getPublicKey() throws Exception {
System.out.println(RsaUtils.getPublicKey(publicKeyFile));
}
/**
* 测试获取私钥
* @author Demo_Null
* @date 2020/10/20
* @param
* @return void
**/
@Test
public void getPrivateKey() throws Exception {
System.out.println(RsaUtils.getPrivateKey(privateKeyFile));
}
}
Spring Security 主要是通过过滤器链来实现认证和身份校验的,我们重点来看一下用户认证和身份校验的过滤器。在分布式中我们需要重写的也就是以下几个过滤器。
☞ UsernamePasswordAuthenticationFilter
AbstractAuthenticationProcessingFilter.doFilter() 调用 UsernamePasswordAuthenticationFilter 中的 attemptAuthentication 实现认证功能,该方法将表单请求(POST)的信息赋值给 UsernamePasswordAuthenticationToken (authRequest),然后调用 getAuthenticationManager().authenticate(authRequest) 对用户密码的正确性进行验证,认证失败就抛出异常,成功就返回 Authentication 对象。
☞ AbstractAuthenticationProcessingFilter
第二个过滤器就是 UsernamePasswordAuthenticationFilter 的父类 AbstractAuthenticationProcessingFilter, 该过滤器中提供 successfulAuthentication 方法进行验证用户是否登录,认证通过之后将认证信息存放到 session。
☞ BasicAuthenticationFilter
BasicAuthenticationFilter 过滤器中 doFilterInternal 方法会去验证 session 中是否由用户信息来判断用户是否登录,验证成功则放行,验证失败则抛出异常。
☞ 用户认证
由于,分布式项目,多数是前后端分离的架构设计,我们要满足可以接受异步 POST 的认证请求参数,需要修改 UsernamePasswordAuthenticationFilter 过滤器中 attemptAuthentication 方法,让其能够接收请求体。另外,默认 successfulAuthentication 方法在认证通过后,是把用户信息直接放入 session 就完事了,现在我们需要修改这个方法,在认证通过后生成 token 并返回给用户。
☞ 身份校验
原本的 BasicAuthenticationFilter 过滤器中 doFilterlnternal 方法校验用户是否登录,就是看 session 中是否有用户信息,我们要修改为,验证用户携带的 token 是否合法,并解析出用户信息,交给 SpringSecurity,以便于后续的授权功能可以正常使用。
像这种其他服务也会使用到的实体类我们一般会将其放到一个单独的模块中,这里为了省事直接放到了 utils 模块中。对于这两个类不熟悉的可以看 Spring Security 在 Spring Boot 中的使用【集中式】
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description 角色类
*/
public class SysRole implements GrantedAuthority {
private Integer id;
private String roleName;
private String roleDesc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@JsonIgnore
@Override
public String getAuthority() {
return roleName;
}
}
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description 用户类
*/
public class SysUser implements UserDetails {
private Integer id;
private String username;
private String password;
private Integer status;
private List<SysRole> roles;
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
}
# 省略数据库操作配置
server:
port: 8081
rsa:
key:
public: "C:\Users\softw\Desktop\key\pub_key"
private: "C:\\Users\\softw\\Desktop\\key\\pri_key"
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description 解析公钥私钥配置类
*/
@Component // 也可以启动类 @EnableConfigurationProperties(RsaKeyProperties.class) 注解进行配置
@ConfigurationProperties("rsa.key")
public class RsaKeyProperties {
// 注意与配置文件中的参数名保持一致,否则不会注入
private String pubKeyFile;
private String priKeyFile;
private PublicKey publicKey;
private PrivateKey privateKey;
@PostConstruct
public void createRsaKey() throws Exception {
publicKey = RsaUtils.getPublicKey(pubKeyFile);
privateKey = RsaUtils.getPrivateKey(priKeyFile);
}
public String getPubKeyFile() {
return pubKeyFile;
}
public void setPubKeyFile(String pubKeyFile) {
this.pubKeyFile = pubKeyFile;
}
public String getPriKeyFile() {
return priKeyFile;
}
public void setPriKeyFile(String priKeyFile) {
this.priKeyFile = priKeyFile;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
public PrivateKey getPrivateKey() {
return privateKey;
}
public void setPrivateKey(PrivateKey privateKey) {
this.privateKey = privateKey;
}
}
☞ UsernamePasswordAuthenticationFilter
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description 重写 attemptAuthentication 和 successfulAuthentication 方法
*/
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
// 不属于 Ioc 管理,无法注入,只能通过构造方法
private AuthenticationManager authenticationManager;
private RsaKeyProperties prop;
/**
* 构造方法,谁使用谁提供 AuthenticationManager,RsaKeyProperties
* @author Demo_Null
* @date 2020/10/20
* @param authenticationManager
* @param prop
* @return
**/
public JwtLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
this.authenticationManager = authenticationManager;
this.prop = prop;
}
/**
* 提供用户认证
* @author Demo_Null
* @date 2020/10/20
* @param request
* @param response
* @return org.springframework.security.core.Authentication
**/
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
try {
// 获取用户登录信息,由于这里前端参数是 application/json 所以不能使用 getParameter 获取
SysUser sysUser = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
// 验证并返回用户登录结果
return authenticationManager.authenticate(authRequest);
}catch (Exception e){
try {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_UNAUTHORIZED);
resultMap.put("msg", "用户名或密码错误!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
}catch (Exception outEx){
outEx.printStackTrace();
}
throw new RuntimeException(e);
}
}
/**
* 认证成功后返回 token
* @author Demo_Null
* @date 2020/10/20
* @param request
* @param response
* @param chain
* @param authResult
* @return void
**/
public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain chain, Authentication authResult) throws IOException, ServletException {
SysUser user = new SysUser();
user.setUsername(authResult.getName());
user.setRoles((List<SysRole>) authResult.getAuthorities());
// 生成 token, 最后一个参数为过期时间单位是分钟
String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey(), 24 * 60);
// 返回 token
response.addHeader("Authorization", "Bearer " + token);
try {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_OK);
resultMap.put("msg", "认证通过!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
}catch (Exception outEx){
outEx.printStackTrace();
}
}
}
☞ BasicAuthenticationFilter
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description 重写 doFilterInternal
*/
public class JwtVerifyFilter extends BasicAuthenticationFilter {
private RsaKeyProperties prop;
public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
super(authenticationManager);
this.prop = prop;
}
/**
* 验证用户携带的 token 是否正确
* @author [email protected]
* @date 2020/10/20
* @param request
* @param response
* @param chain
* @return void
**/
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 请求头中是否包含了认证信息
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
// 如果携带错误的 token,则给用户提示请登录!
chain.doFilter(request, response);
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
resultMap.put("msg", "请登录!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
} else {
try {
// 如果携带了正确格式的 token 要先得到 token
String token = header.replace("Bearer ", "");
// 验证 token 是否正确
Payload<SysUser> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), SysUser.class);
SysUser user = payload.getUserInfo();
if(user!=null){
UsernamePasswordAuthenticationToken authResult =
new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());
// 认证信息放到 session
SecurityContextHolder.getContext().setAuthentication(authResult);
// 放行
chain.doFilter(request, response);
}
} catch (Exception e) {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_UNAUTHORIZED);
resultMap.put("msg", "认证失败!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
}
}
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RsaKeyProperties prop;
@Autowired
private UserServiceImpl UserServiceImpl;
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//指定认证对象的来源
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(UserServiceImpl).passwordEncoder(passwordEncoder());
}
//SpringSecurity配置信息
public void configure(HttpSecurity http) throws Exception {
http.csrf() // 关闭 csrf
.disable()
// 授权后才能访问
.authorizeRequests()
.anyRequest().authenticated()
.and()
// 自定义过滤器
.addFilter(new JwtLoginFilter(super.authenticationManager(), prop))
.addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
// 禁用 session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
需要注意的是,请求参数不要使用 form 表单,要使用 json,返回的 token 在头里面。
# 省略数据库等配置
server:
port: 8082
rsa:
key:
# 此处一定不要有私钥
pubKeyFile: 'C:\Users\softw\Desktop\key\pub_key'
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description 解析公钥配置类, 私钥只能认证服务含有
*/
@Component
@ConfigurationProperties("rsa.key")
public class RsaKeyProperties {
private String pubKeyFile;
private PublicKey publicKey;
@PostConstruct
public void createRsaKey() throws Exception {
publicKey = RsaUtils.getPublicKey(pubKeyFile);
}
public String getPubKeyFile() {
return pubKeyFile;
}
public void setPubKeyFile(String pubKeyFile) {
this.pubKeyFile = pubKeyFile;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
}
这里直接拷贝认证服务中的 JwtVerifyFilter,在资源服务中只需要验证 token 是否正确。
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/19
* @description 重写 doFilterInternal
*/
public class JwtVerifyFilter extends BasicAuthenticationFilter {
private RsaKeyProperties prop;
public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
super(authenticationManager);
this.prop = prop;
}
/**
* 验证用户携带的 token 是否正确
* @author [email protected]
* @date 2020/10/20
* @param request
* @param response
* @param chain
* @return void
**/
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 请求头中是否包含了认证信息
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
// 如果携带错误的 token,则给用户提示请登录!
chain.doFilter(request, response);
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
resultMap.put("msg", "请登录!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
} else {
try {
// 如果携带了正确格式的 token 要先得到 token
String token = header.replace("Bearer ", "");
// 验证 token 是否正确
Payload<SysUser> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), SysUser.class);
SysUser user = payload.getUserInfo();
if(user!=null){
UsernamePasswordAuthenticationToken authResult =
new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());
// 认证信息放到 session
SecurityContextHolder.getContext().setAuthentication(authResult);
// 放行
chain.doFilter(request, response);
}
} catch (Exception e) {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_UNAUTHORIZED);
resultMap.put("msg", "认证失败!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
}
}
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RsaKeyProperties prop;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
//SpringSecurity配置信息
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/10/20
* @description 测试接口
*/
@RestController
@RequestMapping("/demo")
public class DemoController {
@GetMapping("/find")
@Secured("ROLE_USER")
public String find() {
return "查询成功!";
}
}
☞ GitHub