Pig4Cloud之登陸驗(yàn)證(二)發(fā)放token

上一篇介紹了客戶端認(rèn)證處理,那是令牌頒發(fā)的前提。這篇開始,我們就來研究下令牌頒發(fā)。

令牌頒發(fā)

授權(quán)服務(wù)器提供令牌頒發(fā)接口(/oauth2/token),由客戶端發(fā)起請(qǐng)求,授權(quán)服務(wù)器生成訪問令牌(access_token)返回,客戶端使用此令牌才能去調(diào)用資源服務(wù)器的接口。

Spring Authorization Server 目前支持如下三種令牌頒發(fā)策略:Authorization CodeClient Credentials、Refresh Token,分別對(duì)應(yīng) 授權(quán)碼模式、客戶端憑證模式、刷新令牌模式。

Authorization Code(授權(quán)碼模式)

客戶端訪問授權(quán)鏈接,用戶授權(quán),客戶端獲得授權(quán)碼code,通過code獲取令牌

  • 傳參

    • grant_type:固定值 authorization_code
    • code:授權(quán)碼
  • 核心類

    • OAuth2AuthorizationCodeAuthenticationConverter
    • OAuth2AuthorizationCodeAuthenticationProvider

Client Credentials(客戶端憑證模式)

  • 傳參
    • grant_type:固定值 client_credentials
  • 核心類
    • OAuth2ClientCredentialsAuthenticationConverter
    • OAuth2ClientCredentialsAuthenticationProvider

Refresh Token(刷新令牌模式)

當(dāng)客戶端支持刷新令牌時(shí),授權(quán)服務(wù)器頒發(fā)訪問令牌(access_token)時(shí)會(huì)同時(shí)頒發(fā)刷新令牌(refresh_token),客戶端可以使用刷新令牌重新獲取訪問令牌。(由于訪問令牌時(shí)效比較短,刷新令牌時(shí)效比較長(zhǎng),通過刷新令牌獲取訪問令牌,避免多次授權(quán))

  • 傳參
    • grant_type:固定值 refresh_token
    • refresh_token:刷新令牌
  • 核心類
    • OAuth2RefreshTokenAuthenticationConverter
    • OAuth2RefreshTokenAuthenticationProvider

OAuth2TokenEndpointFilter

實(shí)現(xiàn)令牌頒發(fā)功能的攔截器就是 OAuth2TokenEndpointFilter。OAuth2TokenEndpointFilter 會(huì)接收通過上文 OAuth2ClientAuthenticationFilter 客戶端認(rèn)證的請(qǐng)求,其核心代碼如下:

@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //step1
        if (!this.tokenEndpointMatcher.matches(request)) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            String[] grantTypes = request.getParameterValues(OAuth2ParameterNames.GRANT_TYPE);
            if (grantTypes == null || grantTypes.length != 1) {
                throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.GRANT_TYPE);
            }
        //step2
            Authentication authorizationGrantAuthentication = this.authenticationConverter.convert(request);
            if (authorizationGrantAuthentication == null) {
                throwError(OAuth2ErrorCodes.UNSUPPORTED_GRANT_TYPE, OAuth2ParameterNames.GRANT_TYPE);
            }
            if (authorizationGrantAuthentication instanceof AbstractAuthenticationToken) {
                ((AbstractAuthenticationToken) authorizationGrantAuthentication)
                        .setDetails(this.authenticationDetailsSource.buildDetails(request));
            }
        //step3
            OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
                    (OAuth2AccessTokenAuthenticationToken) this.authenticationManager.authenticate(authorizationGrantAuthentication);
        //step4
            this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, accessTokenAuthentication);
        } catch (OAuth2AuthenticationException ex) {
            SecurityContextHolder.clearContext();
            this.authenticationFailureHandler.onAuthenticationFailure(request, response, ex);
        }
    }

