SpringBoot+Security+JWT進階:一缘滥、自定義認證

title: SpringBoot+Security+JWT進階:一、自定義認證
date: 2019-07-04
author: maxzhao
tags:
- JAVA
- SpringBoot
- Security
- JWT
- Authentication
categories:
- SpringBoot
- Security+JWT

這里談談自定義認證

不使用自定義認證的 WebSecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Resource(name = "userDetailsService")
    private UserDetailsService userDetailsService;
    @Resource(name = "passwordEncoder")
    private PasswordEncoder passwordEncoder;
//**********************
// 略
//**********************

    /**
     * 身份驗證
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder)
        ;

    }
}

不使用自定義認證的驗證類 AbstractUserDetailsAuthenticationProvider

這里只看 authenticate驗證的方法造成,根據(jù)自己的理解趁餐,我寫上了注釋,//// 為重點強調

public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
    // 對 supports 方法的二次校驗菇绵,為空或不等拋出錯誤
        Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
                () -> messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.onlySupports",
                        "Only UsernamePasswordAuthenticationToken is supported"));

        // Determine username肄渗,authentication.getPrincipal()獲取的就是UserDetail
        String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
                : authentication.getName();
        // 默認情況下從緩存中(UserCache接口實現(xiàn))取出用戶信息
        boolean cacheWasUsed = true;
        UserDetails user = this.userCache.getUserFromCache(username);
        if (user == null) {
            // 如果從緩存中取不到用戶,則設置cacheWasUsed 為false咬最,供后面使用
            cacheWasUsed = false;
            try {
                // retrieveUser是抽象方法恳啥,通過子類來實現(xiàn)獲取用戶的信息,以UserDetails接口形式返回,默認的子類為 DaoAuthenticationProvider
                user = retrieveUser(username,
                        (UsernamePasswordAuthenticationToken) authentication);
            }
            //// 這就是為什么 UsernameNotFoundException 拋出信息卻獲取不到的原因
            catch (UsernameNotFoundException notFound) {
                logger.debug("User '" + username + "' not found");
                if (hideUserNotFoundExceptions) {
                    throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials","Bad credentials"));
                }
                else {
                    throw notFound;
                }
            }
            Assert.notNull(user,
                    "retrieveUser returned null - a violation of the interface contract");
        }
        try {// 驗證帳號是否鎖定\是否禁用\帳號是否到期
            preAuthenticationChecks.check(user);
            // 進一步驗證憑證 和 密碼
            additionalAuthenticationChecks(user,
                    (UsernamePasswordAuthenticationToken) authentication);
        }
        catch (AuthenticationException exception) {
            if (cacheWasUsed) {// 如果是內存用戶丹诀,則再次獲取并驗證
                // There was a problem, so try again after checking
                // we're using latest data (i.e. not from the cache)
                cacheWasUsed = false;
                user = retrieveUser(username,
                        (UsernamePasswordAuthenticationToken) authentication);
                preAuthenticationChecks.check(user);
                additionalAuthenticationChecks(user,
                        (UsernamePasswordAuthenticationToken) authentication);
            }
            else {
                throw exception;
            }
        }
        //驗證憑證是否已過期
        postAuthenticationChecks.check(userDetail);
    //如果沒有緩存則進行緩存,此處的 userCache是 由 NullUserCache 類實現(xiàn)的,名如其義翁垂,該類的 putUserInCache 沒做任何事
        //也可以使用緩存 比如 EhCacheBasedUserCache  或者 SpringCacheBasedUserCache
        if (!cacheWasUsed) {
            this.userCache.putUserInCache(user);
        }
        //以下代碼主要是把用戶的信息和之前用戶提交的認證信息重新組合成一個 authentication 實例返回铆遭,返回類是 UsernamePasswordAuthenticationToken 類的實例
        Object principalToReturn = user;

        if (forcePrincipalAsString) {
            principalToReturn = user.getUsername();
        }

        return createSuccessAuthentication(principalToReturn, authentication, user);
    }
@startuml
Title "Authentication類圖"
interface Principal
interface Authentication
interface AuthenticationManager
interface AuthenticationProvider
abstract class AbstractUserDetailsAuthenticationProvider
class ProviderManager
class DaoAuthenticationProvider
interface UserDetailsService


Principal <|-- Authentication
Authentication <.. AuthenticationManager
AuthenticationManager <|-- ProviderManager
ProviderManager  o--> AuthenticationProvider
AuthenticationProvider <|.. AbstractUserDetailsAuthenticationProvider
AbstractUserDetailsAuthenticationProvider <|-- DaoAuthenticationProvider
UserDetailsService <.. AbstractUserDetailsAuthenticationProvider

interface AuthenticationManager{
# Authentication authenticate(Authentication authentication)
            throws AuthenticationException;
}
abstract class AbstractUserDetailsAuthenticationProvider{
+ public Authentication authenticate(Authentication authentication)
            throws AuthenticationException;
+public boolean supports(Class<?> authentication);
}
@enduml

使用自定義認證的 WebSecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
    
    private PasswordEncoder passwordEncoder;
    @Resource(name = "authenticationProvider")
    private AuthenticationProvider authenticationProvider;
//**********************
// 略
//**********************

    /**
     * 身份驗證
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .authenticationProvider(authenticationProvider)
        ;

    }
}

自定義認證類 AuthenticationProviderImpl

/**
 * AuthenticationProviderImpl
 * 自定義認證服務
 *
 * @author maxzhao
 * @date 2019-05-23 15:43
 */
