亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

OAuth2生成token代碼備忘實現(xiàn)過程示例

 更新時間:2023年08月15日 10:51:51   作者:AC編程  
這篇文章主要為大家介紹了OAuth2生成token代碼備忘實現(xiàn)過程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

一、登錄接口(用戶名+密碼)

1、前端請求auth服務(wù)

http://127.0.0.1:72/oauth/pwdLogin

2、請求數(shù)據(jù)

{
    "mobile": "134178101xx",
    "password": "123456"
}

3、Controller方法

    @SneakyThrows
    @PostMapping("pwdLogin")
    @SignMemberLoginLog(value = "APP_PWD", desc = "密碼登錄")
    @ApiOperation(value = "會員登錄(密碼登錄)")
    public Result<Oauth2TokenDto> pwdLogin(@RequestBody MemberLoginPwdVO vo, HttpServletRequest request) {
        if (StringUtil.isEmpty(vo.getClientId())) {
            vo.setClientId("app");
        }
        vo.setIp(IpUtils.ip(request));
        Map<String, String> params = getMemberBaseParam(vo, SecurityLoginTypeEnum.APP_PWD.getCode());
        params.put("mobile", vo.getMobile());
        params.put("password", vo.getPassword());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        Oauth2TokenDto oauth2TokenDto = authTokenComponent.getAccessToken(vo.getClientId(), "app", grantedAuthorities, params);
        return Result.success(oauth2TokenDto);
    }
    private Map<String, String> getMemberBaseParam(MemberLoginBaseVO vo, String grantType) {
       Map<String, String> params = new HashMap<>();
       params.put("client_id", vo.getClientId());
       params.put("client_secret", "app");
       params.put("grant_type", grantType);
       params.put("scope", "all");
       params.put("platform", vo.getPlatform());
       //附加信息
       params.put("version", vo.getVersion());
       params.put("device", vo.getDevice());
       params.put("iemi", vo.getIemi());
       params.put("location", vo.getLocation());
       params.put("ip", vo.getIp());
       params.put("recommendCode", vo.getRecommendCode());
       return params;
   }

二、授權(quán)接口調(diào)用邏輯

2.1 AuthTokenComponent類

import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
@Component
public class AuthTokenComponent {
    @Autowired
    private TokenEndpoint tokenEndpoint;
    public Oauth2TokenDto getAccessToken(String clientId, String clientSecurity , List<GrantedAuthority> grantedAuthorities, Map<String, String> params) throws HttpRequestMethodNotSupportedException {
        User principle = new User(clientId,clientSecurity,true,true,true,true,grantedAuthorities);
       return getAccessToken(principle,params);
    }
    public Oauth2TokenDto getAccessToken(User principle, Map<String, String> params) throws HttpRequestMethodNotSupportedException {
        UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken(principle,null,principle.getAuthorities());
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, params).getBody();
        Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead("Bearer ").build();
        return oauth2TokenDto;
    }
}

調(diào)用tokenEndpoint.postAccessToken生成token時,接口調(diào)用邏輯:

  • 1、調(diào)用AuthenticationProvider接口(AdminAuthenticationProvider實現(xiàn)類)密碼校驗
  • 2、調(diào)用UserDetailsService接口(MyUserDetailsService實現(xiàn)類)獲取用戶信息
  • 3、調(diào)用DefaultTokenServices接口(CustomTokenServices實現(xiàn)類)生成token

2.2 AuthenticationProvider接口

1、MobilePasswordAuthenticationProvider實現(xiàn)類

