Example usage for org.springframework.security.oauth2.common.exceptions InvalidGrantException InvalidGrantException

List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidGrantException InvalidGrantException

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions InvalidGrantException InvalidGrantException.

Prototype

public InvalidGrantException(String msg) 

Source Link

Usage

From source file:eu.trentorise.smartcampus.permissionprovider.oauth.NonRemovingTokenServices.java

private OAuth2AccessToken refreshWithRepeat(String refreshTokenValue, AuthorizationRequest request,
        boolean repeat) {
    OAuth2AccessToken accessToken = localtokenStore.readAccessTokenForRefreshToken(refreshTokenValue);
    if (accessToken == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }/*ww w. j ava  2 s  . c om*/

    if (accessToken.getExpiration().getTime() - System.currentTimeMillis() > tokenThreshold * 1000L) {
        return accessToken;
    }

    try {
        OAuth2AccessToken res = super.refreshAccessToken(refreshTokenValue, request);
        OAuth2Authentication auth = localtokenStore.readAuthentication(res);
        traceUserLogger.info(
                String.format("'type':'refresh','user':'%s','token':'%s'", auth.getName(), res.getValue()));
        return res;
    } catch (RuntimeException e) {
        // do retry: it may be the case of race condition so retry the operation but only once
        if (!repeat)
            return refreshWithRepeat(refreshTokenValue, request, true);
        throw e;
    }
}

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java

@Override
public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken t = jp.getCurrentToken();/* www.  j a va2s .c  om*/
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        }
        // Some servers might send back complex content
        else if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }

    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description")
            ? errorParams.get("error_description").toString()
            : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }

    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedUserException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage,
                OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else {
        ex = new OAuth2Exception(errorMessage);
    }

    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }

    return ex;

}

From source file:com.haulmont.restapi.auth.CubaUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    String ipAddress = request.getRemoteAddr();

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug(/*  ww w.  j  a va  2 s  .c  o m*/
                    "Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");

            throw new InvalidGrantException("Authentication disabled");
        }

        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

        String login = (String) token.getPrincipal();

        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());

            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));

            //if the locale value is explicitly passed in the Accept-Language header then set its value to the
            //credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } catch (RestApiAccessDeniedException ex) {
            log.info("User is not allowed to use the REST API {}", login);
            throw new BadCredentialsException("User is not allowed to use the REST API");
        } catch (LoginException e) {
            log.info("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }

        AppContext.setSecurityContext(new SecurityContext(session));

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(),
                getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked")
        Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }

    return null;
}

From source file:it.smartcommunitylab.aac.oauth.NonRemovingTokenServices.java

private OAuth2AccessToken refreshWithRepeat(String refreshTokenValue, TokenRequest request, boolean repeat) {
    OAuth2AccessToken accessToken = localtokenStore.readAccessTokenForRefreshToken(refreshTokenValue);
    if (accessToken == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }/*from   ww w  . ja v  a 2s .  c  om*/

    if (accessToken.getExpiration().getTime() - System.currentTimeMillis() > tokenThreshold * 1000L) {
        return accessToken;
    }

    try {
        OAuth2AccessToken res = super.refreshAccessToken(refreshTokenValue, request);
        OAuth2Authentication auth = localtokenStore.readAuthentication(res);
        traceUserLogger.info(
                String.format("'type':'refresh','user':'%s','token':'%s'", auth.getName(), res.getValue()));
        return res;
    } catch (RuntimeException e) {
        // do retry: it may be the case of race condition so retry the operation but only once
        if (!repeat)
            return refreshWithRepeat(refreshTokenValue, request, true);
        throw e;
    }
}

From source file:org.mitre.oauth2.service.impl.DefaultOAuth2AuthorizationCodeService.java

/**
 * Consume a given authorization code.//  w  w w.  j  a va2s  .c  o m
 * Match the provided string to an AuthorizationCodeEntity. If one is found, return
 * the authentication associated with the code. If one is not found, throw an
 * InvalidGrantException.
 * 
 * @param code      the authorization code
 * @return         the authentication that made the original request
 * @throws          InvalidGrantException, if an AuthorizationCodeEntity is not found with the given value
 */
