Java Code Examples for org.springframework.security.oauth2.common.DefaultOAuth2AccessToken

The following examples show how to use org.springframework.security.oauth2.common.DefaultOAuth2AccessToken. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cloud-service   Source File: AuthorizationServerConfig.java    License: MIT License 6 votes vote down vote up
/**
 * 将当前用户信息追加到登陆后返回的json数据里<br>
 * 通过参数access_token.add-userinfo控制<br>
 * 2019.07.13
 *
 * @param accessToken
 * @param authentication
 */
private void addLoginUserInfo(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    if (!addUserInfo) {
        return;
    }

    if (accessToken instanceof DefaultOAuth2AccessToken) {
        DefaultOAuth2AccessToken defaultOAuth2AccessToken = (DefaultOAuth2AccessToken) accessToken;

        Authentication userAuthentication = authentication.getUserAuthentication();
        Object principal = userAuthentication.getPrincipal();
        if (principal instanceof LoginAppUser) {
            LoginAppUser loginUser = (LoginAppUser) principal;

            Map<String, Object> map = new HashMap<>(defaultOAuth2AccessToken.getAdditionalInformation()); // 旧的附加参数
            map.put("loginUser", loginUser); // 追加当前登陆用户

            defaultOAuth2AccessToken.setAdditionalInformation(map);
        }
    }
}
 
Example 2
private void retrieveNewAccessToken() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    final String authString = jHipsterProperties.getSecurity().getClientAuthorization().getClientId() + ":" + jHipsterProperties.getSecurity().getClientAuthorization().getClientSecret();
    final String authorization = "Basic " + Base64.encodeBase64String(authString.getBytes());
    headers.add("Authorization", authorization);

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("grant_type", "client_credentials");

    HttpEntity<?> requestEntity = new HttpEntity<>(map, headers);
    String uaaServiceId = jHipsterProperties.getSecurity().getClientAuthorization().getTokenServiceId();
    ResponseEntity<DefaultOAuth2AccessToken> responseEntity = this.restTemplate.exchange("http://" + uaaServiceId + "/oauth/token", HttpMethod.POST, requestEntity, DefaultOAuth2AccessToken.class);

    if (!responseEntity.getStatusCode().is2xxSuccessful()) {
        //TODO
    }

    accessToken = Objects.requireNonNull(responseEntity.getBody()).getValue();
}
 
Example 3
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
    OAuth2Authentication auth2Authentication = readAuthentication(token.getValue());
    //是否开启token续签
    boolean isRenew = securityProperties.getAuth().getRenew().getEnable();
    if (isRenew && auth2Authentication != null) {
        OAuth2Request clientAuth = auth2Authentication.getOAuth2Request();
        //判断当前应用是否需要自动续签
        if (checkRenewClientId(clientAuth.getClientId())) {
            //获取过期时长
            int validitySeconds = getAccessTokenValiditySeconds(clientAuth.getClientId());
            if (validitySeconds > 0) {
                double expiresRatio = token.getExpiresIn() / (double)validitySeconds;
                //判断是否需要续签,当前剩余时间小于过期时长的50%则续签
                if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) {
                    //更新AccessToken过期时间
                    DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;
                    oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
                    storeAccessToken(oAuth2AccessToken, auth2Authentication, true);
                }
            }
        }
    }
    return auth2Authentication;
}
 
Example 4
Source Project: spring-boot   Source File: Oauth2ClientRestTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClientCredentialsRestTemplate() throws Exception {

    ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
     details.setId("4");
    details.setClientId(client_id);
    details.setClientSecret(client_secret);
    details.setAccessTokenUri(access_token_uri);
   // details.setScope(Arrays.asList("read write"));
    OAuth2RestTemplate operations = new OAuth2RestTemplate(details,new DefaultOAuth2ClientContext());
   // OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
    operations.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider());

  //  OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails(),oAuth2ClientContext());
    DefaultOAuth2AccessToken token=(DefaultOAuth2AccessToken)operations.getAccessToken();
    token.setTokenType("Bearer");

    System.out.println("client_id : " + client_id);
    System.out.println("source_url : " + source_url);

  //  OAuth2RestOperations operations = restTemplate.clientCredentialsRestTemplate(client_id, client_secret, access_token_uri, scopes);  // getForObject 发送 get 方法
    System.out.println(JSON.toJSONString(operations.getForObject(source_url, JsonNode.class)));  // getForObject 发送 get 方法

}
 