@Setter
public class MobilePasswordAuthenticationProvider implements AuthenticationProvider {
    private QmUserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) {
        MobilePasswordAuthenticationToken authenticationToken = (MobilePasswordAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String password = (String) authenticationToken.getCredentials();
        SecurityUser user = userDetailsService.loadUserByMobile(mobile);
        if (user == null) {
            throw new QiMiaoException(ResultCode.JWT_USER_INVALID);
        }
        if(userDetailsService.checkBlock(mobile)) {
            throw new QiMiaoException(ResultCode.JWT_USER_BLOCK);
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            userDetailsService.inc(mobile);
            throw new QiMiaoException(ResultCode.JWT_USER_INVALID_PWD);
        }
        Map<String, String> parameters = (Map<String, String>)authenticationToken.getDetails();
        if(null != parameters.get("platform")) {
            user.setPlatform(parameters.get("platform"));
        }
        MobilePasswordAuthenticationToken authenticationResult = new MobilePasswordAuthenticationToken(user, password, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }
    @Override
    public boolean supports(Class<?> authentication) {
        return MobilePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

2、MobileAuthenticationSecurityConfig配置類

@Component
public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    private QmUserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SmsVcodeRdsHelper smsVcodeRdsHelper;
    @Override
    public void configure(HttpSecurity http) {
        MobilePasswordAuthenticationProvider provider = new MobilePasswordAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        http.authenticationProvider(provider);
        MobileSmsAuthenticationProvider smsProvider = new MobileSmsAuthenticationProvider();
        smsProvider.setUserDetailsService(userDetailsService);
        smsProvider.setSmsVcodeRdsHelper(smsVcodeRdsHelper);
        http.authenticationProvider(smsProvider);
        MobileOneKeyAuthenticationProvider oneKeyProvider = new MobileOneKeyAuthenticationProvider();
        oneKeyProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(oneKeyProvider);
        VisitorAuthenticationProvider visitorAuthenticationProvider = new VisitorAuthenticationProvider();
        visitorAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(visitorAuthenticationProvider);
        QRCodeAuthenticationProvider qrCodeAuthenticationProvider = new QRCodeAuthenticationProvider();
        qrCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(qrCodeAuthenticationProvider);
        SocialAuthenticationProvider socialAuthenticationProvider = new SocialAuthenticationProvider();
        socialAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(socialAuthenticationProvider);
    }
}

3、WebSecurityConfig配置類

@Configuration
@EnableWebSecurity
@Import(DefaultPasswordConfig.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  //管理系統(tǒng)登錄
  @Autowired
  private AdminAuthenticationSecurityConfig adminAuthenticationSecurityConfig;
  //App登錄
  @Autowired
  private MobileAuthenticationSecurityConfig mobileAuthenticationSecurityConfig;
  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
                .antMatchers("/rsa/publicKey", "/actuator/**").permitAll()
                .antMatchers("/").permitAll()
                .antMatchers(HttpMethod.POST, "/oauth/**").permitAll()
                // swagger
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/configuration/ui").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest()
                //授權(quán)服務(wù)器關(guān)閉basic認(rèn)證
                .permitAll()
                .and()
                .logout()
                .logoutUrl(SecurityConstants.LOGOUT_URL)
                .logoutSuccessHandler(oauthLogoutSuccessHandler)
                .addLogoutHandler(oauthLogoutHandler)
                .clearAuthentication(true)
                .and()
                .apply(mobileAuthenticationSecurityConfig)
                .and()
                .apply(adminAuthenticationSecurityConfig)
                .and()
                .csrf().disable()
                // 解決不允許顯示在iframe的問題
                .headers().frameOptions().disable().cacheControl();
        // 基于密碼 等模式可以無session,不支持授權(quán)碼模式
        if (authenticationEntryPoint != null) {
            http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        } else {
            // 授權(quán)碼模式單獨處理,需要session的支持,此模式可以支持所有oauth2的認(rèn)證
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        }
    }
}

2.3 MyUserDetailsService接口 & MyUserDetailServiceImpl類

public interface MyUserDetailsService extends UserDetailsService {
    SecurityUser loadUserByMobile(String mobile);
    SecurityUser loadUserById(Long id);
    SecurityUser loadUserByOpenId(String openId, String platform);
    SecurityUser loadUserByImei(String im);
    SecurityUser loadAdminUser(String mobileOrUserName);
    SecurityUser createUserByMobile(String mobile);
    SecurityUser createUserByMobile(String globalCode, String mobile);
    SecurityUser createVisitor(Map<String, String> map);
}
@Slf4j
public class MyUserDetailServiceImpl implements MyUserDetailsService{
  @Override
    public SecurityUser loadAdminUser(String mobileOrUserName) {
        SecurityUser securityUser = null;
        Result<UserDTO> userDTOResult = userFeignService.selectByMobile(mobileOrUserName);
        if (ResultCode.SUCCESS.getCode() == userDTOResult.getCode()) {
            if (userDTOResult.getData() == null) {
                throw new Exception(ResultCode.JWT_USER_INVALID);
            }
            UserDTO userDTO = userDTOResult.getData();
            //是否被禁用
            if (!userDTO.getStatus()) {
                throw new Exception(ResultCode.JWT_USER_ENABLED);
            }
            securityUser = new SecurityUser();
            securityUser.setUserType(SecurityUserTypeEnum.ADMIN);
            securityUser.setGrantType(SecurityLoginTypeEnum.ADMIN_PWD);
            securityUser.setId(userDTO.getId());
            securityUser.setUsername(userDTO.getLoginName());
            securityUser.setPassword(userDTO.getLoginPwd());
            securityUser.setEnabled(true);
            Collection<SimpleGrantedAuthority> authorities = new HashSet<>();
            //基于權(quán)限控制
            Result<List<PermDTO>> dtoResult = permFeignService.permListByUserId(userDTO.getId());
            if (ResultCode.SUCCESS.getCode() == dtoResult.getCode()) {
                if (dtoResult.getData() != null) {
                    for (PermDTO dto : dtoResult.getData()) {
                        authorities.add(new SimpleGrantedAuthority(dto.getPermApiHttpMethod() + dto.getPermValue()));
                    }
                }
            }
            securityUser.setAuthorities(authorities);
        }
        return securityUser;
    }
}

2.4 CustomTokenServices類

@Slf4j
public class CustomTokenServices extends DefaultTokenServices {
        private TokenStore tokenStore;
        private TokenEnhancer accessTokenEnhancer;
        //是否登錄同應(yīng)用同賬號互踢
        private boolean isSingleLogin;
        public CustomTokenServices(boolean isSingleLogin) {
            this.isSingleLogin = isSingleLogin;
        }
        @Override
        @Transactional
        public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
            OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);
            log.info("createAccessToken,start existingAccessToken={}",existingAccessToken);
            OAuth2RefreshToken refreshToken = null;
            if (existingAccessToken != null) {
                if (isSingleLogin) {
                    if (existingAccessToken.getRefreshToken() != null) {
                        tokenStore.removeRefreshToken(existingAccessToken.getRefreshToken());
                        log.info("createAccessToken,removeRefreshToken A={}",existingAccessToken);
                        log.info("createAccessToken,getRefreshToken A1={}",existingAccessToken.getRefreshToken());
                    }
                } else if (existingAccessToken.isExpired()) {
                    if (existingAccessToken.getRefreshToken() != null) {
                        refreshToken = existingAccessToken.getRefreshToken();
                        tokenStore.removeRefreshToken(refreshToken);
                    }
                    tokenStore.removeAccessToken(existingAccessToken);
                    log.info("createAccessToken,isExpired B={}",existingAccessToken);
                } else {
                    // oidc每次授權(quán)都刷新id_token
                    existingAccessToken = refreshIdToken(existingAccessToken, authentication);
                    tokenStore.storeAccessToken(existingAccessToken, authentication);
                    log.info("createAccessToken,isExpired C={}",existingAccessToken);
                    return existingAccessToken;
                }
            }
            if (refreshToken == null) {
                refreshToken = createRefreshToken(authentication);
            }
            else if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
                ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken;
                if (System.currentTimeMillis() > expiring.getExpiration().getTime()) {
                    refreshToken = createRefreshToken(authentication);
                }
            }
            OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
            tokenStore.storeAccessToken(accessToken, authentication);
            refreshToken = accessToken.getRefreshToken();
            if (refreshToken != null) {
                tokenStore.storeRefreshToken(refreshToken, authentication);
            }
            log.info("createAccessToken,end accessToken={}",accessToken);
            return accessToken;
        }
}

