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

The following examples show how to use org.springframework.security.oauth2.common.OAuth2AccessToken. 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: TokenService.java    From osiam with MIT License 7 votes vote down vote up
public AccessToken validateToken(final String token) {
    OAuth2Authentication auth = tokenStore.readAuthentication(token);
    OAuth2AccessToken accessToken = tokenStore.getAccessToken(auth);
    OAuth2Request authReq = auth.getOAuth2Request();

    AccessToken.Builder tokenBuilder = new AccessToken.Builder(token).setClientId(authReq.getClientId());

    if (auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) {
        User user = (User) auth.getPrincipal();
        tokenBuilder.setUserName(user.getUserName());
        tokenBuilder.setUserId(user.getId());
    }

    tokenBuilder.setExpiresAt(accessToken.getExpiration());
    for (String scopeString : authReq.getScope()) {
        tokenBuilder.addScope(new Scope(scopeString));
    }

    return tokenBuilder.build();
}
 
Example #2
Source File: MongoTokenStore.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    final String authenticationId = authenticationKeyGenerator.extractKey(authentication);
    OAuth2AccessToken accessToken = null;

    try {
        AccessToken token = tokenRepository.findAccessTokenByAuthenticationId(authenticationId);
        accessToken = token != null ? token.token() : null;
    } catch (IllegalArgumentException e) {
        LOG.error("Could not extract access token for authentication {}", authentication);
    }

    if (accessToken != null
            && !authenticationId.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
        removeAccessToken(accessToken.getValue());
        storeAccessToken(accessToken, authentication);
    }

    return accessToken;
}
 
Example #3
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example #4
Source File: PigRedisTokenStore.java    From pig with MIT License 6 votes vote down vote up
public void removeAccessToken(String tokenValue) {
    OAuth2AccessToken removed = (OAuth2AccessToken) redisTemplate.opsForValue().get(ACCESS + tokenValue);
    // caller to do that
    OAuth2Authentication authentication = (OAuth2Authentication) this.redisTemplate.opsForValue().get(AUTH + tokenValue);

    this.redisTemplate.delete(AUTH + tokenValue);
    redisTemplate.delete(ACCESS + tokenValue);
    this.redisTemplate.delete(ACCESS_TO_REFRESH + tokenValue);

    if (authentication != null) {
        this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));

        String clientId = authentication.getOAuth2Request().getClientId();
        redisTemplate.opsForList().leftPop(UNAME_TO_ACCESS + getApprovalKey(clientId, authentication.getName()));

        redisTemplate.opsForList().leftPop(CLIENT_ID_TO_ACCESS + clientId);

        this.redisTemplate.delete(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
    }
}
 
Example #5
Source File: AuthorizationHeaderUtil.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeaderFromOAuth2Context() {
    OAuth2AccessToken previousAccessToken = oAuth2RestTemplate.getOAuth2ClientContext().getAccessToken();
    if (previousAccessToken == null) {
        return Optional.empty();
    } else {
        OAuth2AccessToken accessToken;
        try {
            // Get the token from OAuth2ClientContext and refresh it if necessary
            accessToken = oAuth2RestTemplate.getAccessToken();
        } catch (UserRedirectRequiredException e) {
            // It's a refresh failure (because previous token wasn't null)
            // If it's an AJAX Request, this sends a 401 error
            throw new AccessTokenRequiredException("Refreshing access token failed",null);
        }

        String tokenType = accessToken.getTokenType();
        if (!StringUtils.hasText(tokenType)) {
            tokenType = OAuth2AccessToken.BEARER_TYPE;
        }
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #6
Source File: CustomAuthenticationManager.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@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) {
                    return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue));
                } else if (accessToken.isExpired()) {
                    tokenStore.removeAccessToken(accessToken);
                    return Mono.error(new InvalidTokenException("Access token expired: " + accessTokenValue));
                }

                OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
                if (result == null) {
                    return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue));
                }
                return Mono.just(result);
            }))
            .cast(Authentication.class);
}
 
Example #7
Source File: LoginAuthSuccessHandler.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

    try {

        TokenRequest tokenRequest = new TokenRequest(null, null, null, null);

        // 简化
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(new BaseClientDetails());
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);


        OAuth2AccessToken oAuth2AccessToken = yamiTokenServices.createAccessToken(oAuth2Authentication);
        log.info("获取token 成功:{}", oAuth2AccessToken.getValue());

        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
        throw new BadCredentialsException(
                "Failed to decode basic authentication token");
    }

}
 