Example 5
Source Project: sophia_scaffolding   Source File: JwtTokenEnhancer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    final Map<String, Object> additionalInfo = new HashMap<>();
    // 给/oauth/token接口加属性roles,author
    String roles = "";
    if (authentication.getAuthorities().size() > 0) {
        JSONObject jsonObject = new JSONObject(authentication.getPrincipal());
        List<Object> authorities = jsonObject.getJSONArray("authorities").toList();
        StringBuilder stringBuilder = new StringBuilder();
        for (Object authority : authorities) {
            Map map = (Map) authority;
            stringBuilder.append(map.get("authority"));
            stringBuilder.append(",");
        }
        roles = stringBuilder.toString();
    }
    if (StringUtils.isNotBlank(roles)) {
        additionalInfo.put("roles", roles.substring(0, roles.length() - 1));
    }
    additionalInfo.put("author", "sophia");
    additionalInfo.put("createTime", df.format(LocalDateTime.now()));
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example 6
@Override
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException {


    logger.debug("Get access token");
    Map<String, String> request = new HashMap<>();
    request.put("userIdentifier", details.getClientId());
    request.put("userSecret", details.getClientSecret());

    DefaultOAuth2AccessToken defaultOAuth2AccessToken = null;
    try {
        DateTime now = getNowForToken();
        AuthenticationResponse authenticationResponse = restTemplate.postForObject(details.getAccessTokenUri(), request, AuthenticationResponse.class);
        defaultOAuth2AccessToken = getDefaultOAuth2AccessToken(now, authenticationResponse);
    } catch (Exception e) {
        String msg = "Can't get Smartling token";
        logger.debug(msg, e);
        throw new OAuth2AccessDeniedException(msg, details, e);
    }

    return defaultOAuth2AccessToken;
}
 
Example 7
Source Project: osiam   Source File: OsiamTokenEnhancer.java    License: MIT License 6 votes vote down vote up
@Override
public OAuth2AccessToken enhance(final OAuth2AccessToken accessToken, final OAuth2Authentication authentication) {
    DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
    Map<String, Object> additionalInformation = new HashMap<>();
    additionalInformation.put("expires_at", token.getExpiration());

    if (token.getRefreshToken() != null) {
        DefaultExpiringOAuth2RefreshToken refreshToken =
                (DefaultExpiringOAuth2RefreshToken) token.getRefreshToken();
        additionalInformation.put("refresh_token_expires_at", refreshToken.getExpiration());
    }

    additionalInformation.put("client_id", authentication.getOAuth2Request().getClientId());

    if (authentication.getUserAuthentication() != null && authentication.getPrincipal() instanceof User) {
        User user = (User) authentication.getPrincipal();
        additionalInformation.put("user_name", user.getUserName());
        additionalInformation.put("user_id", user.getId());
    }

    token.setAdditionalInformation(additionalInformation);

    return accessToken;
}
 
Example 8
Source Project: black-shop   Source File: AuthorizationServerConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * token增强
 *
 * @return TokenEnhancer
 */
