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

The following examples show how to use org.springframework.security.oauth2.common.DefaultOAuth2AccessToken. 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 File: AuthorizationServerConfigration.java    From Taroco with 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 #2
Source File: JwtTokenEnhancer.java    From sophia_scaffolding with 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 #3
Source File: OAuth2RestOperationsConfiguration.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: OAuth2HttpClientTest.java    From feign-oauth2-spring-cloud-starter with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: SmartlingAuthorizationCodeAccessTokenProvider.java    From mojito with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: CustomAccessTokenConverter.java    From spring-boot-2-oauth2-resource-jwt with MIT License 6 votes vote down vote up
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 #7
Source File: OsiamTokenEnhancer.java    From osiam with 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 File: JwtTokenRedisStore.java    From onetwo with 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 #9
Source File: GatewayRestControllerTest.java    From konker-platform with 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 #10
Source File: AuthorizationServerConfig.java    From black-shop with 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 #11
Source File: IHealthShim.java    From shimmer with 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 #12
Source File: Oauth2ClientRestTemplateTest.java    From spring-boot with 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 #13
Source File: CustomRedisTokenStore.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: TokenServiceImpl.java    From oauth-server with 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 #15
Source File: OAuth2ClientCredentialsService.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: AuthorizationServerConfig.java    From cloud-service with 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 #17
Source File: CustomTokenEnhancer.java    From Building-Web-Apps-with-Spring-5-and-Angular with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    final Map<String, Object> additionalInfo = new HashMap<>();
    Collection<GrantedAuthority> authorities = authentication.getAuthorities();
    Object[] ga = authorities.toArray();
    SimpleGrantedAuthority sga = (SimpleGrantedAuthority) ga[0];
    String role = sga.getAuthority();
    additionalInfo.put("role", role);
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example #18
Source File: CustomTokenEnhancer.java    From java-microservice with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(
        OAuth2AccessToken accessToken,
        OAuth2Authentication authentication
) {
    Map<String, Object> additionalInfo = new HashMap<>();
    additionalInfo.put("name", authentication.getName());
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example #19
Source File: CustomTokenEnhancer.java    From Building-Web-Apps-with-Spring-5-and-Angular with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    final Map<String, Object> additionalInfo = new HashMap<>();
    Collection<GrantedAuthority> authorities = authentication.getAuthorities();
    Object[] ga = authorities.toArray();
    SimpleGrantedAuthority sga = (SimpleGrantedAuthority) ga[0];
    String role = sga.getAuthority();
    additionalInfo.put("role", role);
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example #20
Source File: IatTokenEnhancer.java    From tutorials with MIT License 5 votes vote down vote up
private void addClaims(DefaultOAuth2AccessToken accessToken) {
    DefaultOAuth2AccessToken token = accessToken;
    Map<String, Object> additionalInformation = token.getAdditionalInformation();
    if (additionalInformation.isEmpty()) {
        additionalInformation = new LinkedHashMap<String, Object>();
    }
    //add "iat" claim with current time in secs
    //this is used for an inactive session timeout
    additionalInformation.put("iat", new Integer((int)(System.currentTimeMillis()/1000L)));
    token.setAdditionalInformation(additionalInformation);
}
 
Example #21
Source File: UserInfoTokenServicesRefreshTokenTests.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void withRestTemplate() {
	OAuth2ProtectedResourceDetails resource = new AuthorizationCodeResourceDetails();
	OAuth2ClientContext context = new DefaultOAuth2ClientContext();
	DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("FOO");
	token.setRefreshToken(new DefaultExpiringOAuth2RefreshToken("BAR", new Date(0L)));
	context.setAccessToken(token);
	this.services.setRestTemplate(new OAuth2RestTemplate(resource, context));
	assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("me");
	assertThat(context.getAccessToken().getValue()).isEqualTo("FOO");
	// The refresh token is still intact
	assertThat(context.getAccessToken().getRefreshToken()).isEqualTo(token.getRefreshToken());
}
 
Example #22
Source File: PoPTokenEnhancer.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(
    OAuth2AccessToken accessToken,
    OAuth2Authentication authentication) {

    Map<String, Object> additional = new HashMap<>();
    String publicKey = authentication.getOAuth2Request().getRequestParameters().get("public_key");
    additional.put("public_key", publicKey);

    DefaultOAuth2AccessToken defaultAccessToken = (DefaultOAuth2AccessToken) accessToken;
    defaultAccessToken.setAdditionalInformation(additional);

    return accessToken;
}
 
Example #23
Source File: CustomTokenEnhancer.java    From Auth-service with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
                                 OAuth2Authentication authentication) {
    CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
    authentication.getUserAuthentication().getPrincipal();
    Map<String, Object> info = new HashMap<>();
    info.put(TOKEN_SEG_USER_ID, userDetails.getUserId());

    DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken);
    customAccessToken.setAdditionalInformation(info);

    OAuth2AccessToken enhancedToken = super.enhance(customAccessToken, authentication);
    enhancedToken.getAdditionalInformation().put(TOKEN_SEG_CLIENT, userDetails.getClientId());
    return enhancedToken;
}
 