Example #8
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example #9
Source File: OAuth2AuthorizationServerConfig.java    From NFVO with Apache License 2.0 6 votes vote down vote up
/**
 * Method returns a token that can be used to request a specific image file contained in the
 * NFVImage repository from the REST API.
 *
 * @param imageId ID of the image that can be retrieved with the token
 * @return the oauth2 token for fetching image files from the image repository
 */
public String getNewImageToken(String imageId) {
  Set<GrantedAuthority> authorities = new HashSet<>();
  authorities.add(new SimpleGrantedAuthority(imageId));

  OAuth2Request oAuth2Request = buildOAuth2Request("vimdriver" + imageId, authorities);

  User userPrincipal =
      new User(
          "vimdriver" + imageId, "" + Math.random() * 1000, true, true, true, true, authorities);

  UsernamePasswordAuthenticationToken authenticationToken =
      new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
  OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);

  OAuth2AccessToken token = imageTokenServices.createAccessToken(auth);
  return token.getValue();
}
 
Example #10
Source File: TokenServiceImpl.java    From auth-server with Apache License 2.0 6 votes vote down vote up
@Override
public void revokeTokens(String username) {
  log.debug("Revoking tokens for {}", username);

  if (!(tokenStore instanceof JdbcTokenStore)) {
    log.debug("Token store is not instance of JdbcTokenStore. Cannot revoke tokens!");

    return;
  }

  Collection<OAuth2AccessToken> tokens = ((JdbcTokenStore) tokenStore).findTokensByUserName(username);

  for (OAuth2AccessToken token : tokens) {
    log.debug("Revoking access token {}", token);
    tokenStore.removeAccessToken(token);

    log.debug("Revoking refresh token {}", token.getRefreshToken());
    tokenStore.removeRefreshToken(token.getRefreshToken());
  }

}
 
Example #11
Source File: UserInfoService.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
public Map<String, String> getUserInfoFor(OAuth2AccessToken accessToken) {
    RestTemplate restTemplate = new RestTemplate();

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(
            getHeader(accessToken),
            HttpMethod.GET,
            URI.create("https://www.googleapis.com/oauth2/v3/userinfo")
    );

    ResponseEntity<Map> result = restTemplate.exchange(
            requestEntity, Map.class);

    if (result.getStatusCode().is2xxSuccessful()) {
        return result.getBody();
    }

    throw new RuntimeException("It wasn't possible to retrieve userInfo");
}
 
Example #12
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 #13
Source File: AuthResource.java    From cubeai with Apache License 2.0 6 votes vote down vote up
/**
 * Authenticates a user setting the access and refresh token cookies.
 *
 * @param request  the HttpServletRequest holding - among others - the headers passed from the client.
 * @param response the HttpServletResponse getting the cookies set upon successful authentication.
 * @param params   the login params (username, password, rememberMe).
 * @return the access token of the authenticated user. Will return an error code if it fails to authenticate the user.
 */
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType
    .APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, @RequestBody
    Map<String, String> params) {

    if (params.get("username").equals("system")) {
        return ResponseEntity.badRequest().build();
    }

    int verifyResult = this.uaaClient.validateVerifyCode(params);
    if (1 == verifyResult) {
        return authenticationService.authenticate(request, response, params);
    } else {
        return ResponseEntity.badRequest().build();
    }

}
 
Example #14
Source File: CustomJwtTokenEnhancer.java    From fast-family-master with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
    if (oAuth2AccessToken instanceof DefaultOAuth2AccessToken) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;
        String clientId = oAuth2Authentication.getOAuth2Request().getClientId();
        Date expiration = oAuth2AccessToken.getExpiration();
        String createToken = createToken(clientId, expiration);
        token.setValue(createToken);
        OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
        if (refreshToken instanceof DefaultOAuth2AccessToken) {
            token.setRefreshToken(new DefaultOAuth2RefreshToken(createToken(clientId, expiration)));
        }
        Map<String, Object> additionalInformation = new HashMap<>();
        additionalInformation.put("client_id", oAuth2Authentication.getOAuth2Request().getClientId());
        token.setAdditionalInformation(additionalInformation);
        return token;
    }
    return oAuth2AccessToken;
}
 