@Bean
public TokenEnhancer tokenEnhancer() {
	return (accessToken, authentication) -> {
		if ("client_credentials"
				.equals(authentication.getOAuth2Request().getGrantType())) {
			return accessToken;
		}

		final Map<String, Object> additionalInfo = new HashMap<>(1);
		SecurityUserDetail securityUserDetail = (SecurityUserDetail) authentication.getUserAuthentication().getPrincipal();
		additionalInfo.put("username", securityUserDetail.getUsername());
		((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
		return accessToken;
	};
}
 
Example 9
Source Project: shimmer   Source File: IHealthShim.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected ResponseExtractor<OAuth2AccessToken> getResponseExtractor() {

    return new ResponseExtractor<OAuth2AccessToken>() {

        @Override
        public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {

            JsonNode node = new ObjectMapper().readTree(response.getBody());
            String token = Preconditions
                    .checkNotNull(node.path("AccessToken").textValue(), "Missing access token: %s", node);
            String refreshToken = Preconditions
                    .checkNotNull(node.path("RefreshToken").textValue(), "Missing refresh token: %s" + node);
            String userId =
                    Preconditions.checkNotNull(node.path("UserID").textValue(), "Missing UserID: %s", node);
            long expiresIn = node.path("Expires").longValue() * 1000;
            Preconditions.checkArgument(expiresIn > 0, "Missing Expires: %s", node);

            DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(token);
            accessToken.setExpiration(new Date(System.currentTimeMillis() + expiresIn));
            accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
            accessToken.setAdditionalInformation(ImmutableMap.<String, Object>of("UserID", userId));
            return accessToken;
        }
    };
}
 
Example 10
Source Project: oauth-server   Source File: TokenServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void deleteOne(String tokenId) {
    //筛选token
    AccessTokenDO accessTokenDO = accessTokenMapper.selectByPrimaryKey(tokenId);
    //token不存在
    if (accessTokenDO == null) {
        throw new CommonException("error.delete.token.not.exist");
    }
    //提取sessionId
    DefaultOAuth2AccessToken deserialize = SerializationUtils.deserialize(accessTokenDO.getToken());
    //删除redis session
    redisTemplate.delete(SESSION_KEY_PREFIX + deserialize.getAdditionalInformation().get("sessionId"));
    //删除db accessToken/refreshToken
    accessTokenMapper.deleteByPrimaryKey(tokenId);
    refreshTokenMapper.deleteByPrimaryKey(accessTokenDO.getRefreshToken());
    LOGGER.info("delete token,tokenId:{},sessionId:{}",tokenId,deserialize.getAdditionalInformation().get("sessionId"));
}
 
Example 11
Source Project: Taroco   Source File: AuthorizationServerConfigration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * jwt 生成token 定制化处理
 * <p>
 * 额外信息(这部分信息不关乎加密方式), 添加到随token一起的additionalInformation当中
 *
 * @return TokenEnhancer
 */
@Bean
public TokenEnhancer tokenEnhancer() {
    return (accessToken, authentication) -> {
        final Authentication userAuthentication = authentication.getUserAuthentication();
        if (userAuthentication == null) {
            return accessToken;
        }
        Map<String, Object> additionalInfo = new LinkedHashMap<>(accessToken.getAdditionalInformation());
        final Object principal = userAuthentication.getPrincipal();
        User user;
        if (principal instanceof User) {
            user = (User) principal;
        } else {
            final String username = (String) principal;
            user = (User) userNameUserDetailsService.loadUserByUsername(username);
        }
        additionalInfo.put(SecurityConstants.LICENSE_KEY, SecurityConstants.LICENSE);
        additionalInfo.put(SecurityConstants.USER_NAME_HEADER, user.getUsername());
        additionalInfo.put(SecurityConstants.USER_ID_HEADER, user.getUserId());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    };
}
 
Example 12
Source Project: onetwo   Source File: JwtTokenRedisStore.java    License: Apache License 2.0 6 votes vote down vote up
/***
 * auth server store accessToken
 * tokenEndpoint store acessToken
 */
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
	DefaultOAuth2AccessToken at = (DefaultOAuth2AccessToken) token;
	String tokenId = getTokenId(at);
	Assert.hasLength(tokenId, "tokenId can not be null");
	String key = getStoreKey(tokenId);
	JwtStoredTokenValue value = JwtStoredTokenValue.builder()
										.token(at.getValue())
										.build();
	BoundValueOperations<String, JwtStoredTokenValue> ops = redisTemplate.boundValueOps(key);
	//保存到redis并设置过期时间
	ops.set(value, at.getExpiresIn(), TimeUnit.MILLISECONDS);
	//把tokenvalue置换为tokenId
	at.setValue(tokenId);
}
 
Example 13
public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
	DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(value);
	Map<String, Object> info = new HashMap<String, Object>(map);

	info.remove(EXP);
	info.remove(AUD);
	info.remove(CLIENT_ID);
	info.remove(SCOPE);

	if (map.containsKey(EXP))
		token.setExpiration(new Date((Long) map.get(EXP) * 1000L));

	if (map.containsKey(JTI))
		info.put(JTI, map.get(JTI));

	token.setScope(extractScope(map));
	token.setAdditionalInformation(info);
	return token;
}
 