三、AuthenticationProvider詳解

3.1 AuthenticationProvider多個實現(xiàn)類

如果項目中定義了多個AuthenticationProvider實現(xiàn)類,那登錄時,怎么判斷用哪個AuthenticationProvider實現(xiàn)類?我們可以通過源碼來找到答案

1、MobileAuthenticationSecurityConfig

@Component
public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    private MyUserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SmsVcodeRdsHelper smsVcodeRdsHelper;
    @Override
    public void configure(HttpSecurity http) {
        MobilePasswordAuthenticationProvider provider = new MobilePasswordAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        http.authenticationProvider(provider);
        MobileSmsAuthenticationProvider smsProvider = new MobileSmsAuthenticationProvider();
        smsProvider.setUserDetailsService(userDetailsService);
        smsProvider.setSmsVcodeRdsHelper(smsVcodeRdsHelper);
        http.authenticationProvider(smsProvider);
        MobileOneKeyAuthenticationProvider oneKeyProvider = new MobileOneKeyAuthenticationProvider();
        oneKeyProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(oneKeyProvider);
        VisitorAuthenticationProvider visitorAuthenticationProvider = new VisitorAuthenticationProvider();
        visitorAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(visitorAuthenticationProvider);
        QRCodeAuthenticationProvider qrCodeAuthenticationProvider = new QRCodeAuthenticationProvider();
        qrCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(qrCodeAuthenticationProvider);
        SocialAuthenticationProvider socialAuthenticationProvider = new SocialAuthenticationProvider();
        socialAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(socialAuthenticationProvider);
    }
}

2、管理系統(tǒng)登錄實現(xiàn)類

@Setter
public class AdminAuthenticationProvider implements AuthenticationProvider {
    private QmUserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
        String userName = (String) authenticationToken.getPrincipal();
        String password = (String) authenticationToken.getCredentials();
        UserDetails user = userDetailsService.loadAdminUser(userName);
        if (user == null) {
            throw new Exception(ResultCode.JWT_USER_INVALID);
        }
        if(userDetailsService.checkBlock(userName)) {
            throw new Exception(ResultCode.JWT_USER_BLOCK);
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            userDetailsService.inc(userName);
            throw new Exception(ResultCode.JWT_USER_INVALID);
        }
        UsernamePasswordAuthenticationToken authenticationResult = new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }
    // 重點看這里
    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

3、手機(jī)號+密碼登錄實現(xiàn)類

@Setter
public class MobilePasswordAuthenticationProvider implements AuthenticationProvider {
    private QmUserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) {
        MobilePasswordAuthenticationToken authenticationToken = (MobilePasswordAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String password = (String) authenticationToken.getCredentials();
        SecurityUser user = userDetailsService.loadUserByMobile(mobile);
        if (user == null) {
            throw new QiMiaoException(ResultCode.JWT_USER_INVALID);
        }
        if(userDetailsService.checkBlock(mobile)) {
            throw new QiMiaoException(ResultCode.JWT_USER_BLOCK);
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            userDetailsService.inc(mobile);
            throw new QiMiaoException(ResultCode.JWT_USER_INVALID_PWD);
        }
        Map<String, String> parameters = (Map<String, String>)authenticationToken.getDetails();
        if(null != parameters.get("platform")) {
            user.setPlatform(parameters.get("platform"));
        }
        MobilePasswordAuthenticationToken authenticationResult = new MobilePasswordAuthenticationToken(user, password, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }
  // 重點看這里
    @Override
    public boolean supports(Class<?> authentication) {
        return MobilePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

4、MobilePasswordAuthenticationToken

package com.alanchen.ac;
public class MobilePasswordAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    private final Object principal;
    private Object credentials;
    public MobilePasswordAuthenticationToken(String mobile, String password) {
        super(null);
        this.principal = mobile;
        this.credentials = password;
        setAuthenticated(false);
    }
    public MobilePasswordAuthenticationToken(Object principal, Object credentials,
                                             Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true);
    }
    @Override
    public Object getCredentials() {
        return this.credentials;
    }
    @Override
    public Object getPrincipal() {
        return this.principal;
    }
    @Override
    public void setAuthenticated(boolean isAuthenticated) {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }
    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
}

3.2 AuthenticationProvider源碼

首先進(jìn)入到AuthenticationProvider源碼中可以看到它只是個簡單的接口里面也只有兩個方法:

public interface AuthenticationProvider {
    // 具體認(rèn)證流程
    Authentication authenticate(Authentication authentication)
            throws AuthenticationException;    
    // supports函數(shù)用來指明該Provider是否適用于該類型的認(rèn)證,如果不合適,則尋找另一個Provider進(jìn)行驗證處理。    
    boolean supports(Class<?> authentication);
}

3.3 ProviderManager源碼

ProviderManager提供了一個list對AuthenticationProvider進(jìn)行統(tǒng)一管理,即一個認(rèn)證處理器鏈來支持同一個應(yīng)用中的多個不同身份認(rèn)證機(jī)制,ProviderManager將會根據(jù)順序來進(jìn)行驗證。

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Class<? extends Authentication> toTest = authentication.getClass();
        AuthenticationException lastException = null;
        AuthenticationException parentException = null;
        Authentication result = null;
        Authentication parentResult = null;
        boolean debug = logger.isDebugEnabled();
        Iterator var8 = this.getProviders().iterator();
        while(var8.hasNext()) {
            AuthenticationProvider provider = (AuthenticationProvider)var8.next();
            //這里調(diào)用的就是AuthenticationProvider的方法supports(),如果項目中定義了多個AuthenticationProvider,則是通過這里判斷來取哪一個AuthenticationProvider實現(xiàn)類
            if (provider.supports(toTest)) {
                if (debug) {
                    logger.debug("Authentication attempt using " + provider.getClass().getName());
                }
                try {
                    result = provider.authenticate(authentication);
                    if (result != null) {
                        this.copyDetails(authentication, result);
                        break;
                    }
                } catch (InternalAuthenticationServiceException | AccountStatusException var13) {
                    this.prepareException(var13, authentication);
                    throw var13;
                } catch (AuthenticationException var14) {
                    lastException = var14;
                }
            }
        }
         //省略代碼
}