step1.判斷此次請(qǐng)求是否是 “令牌頒發(fā)” 請(qǐng)求,若是,則繼續(xù)授權(quán)模式檢驗(yàn),否則跳過
step2.解析請(qǐng)求中的參數(shù),構(gòu)建成一個(gè) Authentication(組裝登陸認(rèn)證對(duì)象)
step3.認(rèn)證管理器對(duì) Authentication 進(jìn)行認(rèn)證
step4.到這一步說明access_token生成好了, 將access_token和相關(guān)信息響應(yīng)給請(qǐng)求方。

客戶端認(rèn)證 OAuth2ClientAuthenticationFilter 中也正是用的這種實(shí)現(xiàn)套路。將不同實(shí)現(xiàn)策略抽象為 AuthenticationConverterAuthenticationProvider 接口。每種策略實(shí)際上就是一個(gè) AuthenticationConverter 實(shí)現(xiàn)類 加上一個(gè) AuthenticationProvider實(shí)現(xiàn)類。

組裝認(rèn)證對(duì)象

Authentication authorizationGrantAuthentication = this.authenticationConverter.convert(request);

AuthenticationConverter 會(huì)根據(jù)請(qǐng)求中的參數(shù)和授權(quán)類型組裝成對(duì)應(yīng)的授權(quán)認(rèn)證對(duì)象。

image

授權(quán)認(rèn)證調(diào)用

OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
                    (OAuth2AccessTokenAuthenticationToken) this.authenticationManager.authenticate(authorizationGrantAuthentication);

image

OAuth2ResourceOwnerBaseAuthenticationProvider
image

認(rèn)證邏輯

    Authentication usernamePasswordAuthentication = authenticationManager
                    .authenticate(usernamePasswordAuthenticationToken);

根據(jù)認(rèn)證方法傳入的參數(shù)判定進(jìn)入到AbstractUserDetailsAuthenticationProvider

@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
                () -> this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                        "Only UsernamePasswordAuthenticationToken is supported"));
        String username = determineUsername(authentication);
        boolean cacheWasUsed = true;
        UserDetails user = this.userCache.getUserFromCache(username);
        if (user == null) {
            cacheWasUsed = false;
            try {
                user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
            }
            catch (UsernameNotFoundException ex) {
                this.logger.debug("Failed to find user '" + username + "'");
                if (!this.hideUserNotFoundExceptions) {
                    throw ex;
                }
                throw new BadCredentialsException(this.messages
                        .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
            Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
        }
        try {
            this.preAuthenticationChecks.check(user);
            additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
        }
        catch (AuthenticationException ex) {
            if (!cacheWasUsed) {
                throw ex;
            }
            // 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);
            this.preAuthenticationChecks.check(user);
            additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
        }
        this.postAuthenticationChecks.check(user);
        if (!cacheWasUsed) {
            this.userCache.putUserInCache(user);
        }
        Object principalToReturn = user;
        if (this.forcePrincipalAsString) {
            principalToReturn = user.getUsername();
        }
        return createSuccessAuthentication(principalToReturn, authentication, user);
    }

查詢用戶信息


image

retrieveUser方法

protected abstract UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException;

PigDaoAuthenticationProvider繼承了AbstractUserDetailsAuthenticationProvider并重寫
retrieveUser方法。返回值為UserDetails。

image

用戶密碼校驗(yàn)

image

PigDaoAuthenticationProvider繼承了AbstractUserDetailsAuthenticationProvider并重寫
additionalAuthenticationChecks方法。

@Override
    @SuppressWarnings("deprecation")
    protected void additionalAuthenticationChecks(UserDetails userDetails,
            UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

        // app 模式不用校驗(yàn)密碼
        String grantType = WebUtils.getRequest().get().getParameter(OAuth2ParameterNames.GRANT_TYPE);
        if (StrUtil.equals(SecurityConstants.APP, grantType)) {
            return;
        }

        if (authentication.getCredentials() == null) {
            this.logger.debug("Failed to authenticate since no credentials provided");
            throw new BadCredentialsException(this.messages
                    .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
        String presentedPassword = authentication.getCredentials().toString();
        if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
            this.logger.debug("Failed to authenticate since password does not match stored value");
            throw new BadCredentialsException(this.messages
                    .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

構(gòu)建token

認(rèn)證成功后返回OAuth2ResourceOwnerBaseAuthenticationProvider接著看

image

CustomeOAuth2AccessTokenGenerator實(shí)現(xiàn)OAuth2TokenGenerator接口.

Token 存儲(chǔ)持久化

image
image

RedisOAuth2AuthorizationService實(shí)現(xiàn)OAuth2AuthorizationService
save方法

@Override
    public void save(OAuth2Authorization authorization) {
        Assert.notNull(authorization, "authorization cannot be null");

        if (isState(authorization)) {
            String token = authorization.getAttribute("state");
            redisTemplate.setValueSerializer(RedisSerializer.java());
            redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.STATE, token), authorization, TIMEOUT,
                    TimeUnit.MINUTES);
        }

        if (isCode(authorization)) {
            OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
                    .getToken(OAuth2AuthorizationCode.class);
            OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
            long between = ChronoUnit.MINUTES.between(authorizationCodeToken.getIssuedAt(),
                    authorizationCodeToken.getExpiresAt());
            redisTemplate.setValueSerializer(RedisSerializer.java());
            redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()),
                    authorization, between, TimeUnit.MINUTES);
        }

        if (isRefreshToken(authorization)) {
            OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
            long between = ChronoUnit.SECONDS.between(refreshToken.getIssuedAt(), refreshToken.getExpiresAt());
            redisTemplate.setValueSerializer(RedisSerializer.java());
            redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()),
                    authorization, between, TimeUnit.SECONDS);
        }

        if (isAccessToken(authorization)) {
            OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
            long between = ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt());
            redisTemplate.setValueSerializer(RedisSerializer.java());
            redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()),
                    authorization, between, TimeUnit.SECONDS);
        }
    }