Example 14
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public DefaultOAuth2ClientContext oauth2ClientContext() {
	DefaultOAuth2ClientContext context = new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest());
	Authentication principal = SecurityContextHolder.getContext().getAuthentication();
	if (principal instanceof OAuth2Authentication) {
		OAuth2Authentication authentication = (OAuth2Authentication) principal;
		Object details = authentication.getDetails();
		if (details instanceof OAuth2AuthenticationDetails) {
			OAuth2AuthenticationDetails oauthsDetails = (OAuth2AuthenticationDetails) details;
			String token = oauthsDetails.getTokenValue();
			context.setAccessToken(new DefaultOAuth2AccessToken(token));
		}
	}
	return context;
}
 
Example 15
@Test
public void authenticate() {

    // given
    final String token = UUID.randomUUID().toString();
    oauth2ClientContext.setAccessToken(new DefaultOAuth2AccessToken(token));

    // when
    final ResponseEntity response = authenticationClient.authenticate();

    // then
    assertNotNull(response);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertTrue(response.getHeaders().containsKey("Authorization"));
    assertEquals(token, response.getHeaders().getFirst("Authorization").split(" ")[1]);
}
 
Example 16
Source Project: konker-platform   Source File: GatewayRestControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateToken() throws Exception {

    OAuth2AccessToken oAuth2AccessToken = new DefaultOAuth2AccessToken("ab66tfz3mw");

    when(oAuth2AccessTokenService.getGatewayAccessToken(tenant, application, gateway))
            .thenReturn(ServiceResponseBuilder.<OAuth2AccessToken> ok().withResult(oAuth2AccessToken).build());

    getMockMvc().perform(MockMvcRequestBuilders
            .get(MessageFormat.format("/{0}/{1}/{2}/token", application.getName(), BASEPATH, gateway.getGuid()))
            .contentType("application/json")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
            .andExpect(jsonPath("$.status", is("success")))
            .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
            .andExpect(jsonPath("$.result").isMap())
            .andExpect(jsonPath("$.result.access_token", is("ab66tfz3mw")))
    ;

}
 
Example 17
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    Map<String, Object> additionalInfo = Maps.newHashMap();
    //自定义token内容,加入组织机构信息
    additionalInfo.put("organization", authentication.getName());
 DefaultOAuth2AccessToken defaultOAuth2AccessToken = (DefaultOAuth2AccessToken) accessToken;
 defaultOAuth2AccessToken.setAdditionalInformation(additionalInfo);
 return accessToken;
}
 