3.4 手機(jī)號+密碼Granter

重點關(guān)注該類中的:

1、MobilePasswordAuthenticationToken

2、SecurityGrantType.APP_PWD.getCode(),和Controller.pwdLogin里的grant_type是同一個類型。

public class MobilePwdGranter extends AbstractTokenGranter {

    private final AuthenticationManager authenticationManager;

    public MobilePwdGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
            , ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, SecurityGrantType.APP_PWD.getCode());
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map&lt;String, String&gt; parameters = new LinkedHashMap&lt;&gt;(tokenRequest.getRequestParameters());
        String mobile = parameters.get("mobile");
        String password = parameters.get("password");
        // Protect from downstream leaks of password
        parameters.remove("password");

        Authentication userAuth = new MobilePasswordAuthenticationToken(mobile, password);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        userAuth = authenticationManager.authenticate(userAuth);
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate mobile: " + mobile);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}

3.5 TokenGranter配置

@Configuration
public class TokenGranterConfig {
    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenStore tokenStore;
    @Autowired(required = false)
    private List<TokenEnhancer> tokenEnhancer;
    @Autowired
    private RandomValueAuthorizationCodeServices authorizationCodeServices;
    private boolean reuseRefreshToken = true;
    private AuthorizationServerTokenServices tokenServices;
    private TokenGranter tokenGranter;
    /**
     * 授權(quán)模式
     */
    @Bean
    public TokenGranter tokenGranter() {
        if (tokenGranter == null) {
            tokenGranter = new TokenGranter() {
                private CompositeTokenGranter delegate;
                @Override
                public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
                    if (delegate == null) {
                        delegate = new CompositeTokenGranter(getAllTokenGranters());
                    }
                    return delegate.grant(grantType, tokenRequest);
                }
            };
        }
        return tokenGranter;
    }
    /**
     * 所有授權(quán)模式:默認(rèn)的5種模式 + 自定義的模式
     */
    private List<TokenGranter> getAllTokenGranters() {
        AuthorizationServerTokenServices tokenServices = tokenServices();
        AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();
        OAuth2RequestFactory requestFactory = requestFactory();
        //獲取默認(rèn)的授權(quán)模式
        List<TokenGranter> tokenGranters = getDefaultTokenGranters(tokenServices, authorizationCodeServices, requestFactory);
        if (authenticationManager != null) {
            // 添加social模式
            tokenGranters.add(new SocialGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
            // 添加手機(jī)號加密碼授權(quán)模式
            tokenGranters.add(new MobilePwdGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
            // 添加手機(jī)號加密碼授權(quán)模式
            tokenGranters.add(new MobileSmsGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
            tokenGranters.add(new AdminPwdGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
            tokenGranters.add(new MobileOneKeyGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
            tokenGranters.add(new VisitorGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
            tokenGranters.add(new QRCodeGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
        }
        return tokenGranters;
    }
    /**
     * 默認(rèn)的授權(quán)模式
     */
    private List<TokenGranter> getDefaultTokenGranters(AuthorizationServerTokenServices tokenServices
            , AuthorizationCodeServices authorizationCodeServices, OAuth2RequestFactory requestFactory) {
        List<TokenGranter> tokenGranters = new ArrayList<>();
        // 添加授權(quán)碼模式
        tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, requestFactory));
        // 添加刷新令牌的模式
        tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetailsService, requestFactory));
        // 添加隱士授權(quán)模式
        tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetailsService, requestFactory));
        // 添加客戶端模式
        tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, requestFactory));
        if (authenticationManager != null) {
            // 添加密碼模式
            tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
        }
        return tokenGranters;
    }
    private AuthorizationServerTokenServices tokenServices() {
        if (tokenServices != null) {
            return tokenServices;
        }
        this.tokenServices = createDefaultTokenServices();
        return tokenServices;
    }
    private AuthorizationCodeServices authorizationCodeServices() {
        if (authorizationCodeServices == null) {
            authorizationCodeServices = new InMemoryAuthorizationCodeServices();
        }
        return authorizationCodeServices;
    }
    private OAuth2RequestFactory requestFactory() {
        return new DefaultOAuth2RequestFactory(clientDetailsService);
    }
    private DefaultTokenServices createDefaultTokenServices() {
        //token互踢
        DefaultTokenServices tokenServices = new CustomTokenServices(true);
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setReuseRefreshToken(reuseRefreshToken);
        tokenServices.setClientDetailsService(clientDetailsService);
        tokenServices.setTokenEnhancer(tokenEnhancer());
        addUserDetailsService(tokenServices, this.userDetailsService);
        return tokenServices;
    }
    private TokenEnhancer tokenEnhancer() {
        if (tokenEnhancer != null) {
            TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
            tokenEnhancerChain.setTokenEnhancers(tokenEnhancer);
            return tokenEnhancerChain;
        }
        return null;
    }
    private void addUserDetailsService(DefaultTokenServices tokenServices, UserDetailsService userDetailsService) {
        if (userDetailsService != null) {
            PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
            provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(userDetailsService));
            tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));
        }
    }
}

