pigxCloud微服务项目06——服务端——token过期时间设置

token过期时间设置

  • 1、账号密码登录
  • 2、手机验证码登录和社交账号登录

1、账号密码登录

已启动以下:nacos、gateway、auth、admin四个服务(启动顺序)
修改AuthorizationServerConfig文件

package com.cxbdapp.msp.auth.config;

import cn.hutool.core.util.StrUtil;
import com.cxbdapp.msp.common.core.constant.SecurityConstants;
import com.cxbdapp.msp.common.data.tenant.TenantContextHolder;
import com.cxbdapp.msp.common.security.component.MspWebResponseExceptionTranslator;
import com.cxbdapp.msp.common.security.service.MspClientDetailsService;
import com.cxbdapp.msp.common.security.service.MspUserDetailsService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;

/**
 * @author msp
 * @date 2018/6/22
 * 认证服务器配置
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	private final DataSource dataSource;
	private final TokenEnhancer mspTokenEnhancer;
	private final MspUserDetailsService mspUserDetailsService;
	private final AuthenticationManager authenticationManagerBean;
	private final RedisConnectionFactory redisConnectionFactory;

	@Override
	@SneakyThrows
	public void configure(ClientDetailsServiceConfigurer clients) {
		MspClientDetailsService clientDetailsService = new MspClientDetailsService(dataSource);
		clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
		clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
		clients.withClientDetails(clientDetailsService);
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
		oauthServer.allowFormAuthenticationForClients()
				.checkTokenAccess("isAuthenticated()");
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
		endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
				.tokenStore(tokenStore())
				.tokenEnhancer(mspTokenEnhancer)
				.userDetailsService(mspUserDetailsService)
				.authenticationManager(authenticationManagerBean)
				.reuseRefreshTokens(false)
				.pathMapping("/oauth/confirm_access", "/token/confirm_access")
				.exceptionTranslator(new MspWebResponseExceptionTranslator());

		DefaultTokenServices tokenServices = new DefaultTokenServices();
		tokenServices.setTokenStore(endpoints.getTokenStore());
		tokenServices.setSupportRefreshToken(true);
		tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
		tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
		tokenServices.setAccessTokenValiditySeconds(60 * 60 * 24 * 7); // token有效期设置7天
		tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 30); // refresh_token有效期设置30天
		endpoints.tokenServices(tokenServices);
	}

	@Bean
	public TokenStore tokenStore() {
		RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
		tokenStore.setPrefix(SecurityConstants.MSP_PREFIX + SecurityConstants.OAUTH_PREFIX);
		tokenStore.setAuthenticationKeyGenerator(new DefaultAuthenticationKeyGenerator() {
			@Override
			public String extractKey(OAuth2Authentication authentication) {
				return super.extractKey(authentication) + StrUtil.COLON + TenantContextHolder.getTenantId();
			}
		});
		return tokenStore;
	}
}

修改位置:
pigxCloud微服务项目06——服务端——token过期时间设置_第1张图片

2、手机验证码登录和社交账号登录

手机验证码登录
pigxCloud微服务项目06——服务端——token过期时间设置_第2张图片
社交账号登录

/**
	 * openid登录,并获取token
	 *
	 * @param miniOpenid 小程序openid
	 * @return token
	 */
	private String getOpenidToken(String miniOpenid) {
		String token;
		try {
			String requestUrl = "http://msp-auth:3000/mobile/token/social?grant_type=mobil&mobile=MINI@" + miniOpenid;
			String result = HttpRequest.post(requestUrl)
					.header("Authorization", "Basic cGlnOnBpZw==")
					.execute().body();
			log.info("响应报文:{}", result);
			JSONObject jsonObject = JSONUtil.parseObj(result);
			token = (String) jsonObject.get("access_token");
			return token;

		} catch (Exception e) {
			log.error("获取token错误", e);
		}
		return null;
	}

通过手机验证码、或社交账号登录,修改AuthorizationServerConfig文件没有作用,需要修改如下文件:

package com.cxbdapp.msp.common.security.component;

import com.cxbdapp.msp.common.core.constant.SecurityConstants;
import com.cxbdapp.msp.common.security.service.MspUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author msp
 * @date 2019-09-17
 * 

* token增强,客户端模式不增强。 */ public class MspTokenEnhancer implements TokenEnhancer { /** * Provides an opportunity for customization of an access token (e.g. through its additional information map) during * the process of creating a new token for use by a client. * * @param accessToken the current access token with its expiration and refresh token * @param authentication the current authentication including client and user details * @return a new token enhanced with additional information */ @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { if (SecurityConstants.CLIENT_CREDENTIALS .equals(authentication.getOAuth2Request().getGrantType())) { return accessToken; } final Map<String, Object> additionalInfo = new HashMap<>(8); MspUser mspUser = (MspUser) authentication.getUserAuthentication().getPrincipal(); additionalInfo.put(SecurityConstants.DETAILS_USER_ID, mspUser.getId()); additionalInfo.put(SecurityConstants.DETAILS_USERNAME, mspUser.getUsername()); additionalInfo.put(SecurityConstants.DETAILS_DEPT_ID, mspUser.getDeptId()); additionalInfo.put(SecurityConstants.DETAILS_TENANT_ID, mspUser.getTenantId()); additionalInfo.put(SecurityConstants.DETAILS_REALNAME, mspUser.getRealname()); additionalInfo.put(SecurityConstants.DETAILS_CREATE_USER_IDS, mspUser.getCreateUserIds()); additionalInfo.put(SecurityConstants.DETAILS_LICENSE, SecurityConstants.MSP_LICENSE); additionalInfo.put(SecurityConstants.ACTIVE, Boolean.TRUE); additionalInfo.put(SecurityConstants.USER_TYPE, mspUser.getUserType()); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); int tokenValidityInMilliseconds = 60 * 60 * 24 * 7; // token有效期设置7天 long now = (new Date()).getTime(); Date validity = new Date(now + tokenValidityInMilliseconds * 1000); ((DefaultOAuth2AccessToken) accessToken).setExpiration(validity); return accessToken; } }

修改位置:
pigxCloud微服务项目06——服务端——token过期时间设置_第3张图片

你可能感兴趣的:(微服务,pigx,微服务,pigx)