use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project ORCID-Source by ORCID.
the class OrcidRandomValueTokenServicesImpl method refreshAccessToken.
@Override
@Transactional
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
String parentTokenValue = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.AUTHORIZATION);
String clientId = tokenRequest.getClientId();
String scopes = tokenRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
Long expiresIn = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.EXPIRES_IN) ? Long.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.EXPIRES_IN)) : 0L;
Boolean revokeOld = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.REVOKE_OLD) ? Boolean.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.REVOKE_OLD)) : true;
// Check if the refresh token is enabled
if (!customSupportRefreshToken) {
throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
}
// Check if the client support refresh token
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
if (!clientDetails.getAuthorizedGrantTypes().contains(OrcidOauth2Constants.REFRESH_TOKEN)) {
throw new InvalidGrantException("Client " + clientId + " doesnt have refresh token enabled");
}
OrcidOauth2TokenDetail parentToken = orcidOauth2TokenDetailDao.findByRefreshTokenValue(refreshTokenValue);
ProfileEntity profileEntity = new ProfileEntity(parentToken.getProfile().getId());
OrcidOauth2TokenDetail newToken = new OrcidOauth2TokenDetail();
newToken.setApproved(true);
newToken.setClientDetailsId(clientId);
newToken.setDateCreated(new Date());
newToken.setLastModified(new Date());
newToken.setPersistent(parentToken.isPersistent());
newToken.setProfile(profileEntity);
newToken.setRedirectUri(parentToken.getRedirectUri());
newToken.setRefreshTokenValue(UUID.randomUUID().toString());
newToken.setResourceId(parentToken.getResourceId());
newToken.setResponseType(parentToken.getResponseType());
newToken.setState(parentToken.getState());
newToken.setTokenDisabled(false);
if (expiresIn <= 0) {
// If expiresIn is 0 or less, set the parent token
newToken.setTokenExpiration(parentToken.getTokenExpiration());
} else {
// Assumes expireIn already contains the real expired time expressed in millis
newToken.setTokenExpiration(new Date(expiresIn));
}
newToken.setTokenType(parentToken.getTokenType());
newToken.setTokenValue(UUID.randomUUID().toString());
newToken.setVersion(parentToken.getVersion());
if (PojoUtil.isEmpty(scopes)) {
newToken.setScope(parentToken.getScope());
} else {
newToken.setScope(scopes);
}
// Generate an authentication object to be able to generate the authentication key
Set<String> scopesSet = OAuth2Utils.parseParameterList(newToken.getScope());
AuthorizationRequest request = new AuthorizationRequest(clientId, scopesSet);
request.setApproved(true);
Authentication authentication = new OrcidOauth2UserAuthentication(profileEntity, true);
OrcidOAuth2Authentication orcidAuthentication = new OrcidOAuth2Authentication(request, authentication, newToken.getTokenValue());
newToken.setAuthenticationKey(authenticationKeyGenerator.extractKey(orcidAuthentication));
// Store the new token and return it
orcidOauth2TokenDetailDao.persist(newToken);
// Revoke the old token when required
if (revokeOld) {
orcidOauth2TokenDetailDao.disableAccessToken(parentTokenValue);
}
// Save the changes
orcidOauth2TokenDetailDao.flush();
// and return it
return toOAuth2AccessToken(newToken);
}
use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException 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.common.exceptions.InvalidGrantException in project spring-security-oauth by spring-projects.
the class AuthorizationCodeServicesBaseTests method testConsumeRemovesCode.
@Test
public void testConsumeRemovesCode() {
OAuth2Request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", false);
OAuth2Authentication expectedAuthentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test2", false));
String code = getAuthorizationCodeServices().createAuthorizationCode(expectedAuthentication);
assertNotNull(code);
OAuth2Authentication actualAuthentication = getAuthorizationCodeServices().consumeAuthorizationCode(code);
assertEquals(expectedAuthentication, actualAuthentication);
try {
getAuthorizationCodeServices().consumeAuthorizationCode(code);
fail("Should have thrown exception");
} catch (InvalidGrantException e) {
// good we expected this
}
}
use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project spring-security-oauth by spring-projects.
the class WhitelabelErrorEndpointTests method testErrorPageXSS.
@Test
public void testErrorPageXSS() throws Exception {
request.setAttribute("error", new InvalidGrantException("Invalid grant : <script>alert('XSS');</script>"));
ModelAndView result = endpoint.handleError(request);
result.getView().render(result.getModel(), request, response);
String content = response.getContentAsString();
assertFalse("Wrong content : " + content, content.contains("<script>"));
}
use of org.springframework.security.oauth2.common.exceptions.InvalidGrantException in project cuba by cuba-platform.
the class LdapAuthController method postAccessToken.
@RequestMapping(value = "/v2/ldap/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters, HttpServletRequest request) throws HttpRequestMethodNotSupportedException {
if (!ldapConfig.getLdapEnabled()) {
log.debug("LDAP authentication is disabled. Property cuba.rest.ldap.enabled is false");
throw new InvalidGrantException("LDAP is not supported");
}
if (!(principal instanceof Authentication)) {
throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter.");
}
String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
if (!"password".equals(grantType)) {
throw new InvalidGrantException("grant type not supported for ldap/token endpoint");
}
String username = parameters.get("username");
if (restApiConfig.getStandardAuthenticationUsers().contains(username)) {
log.info("User {} is not allowed to use external login in REST API", username);
throw new BadCredentialsException("Bad credentials");
}
String ipAddress = request.getRemoteAddr();
String password = parameters.get("password");
OAuth2AccessTokenResult tokenResult = authenticate(username, password, request.getLocale(), ipAddress, parameters);
return ResponseEntity.ok(tokenResult.getAccessToken());
}
Aggregations