Example #15
Source File: SophiaWebResponseExceptionTranslator.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) {

        int status = e.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CACHE_CONTROL, "no-store");
        headers.set(HttpHeaders.PRAGMA, "no-cache");
        if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
            headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
        }

        // 客户端异常直接返回客户端,不然无法解析
        if (e instanceof ClientAuthenticationException) {
            return new ResponseEntity<>(e, headers,
                    HttpStatus.valueOf(status));
        }
        return new ResponseEntity<>(new SophiaAuth2Exception(e.getMessage(), e.getOAuth2ErrorCode()), headers,
                HttpStatus.valueOf(status));

    }
 
Example #16
Source File: MongoTokenStore.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
    LOG.trace("Call readAccessToken, tokenValue = {}", tokenValue);
    OAuth2AccessToken token = null;

    try {
        final String tokenId = extractTokenKey(tokenValue);

        final AccessToken accessToken = tokenRepository.findOne(tokenId);
        token = accessToken == null ? null : accessToken.token();
    } catch (IllegalArgumentException e) {
        LOG.warn("Failed to deserialize access token for {}", tokenValue);
        removeAccessToken(tokenValue);
    }

    return token;
}
 
Example #17
Source File: AccessParameterClientTokenServices.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@Override
public void saveAccessToken(
        OAuth2ProtectedResourceDetails resource,
        Authentication authentication, OAuth2AccessToken accessToken) {

    String username = authentication.getPrincipal().toString();
    String shimKey = authentication.getDetails().toString();

    AccessParameters accessParameters =
            accessParametersRepo.findByUsernameAndShimKey(
                    username,
                    shimKey,
                    new Sort(Sort.Direction.DESC, "dateCreated"));

    if (accessParameters == null) {
        accessParameters = new AccessParameters();
        accessParameters.setUsername(username);
        accessParameters.setShimKey(shimKey);
    }

    accessParameters.setSerializedToken(SerializationUtils.serialize(accessToken));

    accessParametersRepo.save(accessParameters);
}
 
Example #18
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 #19
Source File: LogoutController.java    From java-starthere with MIT License 6 votes vote down vote up
@RequestMapping(value = {"/oauth/revoke-token", "/logout"},
                method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public void logout(HttpServletRequest request)
{
    logger.trace(request.getMethod()
                        .toUpperCase() + " " + request.getRequestURI() + " accessed");

    String authHeader = request.getHeader("Authorization");
    if (authHeader != null)
    {
        String tokenValue = authHeader.replace("Bearer",
                                               "")
                                      .trim();
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
        tokenStore.removeAccessToken(accessToken);
    }
}
 
Example #20
Source File: MongoClientTokenServicesTest.java    From spring-security-mongo with MIT License 6 votes vote down vote up
@Test
public void shouldGetAccessToken() {
    //Given
    final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build();
    final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next());

    //And
    final String authenticationId = string().next();
    given(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).willReturn(authenticationId);

    //And
    final OAuth2AccessToken expectedToken = oAuth2AccessTokenBuilder().build();
    given(mongoOAuth2ClientTokenRepository.findByAuthenticationId(authenticationId)).willReturn(mongoOAuth2ClientTokenBuilder().token(expectedToken).build());

    //When
    final OAuth2AccessToken accessToken = mongoClientTokenServices.getAccessToken(oAuth2ProtectedResourceDetails, authentication);

    //Then
    assertThat(accessToken).isEqualTo(expectedToken);
}
 
Example #21
Source File: MongoTokenStoreTest.java    From spring-security-mongo with MIT License 6 votes vote down vote up
@Test
public void shouldFindTokensByClientIdAndUserName() {
    //Given
    final String username = string().next();
    final String clientId = string().next();

    //And
    final List<MongoOAuth2AccessToken> expectedTokens = list(ofMongoOAuth2AccessToken()).next();
    given(mongoOAuth2AccessTokenRepository.findByUsernameAndClientId(username, clientId)).willReturn(expectedTokens);

    //When
    final Collection<OAuth2AccessToken> tokens = mongoTokenStore.findTokensByClientIdAndUserName(clientId, username);

    //Then
    assertThat(tokens).hasSize(expectedTokens.size());
}
 