Example #24
Source File: AuthServerConfig.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
	super.configure(endpoints);
	endpoints.authenticationManager(authenticationManagerBean);
	endpoints.tokenStore(tokenStore());
	endpoints.tokenEnhancer(new TokenEnhancer() {

		@Override
		public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
			if (authentication.getPrincipal() instanceof User) {
				final User user = (User) authentication.getPrincipal();

				final Set<String> scopes = new HashSet<String>();
				for (GrantedAuthority authority : user.getAuthorities()) {
					final String role = authority.getAuthority();

					if (role.startsWith("ROLE_")) {
						scopes.add(role.substring(5).toLowerCase());
					}
					else {
						scopes.add(role.toLowerCase());
					}
				}
				((DefaultOAuth2AccessToken) accessToken).setScope(scopes);

			}
			return accessToken;
		}
	});
}
 
Example #25
Source File: JWTokenEnhancer.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
    Map<String, Object> info = new HashMap<>();
    info.put("message", "hello world");

    ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
    return oAuth2AccessToken;
}
 
Example #26
Source File: JWTTokenEnhancer.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    Map<String, Object> additionalInfo = new HashMap<>();
    String              orgId          = getOrgId(authentication.getName());

    additionalInfo.put("organizationId", orgId);                        // Add organizationId field into JWT token

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example #27
Source File: TokenJwtEnhancer.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * Enhance o auth 2 access token.
 *
 * @param accessToken          the access token
 * @param oAuth2Authentication the o auth 2 authentication
 *
 * @return the o auth 2 access token
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication oAuth2Authentication) {
	Map<String, Object> info = new HashMap<>(8);
	info.put("timestamp", System.currentTimeMillis());
	Authentication authentication = oAuth2Authentication.getUserAuthentication();
	if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
		Object principal = authentication.getPrincipal();
		info.put("loginName", ((UserDetails) principal).getUsername());
	}

	((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);

	return accessToken;
}
 
Example #28
Source File: PigAuthorizationConfig.java    From pig with MIT License 5 votes vote down vote up
/**
 * jwt 生成token 定制化处理
 *
 * @return TokenEnhancer
 */
@Bean
public TokenEnhancer tokenEnhancer() {
    return (accessToken, authentication) -> {
        final Map<String, Object> additionalInfo = new HashMap<>(2);
        additionalInfo.put("license", SecurityConstants.PIG_LICENSE);
        UserDetailsImpl user = (UserDetailsImpl) authentication.getUserAuthentication().getPrincipal();
        if (user != null) {
            additionalInfo.put("userId", user.getUserId());
        }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    };
}
 
Example #29
Source File: CustomTokenEnhancer.java    From oauth2lab with 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 #30
Source File: FwAuthorizationConfiguration.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
/**
 * jwt 生成token 定制化处理
 * 
 * @return TokenEnhancer
 */
@Bean
public TokenEnhancer tokenEnhancer() {
	return (accessToken, authentication) -> {
		final Map<String, Object> additionalInfo = new HashMap<>(1);
		additionalInfo.put("license", SecurityConstant.LICENSE);
		((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
		return accessToken;
	};
}