@Override
public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException {

    AuthorizationCodeEntity result = repository.getByCode(code);

    if (result == null) {
        throw new InvalidGrantException(
                "JpaAuthorizationCodeRepository: no authorization code found for value " + code);
    }

    OAuth2Authentication auth = result.getAuthenticationHolder().getAuthentication();

    repository.remove(result);

    return auth;
}

From source file:com.haulmont.restapi.ldap.LdapAuthController.java

@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");
    }//from w  ww .  j  av a 2 s .co  m

    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());
}

From source file:com.monkeyk.sos.web.controller.OAuthRestController.java

@RequestMapping(value = "/oauth2/rest_token", method = RequestMethod.POST)
@ResponseBody/*from   ww  w  .j  a  va2  s.  c o  m*/
public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) {

    String clientId = getClientId(parameters);
    ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

    TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);

    if (clientId != null && !"".equals(clientId)) {
        // Only validate the client details if a client authenticated during this
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // double check to make sure that the client ID in the token request is the same as that in the
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }

    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }

    final String grantType = tokenRequest.getGrantType();
    if (!StringUtils.hasText(grantType)) {
        throw new InvalidRequestException("Missing grant type");
    }
    if ("implicit".equals(grantType)) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }

    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            LOG.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }

    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }

    OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType);
    }

    return token;

}

From source file:com.hundsun.sso.controller.OAuthRestController.java

@RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST)
@ResponseBody//from  w  ww  . ja v  a 2 s . co  m
public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) {

    String clientId = getClientId(parameters);
    ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

    TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);

    if (clientId != null && !"".equals(clientId)) {
        // Only validate the client details if a client authenticated during this
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // double check to make sure that the client ID in the token request is the same as that in the
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }

    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }

    final String grantType = tokenRequest.getGrantType();
    if (!StringUtils.hasText(grantType)) {
        throw new InvalidRequestException("Missing grant type");
    }
    if ("implicit".equals(grantType)) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }

    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            LOG.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }

    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }

    OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType);
    }

    return token;

}

From source file:eu.trentorise.smartcampus.permissionprovider.oauth.ClientCredentialsFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    String clientId = request.getParameter("client_id");
    String clientSecret = request.getParameter("client_secret");

    // If the request is already authenticated we can assume that this filter is not needed
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        return authentication;
    }/* www .ja v  a2 s. c o  m*/

    if (clientId == null) {
        throw new BadCredentialsException("No client credentials presented");
    }

    if (clientSecret == null) {
        clientSecret = "";
    }

    clientId = clientId.trim();

    //      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
    ClientDetailsEntity clientDetails = clientDetailsRepository.findByClientId(clientId);
    boolean isTrusted = false;
    if (clientDetails.getAuthorities() != null) {
        for (GrantedAuthority ga : clientDetails.getAuthorities())
            if (Config.AUTHORITY.ROLE_CLIENT_TRUSTED.toString().equals(ga.getAuthority())) {
                isTrusted = true;
                break;
            }
    }
    if (!isTrusted) {
        throw new InvalidGrantException("Unauthorized client access by client " + clientId);
    }

    String clientSecretServer = clientDetails.getClientSecret();
    ClientAppInfo info = ClientAppInfo.convert(clientDetails.getAdditionalInformation());
    String clientSecretMobile = clientDetails.getClientSecretMobile();
    if (clientSecretMobile.equals(clientSecret) && !info.isNativeAppsAccess()) {
        throw new InvalidGrantException("Native app access is not enabled");
    }

    if (!clientSecretServer.equals(clientSecret) && !clientSecretMobile.equals(clientSecret)) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    User user = new User(clientId, clientSecret, clientDetails.getAuthorities());

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user,
            clientSecretServer, user.getAuthorities());
    //        result.setDetails(authRequest.getDetails());
    return result;
}

From source file:com.haulmont.restapi.idp.IdpAuthController.java

@PostMapping(value = "/v2/idp/token")
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
        @RequestParam Map<String, String> parameters, HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }// w  w w .  j ava2 s  . c o  m

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    // we cannot perform brute-force check here, since we don't know username

    String idpTicket = parameters.get("idp_ticket");
    String ipAddress = request.getRemoteAddr();

    OAuth2AccessTokenResult tokenResult = authenticate(idpTicket, request.getLocale(), ipAddress, parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}