SpringSecurity-02-微服务与授权
微服务架构的授权方式

WebSocket 和 Redis 缓存token Jwt 按照特定规则生成字符串
在微服务架构中使用SpringSecurity一般会重写PasswordEncoder这个接口,接口重写的方法:
@Component
public class DefaultPasswordEncoder implements PasswordEncoder {
@Overrider
public String encode(CharSequence charSequence){
//使用MD5的方式进行加密
return MD5.encrypt(charSequence.toString);
}
@Override
public boolean matches(CharSequence charSequence.String
encodePassword){
return encodedPassword.equals(MD5.encrypt(charSequence.toString()));
}
}
使用jwt生成token,存到Redis中,颁发给用户,用户存到Session内,每一次发送请求的时候,都将token取出放在headers内携带着一起发请求,headers取出token与Redis内的比较,判断用户的权限,再从token中取信息去Redis中查权限表。即登录时将权限表上传到Redis中,根据用户的token从Redis中再取出权限表,这样多了一步验证,然后每次请求的时候都要判断token是否一致,而且用户是否拥有权限。这样每次更新权限的时候,修改完数据库的权限表,再修改Redis缓存里的权限表即可,请求时重新拉取权限表。
首先引入Jwt
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
自定义认证授权的方法
继承两个Filter 修改认证授权过程 一个是UsernamePasswordAuthenticationFilter
要重写三个方法
①public Authentication attemptAuthentication
②protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,FilterChain chain)
③protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
第二个是BasicAuthenticationFilter 重写doFilterInternal方法
即可实现自定义认证授权
浙公网安备 33010602011771号