1. 程式人生 > 其它 >SpringSecurity-02-微服務與授權

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方法

即可實現自定義認證授權