四、生成toekn詳解

生成token前,先從tokenStore里去toeken,看是否已經(jīng)存在,如果存在則執(zhí)行擠下線邏輯。tokenStore對應(yīng)的是實現(xiàn)類com.auth.store.CustomRedisTokenStore。

4.1 TokenStore配置類

@Configuration
public class AuthRedisTokenStore {
    @Bean
    public TokenStore tokenStore(RedisConnectionFactory connectionFactory, RedisSerializer<Object> redisValueSerializer) {
        return new CustomRedisTokenStore(connectionFactory, redisValueSerializer);
    }
}

4.2 TokenStore實現(xiàn)類

/**
 * 優(yōu)化自Spring Security的RedisTokenStore
 * 1. 支持redis所有集群模式包括cluster模式
 * 2. 使用pipeline減少連接次數(shù),提升性能
 * 3. 自動續(xù)簽token
 */
@Slf4j
public class CustomRedisTokenStore implements TokenStore {
    private static final String ACCESS = "{auth}access:";
    private static final String AUTH_TO_ACCESS = "{auth}auth_to_access:";
    private static final String REFRESH_AUTH = "{auth}refresh_auth:";
    private static final String ACCESS_TO_REFRESH = "{auth}access_to_refresh:";
    private static final String REFRESH = "{auth}refresh:";
    private static final String REFRESH_TO_ACCESS = "{auth}refresh_to_access:";
    private static final String RELATION_ID_TOKEN = "{auth}relation_id_token:";
    private static final boolean springDataRedis_2_0 = ClassUtils.isPresent(
            "org.springframework.data.redis.connection.RedisStandaloneConfiguration",
            RedisTokenStore.class.getClassLoader());
    private final RedisConnectionFactory connectionFactory;
    private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
    private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();
    private String prefix = "";
    private Method redisConnectionSet_2_0;
    /**
     * 業(yè)務(wù)redis的value序列化
     */
    private RedisSerializer<Object> redisValueSerializer;
    public CustomRedisTokenStore(RedisConnectionFactory connectionFactory,  RedisSerializer<Object> redisValueSerializer) {
        this.connectionFactory = connectionFactory;
        this.redisValueSerializer = redisValueSerializer;
        if (springDataRedis_2_0) {
            this.loadRedisConnectionMethods_2_0();
        }
    }
    public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
        this.authenticationKeyGenerator = authenticationKeyGenerator;
    }
    public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
        this.serializationStrategy = serializationStrategy;
    }
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    private void loadRedisConnectionMethods_2_0() {
        this.redisConnectionSet_2_0 = ReflectionUtils.findMethod(
                RedisConnection.class, "set", byte[].class, byte[].class);
    }
    private RedisConnection getConnection() {
        return connectionFactory.getConnection();
    }
    private byte[] serialize(Object object) {
        return serializationStrategy.serialize(object);
    }
    private byte[] serializeKey(String object) {
        return serialize(prefix + object);
    }
    private OAuth2AccessToken deserializeAccessToken(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class);
    }
    private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
    }
    private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class);
    }
    private ClientDetails deserializeClientDetails(byte[] bytes) {
        return (ClientDetails)redisValueSerializer.deserialize(bytes);
    }
    private byte[] serialize(String string) {
        return serializationStrategy.serialize(string);
    }
    private String deserializeString(byte[] bytes) {
        return serializationStrategy.deserializeString(bytes);
    }
    @Override
    public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
        String key = authenticationKeyGenerator.extractKey(authentication);
        byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key);
        byte[] bytes;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(serializedKey);
        } finally {
            conn.close();
        }
        OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
        if (accessToken != null) {
            OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue());
            if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) {
                // Keep the stores consistent (maybe the same user is
                // represented by this authentication but the details have
                // changed)
                storeAccessToken(accessToken, authentication);
            }
        }
        return accessToken;
    }
    @Override
    public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
        OAuth2Authentication auth2Authentication = readAuthentication(token.getValue());
        //是否開啟token續(xù)簽
        boolean isRenew = true;
        if (isRenew && auth2Authentication != null) {
            OAuth2Request clientAuth = auth2Authentication.getOAuth2Request();
            //判斷當(dāng)前應(yīng)用是否需要自動續(xù)簽
            if (checkRenewClientId(clientAuth.getClientId())) {
                //獲取過期時長
                int validitySeconds = 2592000;
                double expiresRatio = token.getExpiresIn() / (double)validitySeconds;
                //判斷是否需要續(xù)簽,當(dāng)前剩余時間小于過期時長的50%則續(xù)簽
                if (expiresRatio <= 0.5) {
                    //更新AccessToken過期時間
                    DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;
                    oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
                    storeAccessToken(oAuth2AccessToken, auth2Authentication, true);
                }
            }
        }
        return auth2Authentication;
    }
    /**
     * 判斷應(yīng)用自動續(xù)簽是否滿足白名單和黑名單的過濾邏輯 后期看需求是否需要
     * @param clientId 應(yīng)用id
     * @return 是否滿足
     */
    private boolean checkRenewClientId(String clientId) {
        boolean result = true;
        return result;
    }
    public String getToken(String id){
        byte[] relationIdTokenKey = getRelationIdTokenKey(id);
        RedisConnection conn = getConnection();
        try {
            byte[] bytes = conn.get(relationIdTokenKey);
            return deserializeString(bytes);
        } finally {
            conn.close();
        }
    }
    /**
     * 獲取token的總有效時長
     * @param clientId 應(yīng)用id
     */
    private int getAccessTokenValiditySeconds(String clientId) {
        RedisConnection conn = getConnection();
        byte[] bytes;
        try {
            bytes = conn.get(serializeKey(SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId));
        } finally {
            conn.close();
        }
        if (bytes != null) {
            ClientDetails clientDetails = deserializeClientDetails(bytes);
            if (clientDetails.getAccessTokenValiditySeconds() != null) {
                return clientDetails.getAccessTokenValiditySeconds();
            }
        }
        //返回默認(rèn)值
        return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
    }
    @Override
    public OAuth2Authentication readAuthentication(String token) {
        byte[] bytes;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token));
        } finally {
            conn.close();
        }
        return deserializeAuthentication(bytes);
    }
    @Override
    public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
        return readAuthenticationForRefreshToken(token.getValue());
    }
    public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
        RedisConnection conn = getConnection();
        try {
            byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token));
            return deserializeAuthentication(bytes);
        } finally {
            conn.close();
        }
    }
    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        storeAccessToken(token, authentication, false);
    }
    private byte[] getRelationIdTokenKey(String id){
        return serializeKey(RELATION_ID_TOKEN + id);
    }
    private byte[] getRelationIdTokenKey(OAuth2Authentication authentication){
        byte[] relationIdTokenKey = null;
        Object obj = authentication.getPrincipal();
        Object details = authentication.getUserAuthentication().getDetails();
        if(obj!=null && details!=null){
            if(obj instanceof SecurityUser && details instanceof HashMap){
                SecurityUser user = (SecurityUser)obj;
                Map map = (Map)details;
                String clientId = String.valueOf(map.get("client_id"));
                Long userId = user.getId();
                relationIdTokenKey = serializeKey(RELATION_ID_TOKEN +clientId+":"+userId);
            }
        }else{
            log.error("storeAccessToken 沒有取到principal");
        }
        return relationIdTokenKey;
    }
    public SecurityUser getSecurityUser(String token){
        SecurityUser user = null;
        OAuth2Authentication auth2Authentication = readAuthentication(token);
        if (auth2Authentication != null) {
            Object obj = auth2Authentication.getPrincipal();
            if (obj!=null && obj instanceof SecurityUser) {
                user = (SecurityUser) obj;
            }else{
                log.error("getSecurityUser:解析User失敗,"+obj);
            }
        }else{
            log.error("getSecurityUser:auth2Authentication 為nuLl");
        }
        return user;
    }
    /**
     * 存儲token
     * @param isRenew 是否續(xù)簽
     */
    private void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication, boolean isRenew) {
        byte[] serializedAccessToken = serialize(token);
        byte[] serializedAuth = serialize(authentication);
        byte[] serializedToken = serialize(token.getValue());
        byte[] accessKey = serializeKey(ACCESS + token.getValue());
        byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token.getValue());
        byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
        byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
        byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
        byte[] relationIdTokenKey = getRelationIdTokenKey(authentication);
        RedisConnection conn = getConnection();
        try {
            byte[] oldAccessToken = conn.get(accessKey);
            //如果token已存在,并且不是續(xù)簽的話直接返回
            if (!isRenew && oldAccessToken != null) {
                return;
            }
            conn.openPipeline();
            if (springDataRedis_2_0) {
                try {
                    this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
                    this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth);
                    this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken);
                    if(relationIdTokenKey!=null){
                        this.redisConnectionSet_2_0.invoke(conn, relationIdTokenKey, serializedToken);
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                conn.set(accessKey, serializedAccessToken);
                conn.set(authKey, serializedAuth);
                conn.set(authToAccessKey, serializedAccessToken);
                if(relationIdTokenKey!=null){
                    conn.set(relationIdTokenKey, serializedToken);
                }
            }
            //如果是續(xù)簽token,需要先刪除集合里舊的值
            if (oldAccessToken != null) {
                if (!authentication.isClientOnly()) {
                    conn.lRem(approvalKey, 1, oldAccessToken);
                }
                conn.lRem(clientId, 1, oldAccessToken);
            }
            if (!authentication.isClientOnly()) {
                conn.rPush(approvalKey, serializedAccessToken);
            }
            conn.rPush(clientId, serializedAccessToken);
            if (token.getExpiration() != null) {
                int seconds = token.getExpiresIn();
                conn.expire(accessKey, seconds);
                conn.expire(authKey, seconds);
                conn.expire(authToAccessKey, seconds);
                conn.expire(clientId, seconds);
                conn.expire(approvalKey, seconds);
            }
            OAuth2RefreshToken refreshToken = token.getRefreshToken();
            if (refreshToken != null && refreshToken.getValue() != null) {
                byte[] refresh = serialize(token.getRefreshToken().getValue());
                byte[] auth = serialize(token.getValue());
                byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
                byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
                if (springDataRedis_2_0) {
                    try {
                        this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth);
                        this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                } else {
                    conn.set(refreshToAccessKey, auth);
                    conn.set(accessToRefreshKey, refresh);
                }
                expireRefreshToken(refreshToken, conn, refreshToAccessKey, accessToRefreshKey);
            }
            conn.closePipeline();
        } finally {
            conn.close();
        }
    }
    private static String getApprovalKey(OAuth2Authentication authentication) {
        String userName = authentication.getUserAuthentication() == null ? ""
                : authentication.getUserAuthentication().getName();
        return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
    }
    private static String getApprovalKey(String clientId, String userName) {
        return clientId + (userName == null ? "" : ":" + userName);
    }
    @Override
    public void removeAccessToken(OAuth2AccessToken accessToken) {
        removeAccessToken(accessToken.getValue());
    }
    @Override
    public OAuth2AccessToken readAccessToken(String tokenValue) {
        byte[] key = serializeKey(ACCESS + tokenValue);
        byte[] bytes;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(key);
        } finally {
            conn.close();
        }
        return deserializeAccessToken(bytes);
    }
    public void removeAccessToken(String tokenValue) {
        byte[] accessKey = serializeKey(ACCESS + tokenValue);
        byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + tokenValue);
        byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
        RedisConnection conn = getConnection();
        try {
            byte[] access = conn.get(accessKey);
            byte[] auth = conn.get(authKey);
            conn.openPipeline();
            conn.del(accessKey);
            conn.del(accessToRefreshKey);
            // Don't remove the refresh token - it's up to the caller to do that
            conn.del(authKey);
            conn.closePipeline();
            OAuth2Authentication authentication = deserializeAuthentication(auth);
            if (authentication != null) {
                String key = authenticationKeyGenerator.extractKey(authentication);
                byte[] relationIdTokenKey = getRelationIdTokenKey(authentication);
                byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
                byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
                byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
                conn.openPipeline();
                conn.del(authToAccessKey);
                conn.lRem(unameKey, 1, access);
                conn.lRem(clientId, 1, access);
                conn.del(serialize(ACCESS + key));
                if(relationIdTokenKey!=null){
                    conn.del(relationIdTokenKey);
                }
                conn.closePipeline();
            }
        } catch (Exception e){
            e.printStackTrace();
            log.error("removeAccessToken 失敗:{}",e.getMessage());
        }finally {
            conn.close();
        }
    }
    @Override
    public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
        RedisConnection conn = getConnection();
        try {
            byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
            byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
            byte[] serializedRefreshToken = serialize(refreshToken);
            conn.openPipeline();
            if (springDataRedis_2_0) {
                try {
                    this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken);
                    this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication));
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                conn.set(refreshKey, serializedRefreshToken);
                conn.set(refreshAuthKey, serialize(authentication));
            }
            expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey);
            conn.closePipeline();
        } catch (Exception e){
            e.printStackTrace();
            log.error("storeRefreshToken 失敗:{}",e.getMessage());
        }finally {
            conn.close();
        }
    }
    private void expireRefreshToken(OAuth2RefreshToken refreshToken, RedisConnection conn, byte[] refreshKey, byte[] refreshAuthKey) {
        if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
            ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
            Date expiration = expiringRefreshToken.getExpiration();
            if (expiration != null) {
                int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
                        .intValue();
                conn.expire(refreshKey, seconds);
                conn.expire(refreshAuthKey, seconds);
            }
        }
    }
    @Override
    public OAuth2RefreshToken readRefreshToken(String tokenValue) {
        byte[] key = serializeKey(REFRESH + tokenValue);
        byte[] bytes;
        RedisConnection conn = getConnection();
        try {
            bytes = conn.get(key);
        } finally {
            conn.close();
        }
        return deserializeRefreshToken(bytes);
    }
    @Override
    public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
        removeRefreshToken(refreshToken.getValue());
    }
    public void removeRefreshToken(String tokenValue) {
        RedisConnection conn = getConnection();
        try {
            byte[] refreshKey = serializeKey(REFRESH + tokenValue);
            byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue);
            byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue);
            byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
            conn.openPipeline();
            conn.del(refreshKey);
            conn.del(refreshAuthKey);
            conn.del(refresh2AccessKey);
            conn.del(access2RefreshKey);
            conn.closePipeline();
        } catch (Exception e){
            e.printStackTrace();
            log.error("removeRefreshToken 失?。簕}",e.getMessage());
        }finally {
            conn.close();
        }
    }
    @Override
    public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
        removeAccessTokenUsingRefreshToken(refreshToken.getValue());
    }
    private void removeAccessTokenUsingRefreshToken(String refreshToken) {
        byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken);
        RedisConnection conn = getConnection();
        byte[] bytes = null;
        try {
            bytes = conn.get(key);
            conn.del(key);
        } finally {
            conn.close();
        }
        if (bytes == null) {
            return;
        }
        String accessToken = deserializeString(bytes);
        if (accessToken != null) {
            removeAccessToken(accessToken);
        }
    }
    @Override
    public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
        byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(clientId, userName));
        List<byte[]> byteList;
        RedisConnection conn = getConnection();
        try {
            byteList = conn.lRange(approvalKey, 0, -1);
        } finally {
            conn.close();
        }
        return getTokenCollections(byteList);
    }
    @Override
    public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
        byte[] key = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + clientId);
        List<byte[]> byteList;
        RedisConnection conn = getConnection();
        try {
            byteList = conn.lRange(key, 0, -1);
        } finally {
            conn.close();
        }
        return getTokenCollections(byteList);
    }
    private Collection<OAuth2AccessToken> getTokenCollections(List<byte[]> byteList) {
        if (byteList == null || byteList.size() == 0) {
            return Collections.emptySet();
        }
        List<OAuth2AccessToken> accessTokens = new ArrayList<>(byteList.size());
        for (byte[] bytes : byteList) {
            OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
            accessTokens.add(accessToken);
        }
        return Collections.unmodifiableCollection(accessTokens);
    }
}

