Search in sources :

Example 6 with InvalidGrantException

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);
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Date(java.util.Date) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) Transactional(org.springframework.transaction.annotation.Transactional)

Example 7 with InvalidGrantException

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);
}
Also used : AccountStatusException(org.springframework.security.authentication.AccountStatusException) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) LinkedHashMap(java.util.LinkedHashMap)

Example 8 with InvalidGrantException

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
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Test(org.junit.Test)

Example 9 with InvalidGrantException

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>"));
}
Also used : ModelAndView(org.springframework.web.servlet.ModelAndView) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Test(org.junit.Test)

Example 10 with InvalidGrantException

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());
}
Also used : OAuth2AccessTokenResult(com.haulmont.restapi.auth.OAuthTokenIssuer.OAuth2AccessTokenResult) Authentication(org.springframework.security.core.Authentication) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException)

Aggregations

InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)14 Authentication (org.springframework.security.core.Authentication)10 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)7 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)4 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)4 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)4 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)3 InvalidRequestException (org.springframework.security.oauth2.common.exceptions.InvalidRequestException)3 Transactional (org.springframework.transaction.annotation.Transactional)3 OAuth2AccessTokenResult (com.haulmont.restapi.auth.OAuthTokenIssuer.OAuth2AccessTokenResult)2 Date (java.util.Date)2 HashSet (java.util.HashSet)2 Test (org.junit.Test)2 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)2 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)2 RedirectMismatchException (org.springframework.security.oauth2.common.exceptions.RedirectMismatchException)2 SecurityContext (com.haulmont.cuba.core.sys.SecurityContext)1 LoginPasswordCredentials (com.haulmont.cuba.security.auth.LoginPasswordCredentials)1