Example #22
Source File: SocialLoginServiceImpl.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessToken getOauth2AccessToken(SystemUser user) throws FebsException {
    final HttpServletRequest httpServletRequest = FebsUtil.getHttpServletRequest();
    httpServletRequest.setAttribute(ParamsConstant.LOGIN_TYPE, SocialConstant.SOCIAL_LOGIN);
    String socialLoginClientId = properties.getSocialLoginClientId();
    ClientDetails clientDetails = null;
    try {
        clientDetails = redisClientDetailsService.loadClientByClientId(socialLoginClientId);
    } catch (Exception e) {
        throw new FebsException("获取第三方登录可用的Client失败");
    }
    if (clientDetails == null) {
        throw new FebsException("未找到第三方登录可用的Client");
    }
    Map<String, String> requestParameters = new HashMap<>(5);
    requestParameters.put(ParamsConstant.GRANT_TYPE, GrantTypeConstant.PASSWORD);
    requestParameters.put(USERNAME, user.getUsername());
    requestParameters.put(PASSWORD, SocialConstant.SOCIAL_LOGIN_PASSWORD);

    String grantTypes = String.join(StringConstant.COMMA, clientDetails.getAuthorizedGrantTypes());
    TokenRequest tokenRequest = new TokenRequest(requestParameters, clientDetails.getClientId(), clientDetails.getScope(), grantTypes);
    return granter.grant(GrantTypeConstant.PASSWORD, tokenRequest);
}
 
Example #23
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private OAuth2AccessToken obtainAccessToken(String username, String password, boolean remove) throws Exception {
    OAuth2AccessToken oauthToken = null;
    try {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "password");
        params.add("username", username);
        params.add("password", password);
        String hash = new String(Base64.encode("test1_consumer:secret".getBytes()));
        ResultActions result
                = mockMvc.perform(post("/oauth/token")
                        .params(params)
                        .header("Authorization", "Basic " + hash)
                        .accept("application/json;charset=UTF-8"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"));
        String resultString = result.andReturn().getResponse().getContentAsString();
        System.out.println(resultString);
        Assert.assertTrue(StringUtils.isNotBlank(resultString));
        String token = JsonPath.parse(resultString).read("$.access_token");
        Assert.assertTrue(StringUtils.isNotBlank(token));
        Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
        Assert.assertEquals(1, oauthTokens.size());
        oauthToken = oauthTokens.stream().findFirst().get();
        Assert.assertEquals(token, oauthToken.getValue());
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != oauthToken && remove) {
            this.apiOAuth2TokenManager.removeAccessToken(oauthToken);
        }
    }
    return oauthToken;
}
 
Example #24
Source File: MongoTokenStore.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
    LOG.debug("Call findTokensByUserName, clientId = {}, username = {}", clientId, userName);
    List<OAuth2AccessToken> accessTokens = new ArrayList<>();

    List<AccessToken> tokenList = tokenRepository.findAccessTokensByClientIdAndUsername(clientId, userName);
    for (AccessToken token : tokenList) {
        final OAuth2AccessToken accessToken = token.token();
        if (accessToken != null) {
            accessTokens.add(accessToken);
        }
    }

    return accessTokens;
}
 
Example #25
Source File: OpenApiTokenEnhancer.java    From spring-oauth2-jwt-jdbc with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    JwtAuthenticatedProfile user = (JwtAuthenticatedProfile) authentication.getPrincipal();
    final Map<String, Object> additionalInfo = new HashMap<>();

    additionalInfo.put("id_token", UUID.randomUUID().toString());

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

    return accessToken;
}
 
Example #26
Source File: YamiTokenServices.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #27
Source File: OAuth2FeignRequestInterceptorTests.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Test(expected = OAuth2AccessDeniedException.class)
public void tryToAcquireToken() {
	oAuth2FeignRequestInterceptor = new OAuth2FeignRequestInterceptor(
			new DefaultOAuth2ClientContext(),
			new BaseOAuth2ProtectedResourceDetails());
	OAuth2AccessToken oAuth2AccessToken = oAuth2FeignRequestInterceptor.getToken();
	Assert.assertTrue(oAuth2AccessToken.getValue() + " Must be null",
			oAuth2AccessToken.getValue() == null);
}
 
Example #28
Source File: CustomTokenEnhancer.java    From JetfireCloud with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    Map<String, Object> additionalInfo = Maps.newHashMap();
    //自定义token内容,加入组织机构信息
    additionalInfo.put("organization", authentication.getName());
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example #29
Source File: CustomJwtAccessTokenConverter.java    From spring-security with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #30
Source File: CustomTokenEnhancer.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
@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;
}