Example 18
@Bean
public TokenEnhancer tokenEnhancer() {
	return (accessToken, authentication) -> {
		final Map<String, Object> additionalInfo = new HashMap<>(1);
		additionalInfo.put("license", SecurityConstants.PROJECT_LICENSE);
		((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
		return accessToken;
	};
}
 
Example 19
Source Project: spring-security-oauth   Source File: CustomTokenEnhancer.java    License: MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    final Map<String, Object> additionalInfo = new HashMap<>();
    additionalInfo.put("organization", authentication.getName() + randomAlphabetic(4));
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example 20
Source Project: shimmer   Source File: GoogleFitShim.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
        OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException,
        OAuth2AccessDeniedException {

    OAuth2AccessToken accessToken = super.refreshAccessToken(resource, refreshToken, request);
    // Google does not replace refresh tokens, so we need to hold on to the existing refresh token...
    if (accessToken.getRefreshToken() == null) {
        ((DefaultOAuth2AccessToken) accessToken).setRefreshToken(refreshToken);
    }
    return accessToken;
}
 
Example 21
Source Project: microservices-platform   Source File: AuthJwtTokenStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * jwt 生成token 定制化处理
 * 添加一些额外的用户信息到token里面
 *
 * @return TokenEnhancer
 */
@Bean
public TokenEnhancer tokenEnhancer() {
    return (accessToken, authentication) -> {
        final Map<String, Object> additionalInfo = new HashMap<>(1);
        Object principal = authentication.getPrincipal();
        //增加id参数
        if (principal instanceof SysUser) {
            SysUser user = (SysUser)principal;
            additionalInfo.put("id", user.getId());
        }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    };
}
 
Example 22
Source Project: spring-security-mongo   Source File: OAuth2AccessTokenBuilder.java    License: MIT License 5 votes vote down vote up
public OAuth2AccessToken build() {
    final DefaultOAuth2AccessToken oAuth2AccessToken = new DefaultOAuth2AccessToken(token);
    oAuth2AccessToken.setExpiration(convertToDateFrom(expiration));
    oAuth2AccessToken.setRefreshToken(oAuth2RefreshToken);
    oAuth2AccessToken.setScope(scope);
    oAuth2AccessToken.setAdditionalInformation(additionalInformation);
    return oAuth2AccessToken;
}
 
Example 23
@Override
public AccessTokenRequest getAccessTokenRequest() {
	DefaultAccessTokenRequest tokenRequest = new DefaultAccessTokenRequest(
			new HashMap<String, String[]>());
	tokenRequest.setExistingToken(new DefaultOAuth2AccessToken(value));
	return tokenRequest;
}
 
Example 24
/**
 * token增强器
 *
 * @param accessToken
 * @param authentication
 * @return
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    if (accessToken instanceof DefaultOAuth2AccessToken) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof PrexSecurityUser) {
            PrexSecurityUser user = (PrexSecurityUser) principal;
            HashMap<String, Object> map = new HashMap<>();
            map.put(USERNAME, user.getUsername());
            map.put("userId", user.getUserId());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
        }
    }
    return super.enhance(accessToken, authentication);
}
 
Example 25
/**
 * token增强器
 *
 * @param accessToken
 * @param authentication
 * @return
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    if (accessToken instanceof DefaultOAuth2AccessToken) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof PrexSecurityUser) {
            PrexSecurityUser user = (PrexSecurityUser) principal;
            HashMap<String, Object> map = new HashMap<>();
            map.put(USERNAME, user.getUsername());
            map.put("userId", user.getUserId());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
        }
    }
    return super.enhance(accessToken, authentication);
}
 
Example 26
/**
 * 令牌增强器
 *
 * @return TokenEnhancer
 */
@Bean
public TokenEnhancer tokenEnhancer() {
    return (accessToken, authentication) -> {
        Map<String, Object> additionalInfo = new HashMap<>(1);
        additionalInfo.put("organization", authentication.getName());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    };
}
 
Example 27
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    // 创建一个自定义信息
    Map<String, Object> additionalInfo = new HashMap<>(1);
    // 设置值
    additionalInfo.put("organization", authentication.getName());
    // 存进去
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    // 返回
    return accessToken;
}
 
Example 28
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    log.info(":>>> MermaidTokenEnhancer enhance ");
    Map<String, Object> additionalInfo = new HashMap<>();
    additionalInfo.put("userId", 1001L);
    additionalInfo.put("roles", "admin");
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    log.debug(":>>> MermaidTokenEnhancer {$accessToken}:{}", accessToken);
    return accessToken;
}
 
Example 29
Source Project: open-cloud   Source File: OpenJwtAccessTokenEnhancer.java    License: MIT License 5 votes vote down vote up
/**
 * 生成token
 * @param accessToken
 * @param authentication
 * @return
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);
    if(authentication.getPrincipal()!=null && authentication.getPrincipal() instanceof OpenUserDetails){
        // 设置额外用户信息
        OpenUserDetails baseUser = ((OpenUserDetails) authentication.getPrincipal());
        final Map<String, Object> additionalInfo = new HashMap<>(8);
        additionalInfo.put(OpenSecurityConstants.OPEN_ID, baseUser.getUserId());
        additionalInfo.put(OpenSecurityConstants.DOMAIN, baseUser.getDomain());
        defaultOAuth2AccessToken.setAdditionalInformation(additionalInfo);
    }

    return super.enhance(defaultOAuth2AccessToken, authentication);
}
 
Example 30
private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
    int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
    if (validitySeconds > 0) {
        token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
    }
    token.setRefreshToken(refreshToken);
    token.setScope(authentication.getOAuth2Request().getScope());

    return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
}