五、token續(xù)期

方式:后端自動續(xù)期,APP前端不用處理。

在gateway服務(wù)中,每次校驗token時,如果token離過期時間小于24小時,則自動續(xù)期。

5.1 gateway服務(wù)代碼

public class CustomAuthenticationManager implements ReactiveAuthenticationManager {
    private TokenStore tokenStore;
    public CustomAuthenticationManager(TokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }
    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        return Mono.justOrEmpty(authentication)
                .filter(a -> a instanceof BearerTokenAuthenticationToken)
                .cast(BearerTokenAuthenticationToken.class)
                .map(BearerTokenAuthenticationToken::getToken)
                .flatMap((accessTokenValue -> {
                    OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
                    if (accessToken == null) {
                        throw new AlanChenException(ResultCode.UNAUTHORIZED,"登錄狀態(tài)失效");
                    } else if (accessToken.isExpired()) {
                        throw new AlanChenException(ResultCode.UNAUTHORIZED,"登錄狀態(tài)失效");
                    } else {
                        OAuth2RefreshToken refreshToken= tokenStore.readRefreshToken(accessToken.getRefreshToken().getValue());
                        if(null == refreshToken) {
                            throw new AlanChenException(ResultCode.JWT_OFFLINE,"賬號在其他設(shè)備登錄了");
                        }
                    }
                    // token續(xù)期代碼在readAuthentication方法里
                    OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
                    if (result == null) {
                        throw new AlanChenException(ResultCode.FORBIDDEN,"沒有權(quán)限");
                    }
                    return Mono.just(result);
                }))
                .cast(Authentication.class);
    }
}