onAuthenticationSuccess

image

PigAuthenticationSuccessEventHandler實(shí)現(xiàn)AuthenticationSuccessHandler

@SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) {
        OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication;
        Map<String, Object> map = accessTokenAuthentication.getAdditionalParameters();
        if (MapUtil.isNotEmpty(map)) {
            // 發(fā)送異步日志事件
            PigUser userInfo = (PigUser) map.get(SecurityConstants.DETAILS_USER);
            log.info("用戶:{} 登錄成功", userInfo.getName());
            SecurityContextHolder.getContext().setAuthentication(accessTokenAuthentication);
            SysLog logVo = SysLogUtils.getSysLog();
            logVo.setTitle("登錄成功");
            String startTimeStr = request.getHeader(CommonConstants.REQUEST_START_TIME);
            if (StrUtil.isNotBlank(startTimeStr)) {
                Long startTime = Long.parseLong(startTimeStr);
                Long endTime = System.currentTimeMillis();
                logVo.setTime(endTime - startTime);
            }
            logVo.setCreateBy(userInfo.getName());
            logVo.setUpdateBy(userInfo.getName());
            SpringContextHolder.publishEvent(new SysLogEvent(logVo));
        }

        // 輸出token
        sendAccessTokenResponse(request, response, authentication);
    }

輸出token

private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException {

        OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication;

        OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
        OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
        Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();

        OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
                .tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes());
        if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
            builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
        }
        if (refreshToken != null) {
            builder.refreshToken(refreshToken.getTokenValue());
        }
        if (!CollectionUtils.isEmpty(additionalParameters)) {
            builder.additionalParameters(additionalParameters);
        }
        OAuth2AccessTokenResponse accessTokenResponse = builder.build();
        ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);

        // 無狀態(tài) 注意刪除 context 上下文的信息
        SecurityContextHolder.clearContext();
        this.accessTokenHttpResponseConverter.write(accessTokenResponse, null, httpResponse);
    }

CSDN
騰訊云
掘金
博客園

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容