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

The following examples show how to use org.springframework.security.oauth2.common.OAuth2AccessToken. 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: osiam   Source File: TokenService.java    License: MIT License 6 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
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 3
Source Project: auth-server   Source File: TokenServiceImpl.java    License: 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 4
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 5
Source Project: FEBS-Cloud   Source File: SocialLoginServiceImpl.java    License: 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 6
Source Project: spring-security-mongo   Source File: MongoTokenStoreTest.java    License: 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 7
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 8
@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 9
Source Project: konker-platform   Source File: MongoTokenStore.java    License: 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 10
Source Project: fast-family-master   Source File: CustomJwtTokenEnhancer.java    License: 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 11
Source Project: cubeai   Source File: AuthResource.java    License: 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 12
Source Project: OAuth-2.0-Cookbook   Source File: UserInfoService.java    License: 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 13
@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 14
@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 15
Source Project: NFVO   Source File: OAuth2AuthorizationServerConfig.java    License: 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 16
@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 17
Source Project: java-starthere   Source File: LogoutController.java    License: 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 18
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 19
Source Project: konker-platform   Source File: MongoTokenStore.java    License: 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 20
/**
 * 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 21
Source Project: pig   Source File: PigRedisTokenStore.java    License: 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 22
@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 23
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException, OAuth2AccessDeniedException {
    MultiValueMap<String, String> form = new LinkedMultiValueMap();
    form.add("grant_type", "refresh_token");
    form.add("refresh_token", refreshToken.getValue());
    form.add("appid", resource.getClientId());

    try {
        return this.retrieveToken(request, resource, form, this.getHeadersForTokenRequest(request));
    } catch (OAuth2AccessDeniedException var6) {
        throw this.getRedirectForAuthorization((AuthorizationCodeResourceDetails)resource, request);
    }
}
 
Example 24
Source Project: spring-cloud-gray   Source File: Oauth2Service.java    License: Apache License 2.0 5 votes vote down vote up
private OAuth2AccessToken createAccessToken(Oauth2TokenRequest oauth2TokenRequest, TokenGranter tokenGranter) {
    ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(oauth2TokenRequest.getClientId());
    TokenRequest tokenRequest = requestFactory.createTokenRequest(oauth2TokenRequest.getParameters(), authenticatedClient);

    tokenRequest = new UserTokenRequest(tokenRequest,
            oauth2TokenRequest.getTokenRequestInfo().getUserDetails(),
            (Map) oauth2TokenRequest.getTokenRequestInfo().getExtensionProperties());
    return tokenGranter.grant(tokenRequest.getGrantType(), tokenRequest);
}
 
Example 25
Source Project: cubeai   Source File: OAuth2AuthenticationServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
private void mockPasswordGrant(OAuth2AccessToken accessToken) {
    HttpHeaders reqHeaders = new HttpHeaders();
    reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    reqHeaders.add("Authorization", CLIENT_AUTHORIZATION);                //take over Authorization header from client request to UAA request
    MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>();
    formParams.set("username", "user");
    formParams.set("password", "user");
    formParams.add("grant_type", "password");
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formParams, reqHeaders);
    when(restTemplate.postForEntity("http://uaa/oauth/token", entity, OAuth2AccessToken.class))
        .thenReturn(new ResponseEntity<OAuth2AccessToken>(accessToken, HttpStatus.OK));
}
 
Example 26
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    final Map<String, Object> additionalInfo = new HashMap<>(8);
    YamiSysUser yamiSysUser = (YamiSysUser) authentication.getUserAuthentication().getPrincipal();
    additionalInfo.put("shopId", yamiSysUser.getShopId());
    additionalInfo.put("userId", yamiSysUser.getUserId());
    additionalInfo.put("authorities", yamiSysUser.getAuthorities());
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example 27
Source Project: auth-server   Source File: TokenServiceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGivenUsernameWhenRevokingTokensThenRevokeAllTokens() {
  // mock access token
  given(accessToken.getRefreshToken()).willReturn(refreshToken);

  List<OAuth2AccessToken> tokens = new ArrayList<>();
  tokens.add(accessToken);

  given(tokenStore.findTokensByUserName(eq("[email protected]"))).willReturn(tokens);

  tokenService.revokeTokens("[email protected]");

  verify(tokenStore).removeAccessToken(accessToken);
  verify(tokenStore).removeRefreshToken(refreshToken);
}
 
Example 28
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
	List<Object> result =    redisTemplate.opsForList().range(UNAME_TO_ACCESS+ getApprovalKey(clientId, userName), 0, -1);
	
	if (result == null || result.size() == 0) {
		return Collections.<OAuth2AccessToken> emptySet();
	}
	List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size());
	
	for(Iterator<Object> it = result.iterator();it.hasNext();){
		OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
		accessTokens.add(accessToken);
	}
	
	return Collections.<OAuth2AccessToken> unmodifiableCollection(accessTokens); 
}
 
Example 29
Source Project: pacbot   Source File: ApiService.java    License: Apache License 2.0 5 votes vote down vote up
public void logout(Principal principal) {
	 JdbcTokenStore jdbcTokenStore = tokenStore();
	 OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
	 OAuth2AccessToken accessToken = jdbcTokenStore.getAccessToken(oAuth2Authentication);
	 jdbcTokenStore.removeAccessToken(accessToken.getValue());
	 jdbcTokenStore.removeRefreshToken(accessToken.getRefreshToken());
}
 
Example 30
Source Project: NFVO   Source File: GsonSerializerOAuth2AccessToken.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement serialize(
    OAuth2AccessToken src, Type typeOfSrc, JsonSerializationContext context) {
  JsonObject jsonObject = new JsonObject();
  jsonObject.addProperty(OAuth2AccessToken.ACCESS_TOKEN, src.getValue());
  // back compatibility for dashboard
  jsonObject.addProperty("value", src.getValue());

  jsonObject.addProperty(OAuth2AccessToken.TOKEN_TYPE, src.getTokenType());

  OAuth2RefreshToken refreshToken = src.getRefreshToken();
  if (refreshToken != null) {
    jsonObject.addProperty(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue());
  }
  Date expiration = src.getExpiration();
  if (expiration != null) {
    long now = System.currentTimeMillis();
    jsonObject.add(
        OAuth2AccessToken.EXPIRES_IN, new JsonPrimitive((expiration.getTime() - now) / 1000));
  }

  Set<String> scope = src.getScope();

  if (scope != null && !scope.isEmpty()) {
    StringBuilder scopes = new StringBuilder();
    for (String s : scope) {
      Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + "");
      scopes.append(s);
      scopes.append(" ");
    }

    jsonObject.addProperty(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1));
  }

  return jsonObject;
}