注意:gateway這里取token不是直接用的App前端傳過來的token,而是通過Authentication來取的,這有這樣后端token續(xù)期了才會有效。

5.2 CustomRedisTokenStore代碼

@Slf4j
public class CustomRedisTokenStore implements TokenStore {
   //其他代碼省略
   @Override
    public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
        OAuth2Authentication auth2Authentication = readAuthentication(token.getValue());
        if (auth2Authentication != null) {
            //獲取過期時長
            int validitySeconds = 2592000; //2592000
            int expiresRatio = validitySeconds - token.getExpiresIn();
            //判斷是否需要續(xù)簽,當(dāng)前剩余時間小于過期時長的24小時則續(xù)簽
            if (expiresRatio >= 24 * 3600) {
                //更新AccessToken過期時間
                DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;
                Date expiration = new Date(System.currentTimeMillis() + (validitySeconds * 1000L));
                oAuth2AccessToken.setExpiration(expiration);
                storeAccessToken(oAuth2AccessToken, auth2Authentication, true);
                OAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken(token.getRefreshToken().getValue(), expiration);
                storeRefreshToken(refreshToken, auth2Authentication);
            }
        }
        return auth2Authentication;
    }
}

以上就是OAuth2生成token代碼備忘實現(xiàn)過程示例的詳細(xì)內(nèi)容,更多關(guān)于OAuth2生成token代碼備忘的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java數(shù)據(jù)結(jié)構(gòu)與算法之雙向鏈表、環(huán)形鏈表及約瑟夫問題深入理解

    Java數(shù)據(jù)結(jié)構(gòu)與算法之雙向鏈表、環(huán)形鏈表及約瑟夫問題深入理解

    這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)與算法之雙向鏈表、環(huán)形鏈表及約瑟夫問題深入理解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • java 利用反射獲取內(nèi)部類靜態(tài)成員變量的值操作

    java 利用反射獲取內(nèi)部類靜態(tài)成員變量的值操作

    這篇文章主要介紹了java 利用反射獲取內(nèi)部類靜態(tài)成員變量的值操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • Java開發(fā)工具IntelliJ IDEA安裝圖解

    Java開發(fā)工具IntelliJ IDEA安裝圖解

    這篇文章主要介紹了Java開發(fā)工具IntelliJ IDEA安裝圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-11-11
  • SpringBoot中的Spring Cloud Hystrix原理和用法詳解

    SpringBoot中的Spring Cloud Hystrix原理和用法詳解

    在Spring Cloud中,Hystrix是一個非常重要的組件,Hystrix可以幫助我們構(gòu)建具有韌性的分布式系統(tǒng),保證系統(tǒng)的可用性和穩(wěn)定性,在本文中,我們將介紹SpringBoot中的Hystrix,包括其原理和如何使用,需要的朋友可以參考下
    2023-07-07
  • Java異常鏈表throw結(jié)構(gòu)assert詳細(xì)解讀

    Java異常鏈表throw結(jié)構(gòu)assert詳細(xì)解讀

    這篇文章主要給大家介紹了關(guān)于Java中方法使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-08-08
  • mybatis一直加載xml,找到錯誤的解決方案

    mybatis一直加載xml,找到錯誤的解決方案

    這篇文章主要介紹了mybatis一直加載xml,找到錯誤的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • 初識Java設(shè)計模式適配器模式

    初識Java設(shè)計模式適配器模式

    這篇文章主要為大家詳細(xì)介紹了Java設(shè)計模式適配器模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • JavaGUI使用標(biāo)簽與按鈕方法詳解

    JavaGUI使用標(biāo)簽與按鈕方法詳解

    這篇文章主要介紹了JavaGUI使用標(biāo)簽與按鈕方法,前段時間學(xué)了GUI,總體上概念還是有點模糊,于是決定花點時間簡單整理下。先簡單介紹一下GUI,GUI就是圖形用戶界面
    2023-03-03
  • Spring?Boot常用的參數(shù)驗證技巧和使用方法

    Spring?Boot常用的參數(shù)驗證技巧和使用方法

    Spring Boot是一個使用Java編寫的開源框架,用于快速構(gòu)建基于Spring的應(yīng)用程序,這篇文章主要介紹了Spring?Boot常用的參數(shù)驗證技巧和使用方法,需要的朋友可以參考下
    2023-09-09
  • java-list創(chuàng)建的兩種常見方式

    java-list創(chuàng)建的兩種常見方式

    本文給大家分享Java-list創(chuàng)建的兩種常見方式,每種方式結(jié)合實例代碼給大家講解的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2022-11-11

最新評論