use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.
the class DefaultTokenServices method refreshAccessToken.
@Transactional(noRollbackFor = { InvalidTokenException.class, InvalidGrantException.class })
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
if (!supportRefreshToken) {
throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
}
OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
if (refreshToken == null) {
throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
}
OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
if (this.authenticationManager != null && !authentication.isClientOnly()) {
// The client has already been authenticated, but the user authentication might be old now, so give it a
// chance to re-authenticate.
Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities());
user = authenticationManager.authenticate(user);
Object details = authentication.getDetails();
authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
authentication.setDetails(details);
}
String clientId = authentication.getOAuth2Request().getClientId();
if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
}
// clear out any access tokens already associated with the refresh
// token.
tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
if (isExpired(refreshToken)) {
tokenStore.removeRefreshToken(refreshToken);
throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
}
authentication = createRefreshedAuthentication(authentication, tokenRequest);
if (!reuseRefreshToken) {
tokenStore.removeRefreshToken(refreshToken);
refreshToken = createRefreshToken(authentication);
}
OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
tokenStore.storeAccessToken(accessToken, authentication);
if (!reuseRefreshToken) {
tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
}
return accessToken;
}
use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.
the class ImplicitTokenGranter method getOAuth2Authentication.
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) {
Authentication userAuth = SecurityContextHolder.getContext().getAuthentication();
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InsufficientAuthenticationException("There is no currently logged in user");
}
Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest.");
OAuth2Request requestForStorage = ((ImplicitTokenRequest) clientToken).getOAuth2Request();
return new OAuth2Authentication(requestForStorage, userAuth);
}
use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.
the class ResourceOwnerPasswordTokenGranter method getOAuth2Authentication.
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
String username = parameters.get("username");
String password = parameters.get("password");
// Protect from downstream leaks of password
parameters.remove("password");
Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
((AbstractAuthenticationToken) userAuth).setDetails(parameters);
try {
userAuth = authenticationManager.authenticate(userAuth);
} catch (AccountStatusException ase) {
//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
throw new InvalidGrantException(ase.getMessage());
} catch (BadCredentialsException e) {
// If the username/password are wrong the spec says we should send 400/invalid grant
throw new InvalidGrantException(e.getMessage());
}
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate user: " + username);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
use of org.springframework.security.oauth2.provider.TokenRequest in project ORCID-Source by ORCID.
the class OrcidRefreshTokenChecker method validateRequest.
public void validateRequest(String grantType, TokenRequest tokenRequest, Long requestTimeInMillis) {
String authorization = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.AUTHORIZATION);
String clientId = tokenRequest.getClientId();
String scopes = tokenRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
Long expireIn = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.EXPIRES_IN) ? Long.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.EXPIRES_IN)) : 0L;
String refreshToken = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.REFRESH_TOKEN);
OrcidOauth2TokenDetail token = orcidOauth2TokenDetailDao.findByTokenValue(authorization);
// Verify the token belongs to this client
if (!clientId.equals(token.getClientDetailsId())) {
throw new IllegalArgumentException("This token doesnt belong to the given client");
}
// Verify client is enabled
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
// Verify the token is not expired
if (token.getTokenExpiration() != null) {
if (token.getTokenExpiration().before(new Date())) {
throw new InvalidTokenException("Access token expired: " + authorization);
}
}
// Verify access token and refresh token are linked
if (!refreshToken.equals(token.getRefreshTokenValue())) {
throw new InvalidTokenException("Token and refresh token does not match");
}
// Verify the token is not disabled
if (token.getTokenDisabled() != null && token.getTokenDisabled()) {
throw new InvalidTokenException("Parent token is disabled");
}
// Verify scopes are not wider than the token scopes
if (PojoUtil.isEmpty(scopes)) {
scopes = token.getScope();
} else {
Set<ScopePathType> requiredScopes = ScopePathType.getScopesFromSpaceSeparatedString(scopes);
Set<ScopePathType> simpleTokenScopes = ScopePathType.getScopesFromSpaceSeparatedString(token.getScope());
// This collection contains all tokens that should be allowed given
// the scopes that the parent token contains
Set<ScopePathType> combinedTokenScopes = new HashSet<ScopePathType>();
for (ScopePathType scope : simpleTokenScopes) {
combinedTokenScopes.addAll(scope.combined());
}
// combinedTokenScopes
for (ScopePathType scope : requiredScopes) {
if (!combinedTokenScopes.contains(scope)) {
throw new InvalidScopeException("The given scope '" + scope.value() + "' is not allowed for the parent token");
}
}
}
// Validate the expiration for the new token is no later than the parent
// token expiration.
long parentTokenExpiration = token.getTokenExpiration() == null ? System.currentTimeMillis() : token.getTokenExpiration().getTime();
if (expireIn > parentTokenExpiration) {
throw new IllegalArgumentException("Token expiration can't be after " + token.getTokenExpiration());
}
}
use of org.springframework.security.oauth2.provider.TokenRequest in project ORCID-Source by ORCID.
the class OrcidClientCredentialEndPointDelegatorImpl method generateToken.
protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code, String redirectUri, String grantType, String refreshToken, String state, String authorization, boolean revokeOld, Long expiresIn) {
String clientId = client.getName();
Map<String, String> authorizationParameters = new HashMap<String, String>();
if (scopes != null) {
String scopesString = StringUtils.join(scopes, ' ');
authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
}
authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
if (code != null) {
authorizationParameters.put("code", code);
OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao.find(code);
if (authorizationCodeEntity != null) {
if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
} else {
authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
}
if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE) || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
}
//This will pass through to the token generator as a request param.
if (authorizationCodeEntity.getNonce() != null) {
authorizationParameters.put(OrcidOauth2Constants.NONCE, authorizationCodeEntity.getNonce());
}
} else {
authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
}
}
//If it is a refresh token request, set the needed authorization parameters
if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
authorizationParameters.put(OrcidOauth2Constants.AUTHORIZATION, authorization);
authorizationParameters.put(OrcidOauth2Constants.REVOKE_OLD, String.valueOf(revokeOld));
authorizationParameters.put(OrcidOauth2Constants.EXPIRES_IN, String.valueOf(expiresIn));
authorizationParameters.put(OrcidOauth2Constants.REFRESH_TOKEN, String.valueOf(refreshToken));
}
if (redirectUri != null) {
authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
}
AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(authorizationParameters);
TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);
//Need to change this to either the DefaultTokenType or start using a different token type.
OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
Object[] params = { grantType };
if (token == null) {
LOGGER.info("Unsupported grant type for OAuth2: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri });
throw new UnsupportedGrantTypeException(localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
}
LOGGER.info("OAuth2 access token granted: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}, token={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri, token });
return token;
}
Aggregations