List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidClientException InvalidClientException
public InvalidClientException(String msg)
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();/*ww w .j a va 2 s .c o m*/ 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:org.mitre.oauth2.token.JWTAssertionTokenGranter.java
@Override protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException { // read and load up the existing token String incomingTokenValue = tokenRequest.getRequestParameters().get("assertion"); OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue); if (incomingToken.getScope().contains(SystemScopeService.ID_TOKEN_SCOPE)) { if (!client.getClientId().equals(tokenRequest.getClientId())) { throw new InvalidClientException("Not the right client for this token"); }/*from ww w . j a va 2 s. co m*/ // it's an ID token, process it accordingly try { // TODO: make this use a more specific idtoken class JWT idToken = JWTParser.parse(incomingTokenValue); OAuth2AccessTokenEntity accessToken = tokenServices.getAccessTokenForIdToken(incomingToken); if (accessToken != null) { //OAuth2AccessTokenEntity newIdToken = tokenServices.get OAuth2AccessTokenEntity newIdTokenEntity = new OAuth2AccessTokenEntity(); // copy over all existing claims JWTClaimsSet.Builder claims = new JWTClaimsSet.Builder(idToken.getJWTClaimsSet()); if (client instanceof ClientDetailsEntity) { ClientDetailsEntity clientEntity = (ClientDetailsEntity) client; // update expiration and issued-at claims if (clientEntity.getIdTokenValiditySeconds() != null) { Date expiration = new Date(System.currentTimeMillis() + (clientEntity.getIdTokenValiditySeconds() * 1000L)); claims.expirationTime(expiration); newIdTokenEntity.setExpiration(expiration); } } else { //This should never happen logger.fatal("SEVERE: Client is not an instance of OAuth2AccessTokenEntity."); throw new BadCredentialsException( "SEVERE: Client is not an instance of ClientDetailsEntity; JwtAssertionTokenGranter cannot process this request."); } claims.issueTime(new Date()); claims.jwtID(UUID.randomUUID().toString()); // set a random NONCE in the middle of it SignedJWT newIdToken = new SignedJWT((JWSHeader) idToken.getHeader(), claims.build()); jwtService.signJwt(newIdToken); newIdTokenEntity.setJwt(newIdToken); newIdTokenEntity.setAuthenticationHolder(incomingToken.getAuthenticationHolder()); newIdTokenEntity.setScope(incomingToken.getScope()); newIdTokenEntity.setClient(incomingToken.getClient()); newIdTokenEntity = tokenServices.saveAccessToken(newIdTokenEntity); // attach the ID token to the access token entity accessToken.setIdToken(newIdTokenEntity); accessToken = tokenServices.saveAccessToken(accessToken); // delete the old ID token tokenServices.revokeAccessToken(incomingToken); return newIdTokenEntity; } } catch (ParseException e) { logger.warn("Couldn't parse id token", e); } } // if we got down here, we didn't actually create any tokens, so return null return null; /* * Otherwise, process it like an access token assertion ... which we don't support yet so this is all commented out * / if (jwtService.validateSignature(incomingTokenValue)) { Jwt jwt = Jwt.parse(incomingTokenValue); if (oldToken.getScope().contains("id-token")) { // TODO: things } // TODO: should any of these throw an exception instead of returning null? JwtClaims claims = jwt.getClaims(); if (!config.getIssuer().equals(claims.getIssuer())) { // issuer isn't us return null; } if (!authorizationRequest.getClientId().equals(claims.getAudience())) { // audience isn't the client return null; } Date now = new Date(); if (!now.after(claims.getExpiration())) { // token is expired return null; } // FIXME // This doesn't work. We need to look up the old token, figure out its scopes and bind it appropriately. // In the case of an ID token, we need to look up its parent access token and change the reference, and revoke the old one, and // that's tricky. // we might need new calls on the token services layer to handle this, and we might // need to handle id tokens separately. return new OAuth2Authentication(authorizationRequest, null); } else { return null; // throw error?? } */ }
From source file:org.mitre.openid.connect.assertion.JWTBearerAuthenticationProvider.java
/** * Try to validate the client credentials by parsing and validating the JWT. *//*from w ww .ja v a 2 s. c om*/ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { JWTBearerAssertionAuthenticationToken jwtAuth = (JWTBearerAssertionAuthenticationToken) authentication; try { ClientDetailsEntity client = clientService.loadClientByClientId(jwtAuth.getClientId()); JWT jwt = jwtAuth.getJwt(); JWTClaimsSet jwtClaims = jwt.getJWTClaimsSet(); // check the signature with nimbus if (jwt instanceof SignedJWT) { SignedJWT jws = (SignedJWT) jwt; JWSAlgorithm alg = jws.getHeader().getAlgorithm(); if (client.getTokenEndpointAuthSigningAlg() != null && !client.getTokenEndpointAuthSigningAlg().equals(alg)) { throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")"); } if (client.getTokenEndpointAuthMethod() == null || client.getTokenEndpointAuthMethod().equals(AuthMethod.NONE) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST)) { // this client doesn't support this type of authentication throw new AuthenticationServiceException("Client does not support this authentication method."); } else if ((client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) && (alg.equals(JWSAlgorithm.RS256) || alg.equals(JWSAlgorithm.RS384) || alg.equals(JWSAlgorithm.RS512) || alg.equals(JWSAlgorithm.ES256) || alg.equals(JWSAlgorithm.ES384) || alg.equals(JWSAlgorithm.ES512) || alg.equals(JWSAlgorithm.PS256) || alg.equals(JWSAlgorithm.PS384) || alg.equals(JWSAlgorithm.PS512))) || (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT) && (alg.equals(JWSAlgorithm.HS256) || alg.equals(JWSAlgorithm.HS384) || alg.equals(JWSAlgorithm.HS512)))) { // double-check the method is asymmetrical if we're in HEART mode if (config.isHeartMode() && !client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY)) { throw new AuthenticationServiceException("[HEART mode] Invalid authentication method"); } JWTSigningAndValidationService validator = validators.getValidator(client, alg); if (validator == null) { throw new AuthenticationServiceException("Unable to create signature validator for client " + client + " and algorithm " + alg); } if (!validator.validateSignature(jws)) { throw new AuthenticationServiceException( "Signature did not validate for presented JWT authentication."); } } else { throw new AuthenticationServiceException("Unable to create signature validator for method " + client.getTokenEndpointAuthMethod() + " and algorithm " + alg); } } // check the issuer if (jwtClaims.getIssuer() == null) { throw new AuthenticationServiceException("Assertion Token Issuer is null"); } else if (!jwtClaims.getIssuer().equals(client.getClientId())) { throw new AuthenticationServiceException( "Issuers do not match, expected " + client.getClientId() + " got " + jwtClaims.getIssuer()); } // check expiration if (jwtClaims.getExpirationTime() == null) { throw new AuthenticationServiceException("Assertion Token does not have required expiration claim"); } else { // it's not null, see if it's expired Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000)); if (now.after(jwtClaims.getExpirationTime())) { throw new AuthenticationServiceException( "Assertion Token is expired: " + jwtClaims.getExpirationTime()); } } // check not before if (jwtClaims.getNotBeforeTime() != null) { Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); if (now.before(jwtClaims.getNotBeforeTime())) { throw new AuthenticationServiceException( "Assertion Token not valid untill: " + jwtClaims.getNotBeforeTime()); } } // check issued at if (jwtClaims.getIssueTime() != null) { // since it's not null, see if it was issued in the future Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); if (now.before(jwtClaims.getIssueTime())) { throw new AuthenticationServiceException( "Assertion Token was issued in the future: " + jwtClaims.getIssueTime()); } } // check audience if (jwtClaims.getAudience() == null) { throw new AuthenticationServiceException("Assertion token audience is null"); } else if (!(jwtClaims.getAudience().contains(config.getIssuer()) || jwtClaims.getAudience().contains(config.getIssuer() + "token"))) { throw new AuthenticationServiceException("Audience does not match, expected " + config.getIssuer() + " or " + (config.getIssuer() + "token") + " got " + jwtClaims.getAudience()); } // IFF we managed to get all the way down here, the token is valid // add in the ROLE_CLIENT authority Set<GrantedAuthority> authorities = new HashSet<>(client.getAuthorities()); authorities.add(ROLE_CLIENT); return new JWTBearerAssertionAuthenticationToken(client.getClientId(), jwt, authorities); } catch (InvalidClientException e) { throw new UsernameNotFoundException("Could not find client: " + jwtAuth.getClientId()); } catch (ParseException e) { logger.error("Failure during authentication, error was: ", e); throw new AuthenticationServiceException("Invalid JWT format"); } }
From source file:com.monkeyk.sos.web.controller.OAuthRestController.java
@RequestMapping(value = "/oauth2/rest_token", method = RequestMethod.POST) @ResponseBody//w w w.j a v a 2s .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/* w w w . j ava 2 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:org.cloudfoundry.identity.uaa.oauth.event.ClientAdminEventPublisherTests.java
@Test public void testSecretFailureMissingClient() { Mockito.when(clientDetailsService.loadClientByClientId("foo")) .thenThrow(new InvalidClientException("Not found")); subject.secretFailure("foo", new RuntimeException("planned")); Mockito.verify(publisher).publishEvent(Mockito.isA(SecretFailureEvent.class)); }
From source file:org.mitre.oauth2.web.DeviceEndpoint.java
@RequestMapping(value = "/" + URL, method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public String requestDeviceCode(@RequestParam("client_id") String clientId, @RequestParam(name = "scope", required = false) String scope, Map<String, String> parameters, ModelMap model) {/*from w ww . j a v a 2 s. c om*/ ClientDetailsEntity client; try { client = clientService.loadClientByClientId(clientId); // make sure this client can do the device flow Collection<String> authorizedGrantTypes = client.getAuthorizedGrantTypes(); if (authorizedGrantTypes != null && !authorizedGrantTypes.isEmpty() && !authorizedGrantTypes.contains(DeviceTokenGranter.GRANT_TYPE)) { throw new InvalidClientException("Unauthorized grant type: " + DeviceTokenGranter.GRANT_TYPE); } } catch (IllegalArgumentException e) { logger.error("IllegalArgumentException was thrown when attempting to load client", e); model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } if (client == null) { logger.error("could not find client " + clientId); model.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } // make sure the client is allowed to ask for those scopes Set<String> requestedScopes = OAuth2Utils.parseParameterList(scope); Set<String> allowedScopes = client.getScope(); if (!scopeService.scopesMatch(allowedScopes, requestedScopes)) { // client asked for scopes it can't have logger.error("Client asked for " + requestedScopes + " but is allowed " + allowedScopes); model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); model.put(JsonErrorView.ERROR, "invalid_scope"); return JsonErrorView.VIEWNAME; } // if we got here the request is legit try { DeviceCode dc = deviceCodeService.createNewDeviceCode(requestedScopes, client, parameters); Map<String, Object> response = new HashMap<>(); response.put("device_code", dc.getDeviceCode()); response.put("user_code", dc.getUserCode()); response.put("verification_uri", config.getIssuer() + USER_URL); if (client.getDeviceCodeValiditySeconds() != null) { response.put("expires_in", client.getDeviceCodeValiditySeconds()); } if (config.isAllowCompleteDeviceCodeUri()) { URI verificationUriComplete = new URIBuilder(config.getIssuer() + USER_URL) .addParameter("user_code", dc.getUserCode()).build(); response.put("verification_uri_complete", verificationUriComplete.toString()); } model.put(JsonEntityView.ENTITY, response); return JsonEntityView.VIEWNAME; } catch (DeviceCodeCreationException dcce) { model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); model.put(JsonErrorView.ERROR, dcce.getError()); model.put(JsonErrorView.ERROR_MESSAGE, dcce.getMessage()); return JsonErrorView.VIEWNAME; } catch (URISyntaxException use) { logger.error("unable to build verification_uri_complete due to wrong syntax of uri components"); model.put(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR); return HttpCodeView.VIEWNAME; } }
From source file:org.joyrest.oauth2.endpoint.TokenEndpoint.java
@Override protected void configure() { setControllerPath("oauth"); post("token", (req, resp) -> { Authentication principal = basicAuthenticator.authenticate(req); String clientId = getClientId(principal); ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId); Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams()); TokenRequest tokenRequest = requestFactory.createTokenRequest(parameters, authenticatedClient); // Only validate the client details if a client authenticated during this request. if (!isEmpty(clientId) && !clientId.equals(tokenRequest.getClientId())) { throw new InvalidClientException("Given client ID does not match authenticated client"); }//from w w w . j av a2 s .c om if (nonNull(authenticatedClient)) { requestValidator.validateScope(tokenRequest, authenticatedClient); } if (!isEmpty(tokenRequest.getGrantType())) { throw new InvalidRequestException("Missing grant type"); } if (tokenRequest.getGrantType().equals("implicit")) { throw new InvalidGrantException("Implicit grant type not supported from token endpoint"); } // The scope was requested or determined during the authorization step if (isAuthCodeRequest(parameters) && nonEmpty(tokenRequest.getScope())) { tokenRequest.setScope(emptySet()); } // A refresh token has its own default scopes, so we should ignore any added by the factory here. if (isRefreshTokenRequest(parameters)) { tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE))); } OAuth2AccessToken token = tokenGranter.grant(tokenRequest.getGrantType(), tokenRequest); if (isNull(token)) { throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType()); } createResponse(resp, token); }, Resp(OAuth2AccessToken.class)).produces(JSON); }
From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java
@Override protected void configure() { setControllerPath("oauth"); get("authorize", (req, resp) -> { Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams()); AuthorizationRequest authorizationRequest = requestFactory.createAuthorizationRequest(parameters); Set<String> responseTypes = authorizationRequest.getResponseTypes(); if (!responseTypes.contains("token") && !responseTypes.contains("code")) { throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); }//from w w w.j a v a2s .co m if (isNull(authorizationRequest.getClientId())) { throw new InvalidClientException("A client id must be provided"); } ClientDetails client = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId()); String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); if (isEmpty(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } authorizationRequest.setRedirectUri(resolvedRedirect); requestValidator.validateScope(authorizationRequest, client); authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, null); boolean approved = userApprovalHandler.isApproved(authorizationRequest, null); authorizationRequest.setApproved(approved); if (authorizationRequest.isApproved()) { if (responseTypes.contains("token")) { resp.status(HttpStatus.FOUND); resp.header(HeaderName.LOCATION, getImplicitGrantResponse(authorizationRequest)); } if (responseTypes.contains("code")) { resp.status(HttpStatus.FOUND); resp.header(HeaderName.LOCATION, getAuthorizationCodeResponse(authorizationRequest)); } } }); }
From source file:org.osiam.security.helper.LessStrictRedirectUriAuthorizationCodeTokenGranter.java
private void validateClientId(AuthorizationRequest authorizationRequest, AuthorizationRequest pendingAuthorizationRequest) { String pendingClientId = pendingAuthorizationRequest.getClientId(); String clientId = authorizationRequest.getClientId(); if (clientId != null && !clientId.equals(pendingClientId)) { // just a sanity check. throw new InvalidClientException("Client ID mismatch"); }/* w w w. j av a2s .c om*/ }