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

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;
	}
}

修改位置:
在这里插入图片描述

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
 * <p>
 * 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;
	}
}

修改位置:
在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小言W

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值