List of usage examples for org.springframework.security.oauth2.common.exceptions RedirectMismatchException RedirectMismatchException
public RedirectMismatchException(String msg)
From source file:nl.surfnet.coin.api.oauth.ImplicitGrantExplicitRedirectResolver.java
@Override public String resolveRedirect(String requestedRedirect, ClientDetails client) { Set<String> redirectUris = client.getRegisteredRedirectUri(); boolean implicitGrant = isImplicitGrant(); if ((redirectUris == null || redirectUris.isEmpty()) && implicitGrant) { throw new RedirectMismatchException("A redirect_uri must be configured for implicit grant."); }/*from ww w . j av a 2s. c o m*/ return super.resolveRedirect(requestedRedirect, client); }
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();/*from w ww .java2 s .co 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.uma.web.ClaimsCollectionEndpoint.java
@RequestMapping(method = RequestMethod.GET) public String collectClaims(@RequestParam("client_id") String clientId, @RequestParam(value = "redirect_uri", required = false) String redirectUri, @RequestParam("ticket") String ticketValue, @RequestParam(value = "state", required = false) String state, Model m, OIDCAuthenticationToken auth) { ClientDetailsEntity client = clientService.loadClientByClientId(clientId); PermissionTicket ticket = permissionService.getByTicket(ticketValue); if (client == null || ticket == null) { logger.info("Client or ticket not found: " + clientId + " :: " + ticketValue); m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; }// ww w. ja v a2s .c o m // we've got a client and ticket, let's attach the claims that we have from the token and userinfo // subject Set<Claim> claimsSupplied = Sets.newHashSet(ticket.getClaimsSupplied()); String issuer = auth.getIssuer(); UserInfo userInfo = auth.getUserInfo(); claimsSupplied.add(mkClaim(issuer, "sub", new JsonPrimitive(auth.getSub()))); if (userInfo.getEmail() != null) { claimsSupplied.add(mkClaim(issuer, "email", new JsonPrimitive(userInfo.getEmail()))); } if (userInfo.getEmailVerified() != null) { claimsSupplied.add(mkClaim(issuer, "email_verified", new JsonPrimitive(userInfo.getEmailVerified()))); } if (userInfo.getPhoneNumber() != null) { claimsSupplied .add(mkClaim(issuer, "phone_number", new JsonPrimitive(auth.getUserInfo().getPhoneNumber()))); } if (userInfo.getPhoneNumberVerified() != null) { claimsSupplied.add(mkClaim(issuer, "phone_number_verified", new JsonPrimitive(auth.getUserInfo().getPhoneNumberVerified()))); } if (userInfo.getPreferredUsername() != null) { claimsSupplied.add(mkClaim(issuer, "preferred_username", new JsonPrimitive(auth.getUserInfo().getPreferredUsername()))); } if (userInfo.getProfile() != null) { claimsSupplied.add(mkClaim(issuer, "profile", new JsonPrimitive(auth.getUserInfo().getProfile()))); } ticket.setClaimsSupplied(claimsSupplied); PermissionTicket updatedTicket = permissionService.updateTicket(ticket); if (Strings.isNullOrEmpty(redirectUri)) { if (client.getClaimsRedirectUris().size() == 1) { redirectUri = client.getClaimsRedirectUris().iterator().next(); // get the first (and only) redirect URI to use here logger.info("No redirect URI passed in, using registered value: " + redirectUri); } else { throw new RedirectMismatchException("Unable to find redirect URI and none passed in."); } } else { if (!client.getClaimsRedirectUris().contains(redirectUri)) { throw new RedirectMismatchException("Claims redirect did not match the registered values."); } } UriComponentsBuilder template = UriComponentsBuilder.fromUriString(redirectUri); template.queryParam("authorization_state", "claims_submitted"); if (!Strings.isNullOrEmpty(state)) { template.queryParam("state", state); } String uriString = template.toUriString(); logger.info("Redirecting to " + uriString); return "redirect:" + uriString; }
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 va 2s .c o 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 validateRedirectUri(String redirectUri, AuthorizationRequest pendingAuthorizationRequest) { // https://jira.springsource.org/browse/SECOAUTH-333 // This might be null, if the authorization was done without the redirect_uri parameter String redirectUriApprovalParameter = pendingAuthorizationRequest.getAuthorizationParameters() .get(AuthorizationRequest.REDIRECT_URI); String uri = pendingAuthorizationRequest.getRedirectUri(); if ((redirectUriApprovalParameter != null && redirectUri == null) || (redirectUriApprovalParameter != null && (!uri.startsWith(redirectUri)))) { throw new RedirectMismatchException("Redirect URI mismatch."); }/* w w w .j a v a 2 s .com*/ }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
@RequestMapping(value = "/oauth/authorize") public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal, HttpServletRequest request) { ClientDetails client;/* ww w . j ava 2 s. c om*/ String clientId; try { clientId = parameters.get("client_id"); client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId()); } catch (NoSuchClientException x) { throw new InvalidClientException(x.getMessage()); } // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should // query off of the authorization request instead of referring back to the parameters map. The contents of the // parameters map will be stored without change in the AuthorizationRequest object once it is created. AuthorizationRequest authorizationRequest; try { authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters); } catch (DisallowedIdpException x) { return switchIdp(model, client, clientId, request); } Set<String> responseTypes = authorizationRequest.getResponseTypes(); String grantType = deriveGrantTypeFromResponseType(responseTypes); if (!supported_response_types.containsAll(responseTypes)) { throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); } if (authorizationRequest.getClientId() == null) { throw new InvalidClientException("A client id must be provided"); } String resolvedRedirect = ""; try { String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); try { resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); } catch (RedirectMismatchException rme) { throw new RedirectMismatchException( "Invalid redirect " + redirectUriParameter + " did not match one of the registered values"); } if (!StringUtils.hasText(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } boolean isAuthenticated = (principal instanceof Authentication) && ((Authentication) principal).isAuthenticated(); if (!isAuthenticated) { throw new InsufficientAuthenticationException( "User must be authenticated with Spring Security before authorization can be completed."); } if (!(responseTypes.size() > 0)) { return new ModelAndView(new RedirectView( addQueryParameter(addQueryParameter(resolvedRedirect, "error", "invalid_request"), "error_description", "Missing response_type in authorization request"))); } authorizationRequest.setRedirectUri(resolvedRedirect); // We intentionally only validate the parameters requested by the client (ignoring any data that may have // been added to the request by the manager). oauth2RequestValidator.validateScope(authorizationRequest, client); // Some systems may allow for approval decisions to be remembered or approved by default. Check for // such logic here, and set the approved flag on the authorization request accordingly. authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, (Authentication) principal); boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal); authorizationRequest.setApproved(approved); // Validation is all done, so we can check for auto approval... if (authorizationRequest.isApproved()) { if (responseTypes.contains("token") || responseTypes.contains("id_token")) { return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType); } if (responseTypes.contains("code")) { return new ModelAndView( getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal)); } } if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) { return new ModelAndView( new RedirectView(addFragmentComponent(resolvedRedirect, "error=interaction_required"))); } else { // Place auth request into the model so that it is stored in the session // for approveOrDeny to use. That way we make sure that auth request comes from the session, // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session. model.put(AUTHORIZATION_REQUEST, authorizationRequest); model.put("original_uri", UrlUtils.buildFullRequestUrl(request)); model.put(ORIGINAL_AUTHORIZATION_REQUEST, unmodifiableMap(authorizationRequest)); return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal); } } catch (RedirectMismatchException e) { sessionStatus.setComplete(); throw e; } catch (Exception e) { sessionStatus.setComplete(); logger.debug("Unable to handle /oauth/authorize, internal error", e); if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) { return new ModelAndView( new RedirectView(addFragmentComponent(resolvedRedirect, "error=internal_server_error"))); } throw e; } }
From source file:org.slc.sli.api.security.OauthMongoSessionManager.java
/** * Creates a new app session Creates user session if needed *//*from w w w . j av a2 s . com*/ @Override @SuppressWarnings("unchecked") public void createAppSession(String sessionId, String clientId, String redirectUri, String state, String tenantId, String realmId, String samlId, boolean sessionExpired) { NeutralQuery nq = new NeutralQuery(new NeutralCriteria("client_id", "=", clientId)); Entity app = repo.findOne(APPLICATION_COLLECTION, nq); if (app == null) { RuntimeException x = new InvalidClientException( String.format("No app with id %s registered", clientId)); LOG.error(x.getMessage(), x); throw x; } Boolean isInstalled = (Boolean) app.getBody().get("installed"); String appRedirectUri = (String) app.getBody().get("redirect_uri"); if (!isInstalled && (appRedirectUri == null || appRedirectUri.trim().length() == 0)) { RuntimeException x = new RedirectMismatchException("No redirect_uri specified on non-installed app"); LOG.error(x.getMessage()); throw x; } if (!isInstalled && redirectUri != null && !redirectUri.startsWith((String) app.getBody().get("redirect_uri"))) { RuntimeException x = new RedirectMismatchException("Invalid redirect_uri specified " + redirectUri); LOG.error(x.getMessage() + " expected " + app.getBody().get("redirect_uri"), x); throw x; } Entity sessionEntity = sessionId == null ? null : repo.findById(SESSION_COLLECTION, sessionId); if (sessionEntity == null || sessionExpired) { sessionEntity = repo.create(SESSION_COLLECTION, new HashMap<String, Object>()); sessionEntity.getBody().put("expiration", System.currentTimeMillis() + this.sessionLength); sessionEntity.getBody().put("hardLogout", System.currentTimeMillis() + this.hardLogout); sessionEntity.getBody().put("requestedRealmId", realmId); sessionEntity.getBody().put("appSession", new ArrayList<Map<String, Object>>()); } List<Map<String, Object>> appSessions = (List<Map<String, Object>>) sessionEntity.getBody() .get("appSession"); appSessions.add(newAppSession(clientId, redirectUri, state, samlId, isInstalled)); repo.update(SESSION_COLLECTION, sessionEntity, false); }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
@RequestMapping(value = "/oauth/authorize") public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal) { logger.info("paramters:" + parameters.toString()); logger.info("model:" + model.toString()); // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should // query off of the authorization request instead of referring back to the parameters map. The contents of the // parameters map will be stored without change in the AuthorizationRequest object once it is created. AuthorizationRequest authorizationRequest = getOAuth2RequestFactory() .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 av a 2 s .c o m if (authorizationRequest.getClientId() == null) { throw new InvalidClientException("A client id must be provided"); } try { if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) { throw new InsufficientAuthenticationException( "User must be authenticated with Spring Security before authorization can be completed."); } ClientDetails client = getClientDetailsService() .loadClientByClientId(authorizationRequest.getClientId()); // The resolved redirect URI is either the redirect_uri from the parameters or the one from // clientDetails. Either way we need to store it on the AuthorizationRequest. String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); if (!StringUtils.hasText(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } authorizationRequest.setRedirectUri(resolvedRedirect); // We intentionally only validate the parameters requested by the client (ignoring any data that may have // been added to the request by the manager). oauth2RequestValidator.validateScope(authorizationRequest, client); // Some systems may allow for approval decisions to be remembered or approved by default. Check for // such logic here, and set the approved flag on the authorization request accordingly. authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, (Authentication) principal); // TODO: is this call necessary? boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal); authorizationRequest.setApproved(approved); // Validation is all done, so we can check for auto approval... if (authorizationRequest.isApproved()) { if (responseTypes.contains("token")) { return getImplicitGrantResponse(authorizationRequest); } if (responseTypes.contains("code")) { return new ModelAndView( getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal)); } } // Place auth request into the model so that it is stored in the session // for approveOrDeny to use. That way we make sure that auth request comes from the session, // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session. model.put("authorizationRequest", authorizationRequest); return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal); } catch (RuntimeException e) { sessionStatus.setComplete(); throw e; } }