@Service("authenticationProvider")
public class AuthenticationProviderImpl implements AuthenticationProvider {
    @Resource(name = "userDetailsService")
    private UserDetailsService userDetailsService;

    @Resource(name = "passwordEncoder")
    private PasswordEncoder passwordEncoder;

    /**
     *
     * @param authenticate
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authenticate) throws AuthenticationException {
        UsernamePasswordAuthenticationToken token
                = (UsernamePasswordAuthenticationToken) authenticate;
        String username = token.getName();
        UserDetails userDetails = null;

        if (username != null) {
            userDetails = userDetailsService.loadUserByUsername(username);
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException("用戶名/密碼無效");
        } else if (!userDetails.isEnabled()) {
            System.out.println("jinyong用戶已被禁用");
            throw new DisabledException("用戶已被禁用");
        } else if (!userDetails.isAccountNonExpired()) {
            System.out.println("guoqi賬號已過期");
            throw new AccountExpiredException("賬號已過期");
        } else if (!userDetails.isAccountNonLocked()) {
            System.out.println("suoding賬號已被鎖定");
            throw new LockedException("賬號已被鎖定");
        } else if (!userDetails.isCredentialsNonExpired()) {
            System.out.println("pingzheng憑證已過期");
            throw new CredentialsExpiredException("憑證已過期");
        }
        String password = userDetails.getPassword();
        //與authentication里面的credentials相比較 ; todo 加密 token 中的密碼
        if (!password.equals(token.getCredentials())) {
            throw new BadCredentialsException("Invalid username/password");
        }
        //授權
        return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //返回true后才會執(zhí)行上面的authenticate方法,這步能確保authentication能正確轉換類型
        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }
}

本文地址:
SpringBoot+Security+JWT進階:一、自定義認證

推薦

SpringBoot+Security+JWT基礎
SpringBoot+Security+JWT進階:一沿猜、自定義認證
SpringBoot+Security+JWT進階:二枚荣、自定義認證實踐

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市啼肩,隨后出現(xiàn)的幾起案子橄妆,更是在濱河造成了極大的恐慌,老刑警劉巖祈坠,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件害碾,死亡現(xiàn)場離奇詭異,居然都是意外死亡赦拘,警方通過查閱死者的電腦和手機慌随,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人阁猜,你說我怎么就攤上這事丸逸。” “怎么了剃袍?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵黄刚,是天一觀的道長。 經常有香客問我民效,道長憔维,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任研铆,我火速辦了婚禮埋同,結果婚禮上,老公的妹妹穿的比我還像新娘棵红。我一直安慰自己凶赁,他們只是感情好,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布逆甜。 她就那樣靜靜地躺著虱肄,像睡著了一般。 火紅的嫁衣襯著肌膚如雪交煞。 梳的紋絲不亂的頭發(fā)上咏窿,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音素征,去河邊找鬼集嵌。 笑死,一個胖子當著我的面吹牛御毅,可吹牛的內容都是我干的根欧。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼端蛆,長吁一口氣:“原來是場噩夢啊……” “哼凤粗!你這毒婦竟也來了?” 一聲冷哼從身側響起今豆,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤嫌拣,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后呆躲,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體异逐,經...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年插掂,在試婚紗的時候發(fā)現(xiàn)自己被綠了应役。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖箩祥,靈堂內的尸體忽然破棺而出院崇,到底是詐尸還是另有隱情,我是刑警寧澤袍祖,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布底瓣,位于F島的核電站,受9級特大地震影響蕉陋,放射性物質發(fā)生泄漏捐凭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一凳鬓、第九天 我趴在偏房一處隱蔽的房頂上張望茁肠。 院中可真熱鬧,春花似錦缩举、人聲如沸垦梆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽托猩。三九已至,卻和暖如春辽慕,著一層夾襖步出監(jiān)牢的瞬間京腥,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工溅蛉, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留公浪,地道東北人。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓船侧,卻偏偏與公主長得像欠气,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子勺爱,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355