List of usage examples for java.net URI getFragment
public String getFragment()
From source file:nl.basjes.parse.httpdlog.dissectors.HttpUriDissector.java
@Override public void dissect(final Parsable<?> parsable, final String inputname) throws DissectionFailure { final ParsedField field = parsable.getParsableField(INPUT_TYPE, inputname); String uriString = field.getValue().getString(); if (uriString == null || uriString.isEmpty()) { return; // Nothing to do here }// w w w . j av a 2s.c o m // First we cleanup the URI so we fail less often over 'garbage' URIs. // See: http://stackoverflow.com/questions/11038967/brackets-in-a-request-url-are-legal-but-not-in-a-uri-java try { uriString = URIUtil.encode(uriString, badUriChars, "UTF-8"); } catch (URIException e) { throw new DissectionFailure( "Failed to parse URI >>" + field.getValue().getString() + "<< because of : " + e.getMessage()); } // Before we hand it to the standard parser we hack it around a bit so we can parse // nasty edge cases that are illegal yet do occur in real clickstreams. // Also we force the query string to start with ?& so the returned query string starts with & // Which leads to more consistent output after parsing. int firstQuestionMark = uriString.indexOf('?'); int firstAmpersand = uriString.indexOf('&'); // Now we can have one of 3 situations: // 1) No query string // 2) Query string starts with a '?' // (and optionally followed by one or more '&' or '?' ) // 3) Query string starts with a '&'. This is invalid but does occur! // We may have ?x=x&y=y?z=z so we normalize it always // to: ?&x=x&y=y&z=z if (firstAmpersand != -1 || firstQuestionMark != -1) { uriString = uriString.replaceAll("\\?", "&"); uriString = uriString.replaceFirst("&", "?&"); } // We find that people muck up the URL by putting % signs in the URLs that are NOT escape sequences // So any % that is not followed by a two 'hex' letters is fixed uriString = BAD_EXCAPE_PATTERN.matcher(uriString).replaceAll("%25$1"); uriString = BAD_EXCAPE_PATTERN.matcher(uriString).replaceAll("%25$1"); boolean isUrl = true; URI uri; try { if (uriString.charAt(0) == '/') { uri = URI.create("dummy-protocol://dummy.host.name" + uriString); isUrl = false; // I.e. we do not return the values we just faked. } else { uri = URI.create(uriString); } } catch (IllegalArgumentException e) { throw new DissectionFailure( "Failed to parse URI >>" + field.getValue().getString() + "<< because of : " + e.getMessage()); } if (wantQuery || wantPath || wantRef) { if (wantQuery) { String query = uri.getRawQuery(); if (query == null) { query = ""; } parsable.addDissection(inputname, "HTTP.QUERYSTRING", "query", query); } if (wantPath) { parsable.addDissection(inputname, "HTTP.PATH", "path", uri.getPath()); } if (wantRef) { parsable.addDissection(inputname, "HTTP.REF", "ref", uri.getFragment()); } } if (isUrl) { if (wantProtocol) { parsable.addDissection(inputname, "HTTP.PROTOCOL", "protocol", uri.getScheme()); } if (wantUserinfo) { parsable.addDissection(inputname, "HTTP.USERINFO", "userinfo", uri.getUserInfo()); } if (wantHost) { parsable.addDissection(inputname, "HTTP.HOST", "host", uri.getHost()); } if (wantPort) { if (uri.getPort() != -1) { parsable.addDissection(inputname, "HTTP.PORT", "port", uri.getPort()); } } } }
From source file:de.zib.sfs.StatisticsFileSystem.java
private static URI replaceUriScheme(URI uri, String from, String to) { // TODO add cache for replaced URIs? possibly useful for scenarios with // many metadata operations. String scheme = uri.getScheme(); if (scheme != null) { if (scheme.equalsIgnoreCase(from)) { // uri has this scheme, replace it with new scheme // re-create the URI from scratch to avoid escaping of wanted // illegal characters StringBuilder buffer = new StringBuilder(); buffer.append(to).append(":"); String authority = uri.getAuthority(); if (authority != null) { buffer.append("//").append(authority); }//from w ww. j a va2s . c om String path = uri.getPath(); if (path != null) { buffer.append(path); } String fragment = uri.getFragment(); if (fragment != null) { buffer.append("#").append(fragment); } return URI.create(buffer.toString()); } else if (scheme.equalsIgnoreCase(to)) { // uri already has the correct scheme if (LOG.isDebugEnabled()) { LOG.debug("URI '" + uri + "' already has the correct scheme '" + to + "'."); } return null; } else { // uri has wrong scheme return null; } } // uri has no scheme return null; }
From source file:ddf.catalog.impl.operations.ResourceOperations.java
/** * Retrieves a resource by URI./*from w w w .j a va 2 s. c o m*/ * * <p>The {@link ResourceRequest} can specify either the product's URI or ID. If the product ID is * specified, then the matching {@link Metacard} must first be retrieved and the product URI * extracted from this {@link Metacard}. * * @param resourceRequest * @param site * @param isEnterprise * @param federatedSite * @param requestProperties * @param fanoutEnabled * @return * @throws ResourceNotSupportedException * @throws ResourceNotFoundException */ protected ResourceInfo getResourceInfo(ResourceRequest resourceRequest, String site, boolean isEnterprise, StringBuilder federatedSite, Map<String, Serializable> requestProperties, boolean fanoutEnabled) throws ResourceNotSupportedException, ResourceNotFoundException { ResourceInfo resourceInfo; Query query = null; URI resourceUri = null; String name = resourceRequest.getAttributeName(); Object value = resourceRequest.getAttributeValue(); validateResourceInfoRequest(name, value); try { if (ResourceRequest.GET_RESOURCE_BY_PRODUCT_URI.equals(name)) { // because this is a get resource by product uri, we already // have the product uri to return LOGGER.debug("get resource by product uri"); resourceUri = (URI) value; URI truncatedUri = resourceUri; if (StringUtils.isNotBlank(resourceUri.getFragment())) { resourceRequest.getProperties().put(ContentItem.QUALIFIER_KEYWORD, resourceUri.getFragment()); try { // Creating the truncated URL this way is important to preserve encoding!! String uriString = resourceUri.toString(); truncatedUri = new URI(uriString.substring(0, uriString.lastIndexOf('#'))); } catch (URISyntaxException e) { throw new ResourceNotFoundException( "Could not resolve URI by doing a URI based query: " + value); } } query = createPropertyStartsWithQuery(Metacard.RESOURCE_URI, truncatedUri.toString()); } else if (ResourceRequest.GET_RESOURCE_BY_ID.equals(name)) { // since this is a get resource by id, we need to obtain the // product URI LOGGER.debug("get resource by id"); String metacardId = (String) value; LOGGER.debug("metacardId = {}, site = {}", metacardId, site); query = createMetacardIdQuery(metacardId); } QueryRequest queryRequest = new QueryRequestImpl(anyTag(query, site, isEnterprise), isEnterprise, Collections.singletonList(site == null ? this.getId() : site), resourceRequest.getProperties()); resourceInfo = getResourceInfo(queryRequest, resourceUri, requestProperties, federatedSite, fanoutEnabled); } catch (UnsupportedQueryException | FederationException e) { throw new ResourceNotFoundException(DEFAULT_RESOURCE_NOT_FOUND_MESSAGE, e); } if (resourceInfo.getResourceUri() == null) { throw new ResourceNotFoundException(DEFAULT_RESOURCE_NOT_FOUND_MESSAGE); } LOGGER.debug("Returning resourceURI: {}", resourceInfo.getResourceUri()); return resourceInfo; }
From source file:org.xdi.oxauth.authorize.ws.rs.AuthorizeRestWebServiceImpl.java
public Response requestAuthorization(String scope, String responseType, String clientId, String redirectUri, String state, String respMode, String nonce, String display, String prompt, Integer maxAge, String uiLocalesStr, String idTokenHint, String loginHint, String acrValuesStr, String amrValuesStr, String request, String requestUri, String requestSessionId, String sessionId, String accessToken, String method, String originHeaders, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) { scope = ServerUtil.urlDecode(scope); // it may be encoded in uma case // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final , // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate log.debug(/*from w ww.j a v a 2 s. c o m*/ "Attempting to request authorization: " + "responseType = {0}, clientId = {1}, scope = {2}, redirectUri = {3}, nonce = {4}, " + "state = {5}, request = {6}, isSecure = {7}, requestSessionId = {8}, sessionId = {9}", responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(), requestSessionId, sessionId); log.debug("Attempting to request authorization: " + "acrValues = {0}, amrValues = {1}, originHeaders = {4}", acrValuesStr, amrValuesStr, originHeaders); ResponseBuilder builder = Response.ok(); List<String> uiLocales = null; if (StringUtils.isNotBlank(uiLocalesStr)) { uiLocales = Util.splittedStringAsList(uiLocalesStr, " "); } List<ResponseType> responseTypes = ResponseType.fromString(responseType, " "); List<Prompt> prompts = Prompt.fromString(prompt, " "); List<String> acrValues = Util.splittedStringAsList(acrValuesStr, " "); List<String> amrValues = Util.splittedStringAsList(amrValuesStr, " "); ResponseMode responseMode = ResponseMode.getByValue(respMode); User user = sessionUser != null && StringUtils.isNotBlank(sessionUser.getUserDn()) ? userService.getUserByDn(sessionUser.getUserDn()) : null; try { sessionIdService.updateSessionIfNeeded(sessionUser, redirectUri, acrValuesStr); if (!AuthorizeParamsValidator.validateParams(responseType, clientId, prompts, nonce, request, requestUri)) { if (clientId != null && redirectUri != null && redirectionUriService.validateRedirectionUri(clientId, redirectUri) != null) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory .getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400 builder.entity( errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, state)); } } else { Client client = clientService.getClient(clientId); JwtAuthorizationRequest jwtAuthorizationRequest = null; if (client != null) { List<String> scopes = new ArrayList<String>(); if (StringHelper.isNotEmpty(scope)) { Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope); scopes.addAll(grantedScopes); } // Validate redirectUri redirectUri = redirectionUriService.validateRedirectionUri(clientId, redirectUri); boolean validRedirectUri = redirectUri != null; if (AuthorizeParamsValidator.validateResponseTypes(responseTypes, client)) { if (validRedirectUri) { if (ConfigurationFactory.instance().getConfiguration().getFederationEnabled()) { if (!federationDataService.hasAnyActiveTrust(client)) { log.debug( "Forbid authorization. Client is not in any trust relationship however federation is enabled for server. Client id: {0}, client redirectUris: {1}", client.getClientId(), client.getRedirectUris()); return error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state).build(); } } if (StringUtils.isNotBlank(accessToken)) { AuthorizationGrant authorizationGrant = authorizationGrantList .getAuthorizationGrantByAccessToken(accessToken); if (authorizationGrant == null) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.ACCESS_DENIED, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } else { user = userService.getUser(authorizationGrant.getUserId()); sessionUser = sessionIdService.generateAuthenticatedSessionId(user.getDn(), prompt); } } if (StringUtils.isNotBlank(requestUri)) { boolean validRequestUri = false; try { URI reqUri = new URI(requestUri); String reqUriHash = reqUri.getFragment(); String reqUriWithoutFragment = reqUri.getScheme() + ":" + reqUri.getSchemeSpecificPart(); ClientRequest clientRequest = new ClientRequest(reqUriWithoutFragment); clientRequest.setHttpMethod(HttpMethod.GET); ClientResponse<String> clientResponse = clientRequest.get(String.class); int status = clientResponse.getStatus(); if (status == 200) { request = clientResponse.getEntity(String.class); if (StringUtils.isBlank(reqUriHash)) { validRequestUri = true; } else { String hash = JwtUtil .base64urlencode(JwtUtil.getMessageDigestSHA256(request)); validRequestUri = StringUtils.equals(reqUriHash, hash); } } if (validRequestUri) { requestUri = null; } else { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse .parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.INVALID_REQUEST_URI, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } catch (URISyntaxException e) { log.error(e.getMessage(), e); } catch (UnknownHostException e) { log.error(e.getMessage(), e); } catch (ConnectException e) { log.error(e.getMessage(), e); } catch (Exception e) { log.error(e.getMessage(), e); } } boolean invalidOpenidRequestObject = false; if (StringUtils.isNotBlank(request)) { try { jwtAuthorizationRequest = new JwtAuthorizationRequest(request, client); if (!jwtAuthorizationRequest.getResponseTypes().containsAll(responseTypes) || !responseTypes .containsAll(jwtAuthorizationRequest.getResponseTypes())) { throw new InvalidJwtException( "The responseType parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getClientId() != null && !jwtAuthorizationRequest.getClientId().equals(clientId)) { throw new InvalidJwtException( "The clientId parameter is not the same in the JWT"); } else if (!jwtAuthorizationRequest.getScopes().containsAll(scopes) || !scopes.containsAll(jwtAuthorizationRequest.getScopes())) { throw new InvalidJwtException( "The scope parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getRedirectUri() != null && !jwtAuthorizationRequest.getRedirectUri().equals(redirectUri)) { throw new InvalidJwtException( "The redirectUri parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getState() != null && StringUtils.isNotBlank(state) && !jwtAuthorizationRequest.getState().equals(state)) { throw new InvalidJwtException( "The state parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getNonce() != null && StringUtils.isNotBlank(nonce) && !jwtAuthorizationRequest.getNonce().equals(nonce)) { throw new InvalidJwtException( "The nonce parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getDisplay() != null && StringUtils.isNotBlank(display) && !jwtAuthorizationRequest .getDisplay().getParamName().equals(display)) { throw new InvalidJwtException( "The display parameter is not the same in the JWT"); } else if (!jwtAuthorizationRequest.getPrompts().isEmpty() && !prompts.isEmpty() && !jwtAuthorizationRequest.getPrompts().containsAll(prompts)) { throw new InvalidJwtException( "The prompt parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null && maxAge != null && !jwtAuthorizationRequest.getIdTokenMember() .getMaxAge().equals(maxAge)) { throw new InvalidJwtException( "The maxAge parameter is not the same in the JWT"); } } catch (InvalidJwtException e) { invalidOpenidRequestObject = true; log.debug("Invalid JWT authorization request. Exception = {0}, Message = {1}", e, e.getClass().getName(), e.getMessage()); } catch (Exception e) { invalidOpenidRequestObject = true; log.debug("Invalid JWT authorization request. Exception = {0}, Message = {1}", e, e.getClass().getName(), e.getMessage()); } } if (invalidOpenidRequestObject) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.INVALID_OPENID_REQUEST_OBJECT, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { AuthorizationGrant authorizationGrant = null; RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); if (jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null) { Claim userIdClaim = jwtAuthorizationRequest.getIdTokenMember() .getClaim(JwtClaimName.SUBJECT_IDENTIFIER); if (userIdClaim != null && userIdClaim.getClaimValue() != null && userIdClaim.getClaimValue().getValue() != null) { String userIdClaimValue = userIdClaim.getClaimValue().getValue(); if (user != null) { String userId = user.getUserId(); if (!userId.equalsIgnoreCase(userIdClaimValue)) { redirectUriResponse.parseQueryString( errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.USER_MISMATCHED, state)); builder = RedirectUtil.getRedirectResponseBuilder( redirectUriResponse, httpRequest); return builder.build(); } } } } if (user == null) { identity.logout(); if (prompts.contains(Prompt.NONE)) { if (authenticationFilterService.isEnabled()) { Map<String, String> params = new HashMap<String, String>(); if (method.equals(HttpMethod.GET)) { params = QueryStringDecoder.decode(httpRequest.getQueryString()); } else { params = httpRequest.getParameterMap(); } String userDn = authenticationFilterService .processAuthenticationFilters(params); if (userDn != null) { sessionUser = sessionIdService .generateAuthenticatedSessionId(userDn, prompt); user = userService.getUserByDn(sessionUser.getUserDn()); Authenticator authenticator = (Authenticator) Component .getInstance(Authenticator.class, true); authenticator.authenticateExternallyWebService(user.getUserId()); identity.addRole("user"); } else { redirectUriResponse.parseQueryString( errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.LOGIN_REQUIRED, state)); builder = RedirectUtil.getRedirectResponseBuilder( redirectUriResponse, httpRequest); return builder.build(); } } else { redirectUriResponse .parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.LOGIN_REQUIRED, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } else { if (prompts.contains(Prompt.LOGIN)) { endSession(sessionId, httpRequest, httpResponse); prompts.remove(Prompt.LOGIN); } redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } ClientAuthorizations clientAuthorizations = clientAuthorizationsService .findClientAuthorizations(user.getAttribute("inum"), client.getClientId()); if (clientAuthorizations != null && clientAuthorizations.getScopes() != null && Arrays.asList(clientAuthorizations.getScopes()).containsAll(scopes)) { sessionUser.addPermission(clientId, true); } if (prompts.contains(Prompt.NONE) && Boolean.parseBoolean(client.getTrustedClient())) { sessionUser.addPermission(clientId, true); } if (prompts.contains(Prompt.LOGIN)) { endSession(sessionId, httpRequest, httpResponse); prompts.remove(Prompt.LOGIN); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } if (prompts.contains(Prompt.CONSENT) && !sessionUser.isPermissionGrantedForClient(clientId)) { prompts.remove(Prompt.CONSENT); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } // OXAUTH-37 : Validate authentication max age boolean validAuthenticationMaxAge = true; Integer authenticationMaxAge = null; if (maxAge != null) { authenticationMaxAge = maxAge; } else if (!invalidOpenidRequestObject && jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null) { authenticationMaxAge = jwtAuthorizationRequest.getIdTokenMember().getMaxAge(); } GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC")); GregorianCalendar userAuthenticationTime = new GregorianCalendar( TimeZone.getTimeZone("UTC")); userAuthenticationTime.setTime(sessionUser.getAuthenticationTime()); if (authenticationMaxAge != null) { userAuthenticationTime.add(Calendar.SECOND, authenticationMaxAge); validAuthenticationMaxAge = userAuthenticationTime.after(now); } else if (client.getDefaultMaxAge() != null) { userAuthenticationTime.add(Calendar.SECOND, client.getDefaultMaxAge()); validAuthenticationMaxAge = userAuthenticationTime.after(now); } if (!validAuthenticationMaxAge) { endSession(sessionId, httpRequest, httpResponse); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } // OXAUTH-87 : Checks whether client has groups. If yes then user must be in one of these groups otherwise forbid authorization. if (checkUserGroups(user, client)) { AuthorizationCode authorizationCode = null; if (responseTypes.contains(ResponseType.CODE)) { authorizationGrant = authorizationGrantList.createAuthorizationCodeGrant( user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store acr_values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification!!! authorizationCode = authorizationGrant.getAuthorizationCode(); redirectUriResponse.addResponseParameter("code", authorizationCode.getCode()); } AccessToken newAccessToken = null; if (responseTypes.contains(ResponseType.TOKEN)) { if (authorizationGrant == null) { authorizationGrant = authorizationGrantList.createImplicitGrant(user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store acr_values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification!!! } newAccessToken = authorizationGrant.createAccessToken(); redirectUriResponse.addResponseParameter("access_token", newAccessToken.getCode()); redirectUriResponse.addResponseParameter("token_type", newAccessToken.getTokenType().toString()); redirectUriResponse.addResponseParameter("expires_in", newAccessToken.getExpiresIn() + ""); } if (responseTypes.contains(ResponseType.ID_TOKEN)) { if (authorizationGrant == null) { authorizationGrant = authorizationGrantList.createAuthorizationGrant( user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store authentication acr values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification, call is asynchronous!!! } //Map<String, String> idTokenClaims = getClaims(user, authorizationGrant, scopes); IdToken idToken = authorizationGrant.createIdToken(nonce, authorizationCode, newAccessToken, authorizationGrant.getAcrValues()); redirectUriResponse.addResponseParameter("id_token", idToken.getCode()); } if (authorizationGrant != null && StringHelper.isNotEmpty(acrValuesStr)) { redirectUriResponse.addResponseParameter("acr_values", acrValuesStr); } //if (Boolean.valueOf(requestSessionId) && StringUtils.isBlank(sessionId) && if (sessionUser.getId() == null) { final SessionId newSessionUser = sessionIdService .generateAuthenticatedSessionId(sessionUser.getUserDn(), prompt); String newSessionId = newSessionUser.getId(); sessionUser.setId(newSessionId); log.trace("newSessionId = {0}", newSessionId); } redirectUriResponse.addResponseParameter(Parameters.SESSION_ID.getParamName(), sessionUser.getId()); redirectUriResponse.addResponseParameter("state", state); if (scope != null && !scope.isEmpty()) { scope = authorizationGrant.checkScopesPolicy(scope); redirectUriResponse.addResponseParameter("scope", scope); } clientService.updatAccessTime(client, false); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } } } else { // Invalid redirectUri builder = error(Response.Status.BAD_REQUEST, AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state); // 400 } } else { // Invalid responseTypes builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400 builder.entity(errorResponseFactory .getErrorAsJson(AuthorizeErrorResponseType.UNSUPPORTED_RESPONSE_TYPE, state)); } } else { builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state); } } } catch (AcrChangedException e) { builder = Response.status(Response.Status.UNAUTHORIZED) .entity("Session already exist with ACR that is different " + "than the one send with this authorization request. Please perform logout in order to login with another ACR. ACR: " + acrValuesStr); log.error(e.getMessage(), e); } catch (EntryPersistenceException e) { // Invalid clientId builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state); log.error(e.getMessage(), e); } catch (SignatureException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (StringEncrypter.EncryptionException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (InvalidJwtException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (Exception e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } return builder.build(); }
From source file:org.xdi.oxauth.ws.rs.UserInfoRestWebServiceEmbeddedTest.java
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" }) @Test(dependsOnMethods = "dynamicClientRegistration") public void requestUserInfoStep1ImplicitFlow(final String authorizePath, final String userId, final String userSecret, final String redirectUri) throws Exception { final String userEncodedCredentials = Base64.encodeBase64String((userId + ":" + userSecret).getBytes()); final String state = UUID.randomUUID().toString(); new ResourceRequestEnvironment.ResourceRequest(new ResourceRequestEnvironment(this), Method.GET, authorizePath) {/* w w w . j av a2 s .c o m*/ @Override protected void prepareRequest(EnhancedMockHttpServletRequest request) { super.prepareRequest(request); request.addHeader("Authorization", "Basic " + userEncodedCredentials); request.addHeader("Accept", MediaType.TEXT_PLAIN); List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN); List<String> scopes = Arrays.asList("openid", "profile", "address", "email"); String nonce = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce); authorizationRequest.setState(state); authorizationRequest.getPrompts().add(Prompt.NONE); request.setQueryString(authorizationRequest.getQueryString()); } @Override protected void onResponse(EnhancedMockHttpServletResponse response) { super.onResponse(response); showResponse("requestUserInfo step 1 Implicit Flow", response); assertEquals(response.getStatus(), 302, "Unexpected response code."); assertNotNull(response.getHeader("Location"), "Unexpected result: " + response.getHeader("Location")); if (response.getHeader("Location") != null) { try { URI uri = new URI(response.getHeader("Location").toString()); assertNotNull(uri.getFragment(), "Fragment is null"); Map<String, String> params = QueryStringDecoder.decode(uri.getFragment()); assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The access token is null"); assertNotNull(params.get(AuthorizeResponseParam.TOKEN_TYPE), "The token type is null"); assertNotNull(params.get(AuthorizeResponseParam.EXPIRES_IN), "The expires in value is null"); assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope must be null"); assertNull(params.get("refresh_token"), "The refresh_token must be null"); assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null"); assertEquals(params.get(AuthorizeResponseParam.STATE), state); accessToken1 = params.get(AuthorizeResponseParam.ACCESS_TOKEN); } catch (URISyntaxException e) { e.printStackTrace(); fail("Response URI is not well formed"); } catch (Exception e) { e.printStackTrace(); fail("Unexpected error"); } } } }.run(); }
From source file:org.xdi.oxauth.ws.rs.UserInfoRestWebServiceEmbeddedTest.java
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" }) @Test(dependsOnMethods = "dynamicClientRegistration") public void requestUserInfoInsufficientScope(final String authorizePath, final String userId, final String userSecret, final String redirectUri) throws Exception { final String state = UUID.randomUUID().toString(); new ResourceRequestEnvironment.ResourceRequest(new ResourceRequestEnvironment(this), Method.GET, authorizePath) {/* w w w . j a v a2s. c o m*/ @Override protected void prepareRequest(EnhancedMockHttpServletRequest request) { super.prepareRequest(request); List<ResponseType> responseTypes = new ArrayList<ResponseType>(); responseTypes.add(ResponseType.TOKEN); List<String> scopes = Arrays.asList("picture"); String nonce = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce); authorizationRequest.setState(state); authorizationRequest.getPrompts().add(Prompt.NONE); authorizationRequest.setAuthUsername(userId); authorizationRequest.setAuthPassword(userSecret); request.addHeader("Authorization", "Basic " + authorizationRequest.getEncodedCredentials()); request.addHeader("Accept", MediaType.TEXT_PLAIN); request.setQueryString(authorizationRequest.getQueryString()); } @Override protected void onResponse(EnhancedMockHttpServletResponse response) { super.onResponse(response); showResponse("requestUserInfoInsufficientScope step 1", response); assertEquals(response.getStatus(), 302, "Unexpected response code."); assertNotNull(response.getHeader("Location"), "Unexpected result: " + response.getHeader("Location")); if (response.getHeader("Location") != null) { try { URI uri = new URI(response.getHeader("Location").toString()); assertNotNull(uri.getFragment(), "Fragment is null"); Map<String, String> params = QueryStringDecoder.decode(uri.getFragment()); assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The access token is null"); assertNotNull(params.get(AuthorizeResponseParam.TOKEN_TYPE), "The token type is null"); assertNotNull(params.get(AuthorizeResponseParam.EXPIRES_IN), "The expires in value is null"); assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope must be null"); assertNull(params.get("refresh_token"), "The refresh_token must be null"); assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null"); assertEquals(params.get(AuthorizeResponseParam.STATE), state); accessToken2 = params.get(AuthorizeResponseParam.ACCESS_TOKEN); } catch (URISyntaxException e) { e.printStackTrace(); fail("Response URI is not well formed"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } } }.run(); }
From source file:org.xdi.oxauth.ws.rs.UserInfoRestWebServiceEmbeddedTest.java
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" }) @Test(dependsOnMethods = "requestUserInfoHS512Step1") public void requestUserInfoHS512Step2(final String authorizePath, final String userId, final String userSecret, final String redirectUri) throws Exception { final String state = UUID.randomUUID().toString(); new ResourceRequestEnvironment.ResourceRequest(new ResourceRequestEnvironment(this), ResourceRequestEnvironment.Method.GET, authorizePath) { @Override//from www. ja va2 s .c o m protected void prepareRequest(EnhancedMockHttpServletRequest request) { super.prepareRequest(request); List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN); List<String> scopes = Arrays.asList("openid"); String nonce = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId3, scopes, redirectUri, nonce); authorizationRequest.setState(state); authorizationRequest.getPrompts().add(Prompt.NONE); authorizationRequest.setAuthUsername(userId); authorizationRequest.setAuthPassword(userSecret); JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.HS512, clientSecret3); jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false))); jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false))); String authJwt = jwtAuthorizationRequest.getEncodedJwt(); authorizationRequest.setRequest(authJwt); System.out.println("Request JWT: " + authJwt); request.addHeader("Authorization", "Basic " + authorizationRequest.getEncodedCredentials()); request.addHeader("Accept", MediaType.TEXT_PLAIN); request.setQueryString(authorizationRequest.getQueryString()); } @Override protected void onResponse(EnhancedMockHttpServletResponse response) { super.onResponse(response); showResponse("requestUserInfoHS512Step2", response); assertEquals(response.getStatus(), 302, "Unexpected response code."); assertNotNull(response.getHeader("Location"), "Unexpected result: " + response.getHeader("Location")); try { URI uri = new URI(response.getHeader("Location").toString()); assertNotNull(uri.getFragment(), "Query string is null"); Map<String, String> params = QueryStringDecoder.decode(uri.getFragment()); assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The accessToken is null"); assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope is null"); assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null"); assertEquals(params.get(AuthorizeResponseParam.STATE), state); accessToken7 = params.get(AuthorizeResponseParam.ACCESS_TOKEN); } catch (URISyntaxException e) { e.printStackTrace(); fail("Response URI is not well formed"); } } }.run(); }
From source file:org.xdi.oxauth.ws.rs.UserInfoRestWebServiceEmbeddedTest.java
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" }) @Test(dependsOnMethods = "requestUserInfoHS256Step1") public void requestUserInfoHS256Step2(final String authorizePath, final String userId, final String userSecret, final String redirectUri) throws Exception { final String state = UUID.randomUUID().toString(); new ResourceRequestEnvironment.ResourceRequest(new ResourceRequestEnvironment(this), ResourceRequestEnvironment.Method.GET, authorizePath) { @Override//from w ww. j av a2 s .co m protected void prepareRequest(EnhancedMockHttpServletRequest request) { super.prepareRequest(request); List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN); List<String> scopes = Arrays.asList("openid"); String nonce = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId1, scopes, redirectUri, nonce); authorizationRequest.setState(state); authorizationRequest.getPrompts().add(Prompt.NONE); authorizationRequest.setAuthUsername(userId); authorizationRequest.setAuthPassword(userSecret); JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.HS256, clientSecret1); jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false))); jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false))); String authJwt = jwtAuthorizationRequest.getEncodedJwt(); authorizationRequest.setRequest(authJwt); System.out.println("Request JWT: " + authJwt); request.addHeader("Authorization", "Basic " + authorizationRequest.getEncodedCredentials()); request.addHeader("Accept", MediaType.TEXT_PLAIN); request.setQueryString(authorizationRequest.getQueryString()); } @Override protected void onResponse(EnhancedMockHttpServletResponse response) { super.onResponse(response); showResponse("requestUserInfoHS256Step2", response); assertEquals(response.getStatus(), 302, "Unexpected response code."); assertNotNull(response.getHeader("Location"), "Unexpected result: " + response.getHeader("Location")); try { URI uri = new URI(response.getHeader("Location").toString()); assertNotNull(uri.getFragment(), "Query string is null"); Map<String, String> params = QueryStringDecoder.decode(uri.getFragment()); assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The accessToken is null"); assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope is null"); assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null"); assertEquals(params.get(AuthorizeResponseParam.STATE), state); accessToken5 = params.get(AuthorizeResponseParam.ACCESS_TOKEN); } catch (URISyntaxException e) { e.printStackTrace(); fail("Response URI is not well formed"); } } }.run(); }
From source file:org.xdi.oxauth.ws.rs.UserInfoRestWebServiceEmbeddedTest.java
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri" }) @Test(dependsOnMethods = "requestUserInfoHS384Step1") public void requestUserInfoHS384Step2(final String authorizePath, final String userId, final String userSecret, final String redirectUri) throws Exception { final String state = UUID.randomUUID().toString(); new ResourceRequestEnvironment.ResourceRequest(new ResourceRequestEnvironment(this), ResourceRequestEnvironment.Method.GET, authorizePath) { @Override//from ww w .j av a 2 s. co m protected void prepareRequest(EnhancedMockHttpServletRequest request) { super.prepareRequest(request); List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN); List<String> scopes = Arrays.asList("openid"); String nonce = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId2, scopes, redirectUri, nonce); authorizationRequest.setState(state); authorizationRequest.getPrompts().add(Prompt.NONE); authorizationRequest.setAuthUsername(userId); authorizationRequest.setAuthPassword(userSecret); JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.HS384, clientSecret2); jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false))); jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull())); jwtAuthorizationRequest .addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false))); String authJwt = jwtAuthorizationRequest.getEncodedJwt(); authorizationRequest.setRequest(authJwt); System.out.println("Request JWT: " + authJwt); request.addHeader("Authorization", "Basic " + authorizationRequest.getEncodedCredentials()); request.addHeader("Accept", MediaType.TEXT_PLAIN); request.setQueryString(authorizationRequest.getQueryString()); } @Override protected void onResponse(EnhancedMockHttpServletResponse response) { super.onResponse(response); showResponse("requestUserInfoHS384Step2", response); assertEquals(response.getStatus(), 302, "Unexpected response code."); assertNotNull(response.getHeader("Location"), "Unexpected result: " + response.getHeader("Location")); try { URI uri = new URI(response.getHeader("Location").toString()); assertNotNull(uri.getFragment(), "Query string is null"); Map<String, String> params = QueryStringDecoder.decode(uri.getFragment()); assertNotNull(params.get(AuthorizeResponseParam.ACCESS_TOKEN), "The accessToken is null"); assertNotNull(params.get(AuthorizeResponseParam.SCOPE), "The scope is null"); assertNotNull(params.get(AuthorizeResponseParam.STATE), "The state is null"); assertEquals(params.get(AuthorizeResponseParam.STATE), state); accessToken6 = params.get(AuthorizeResponseParam.ACCESS_TOKEN); } catch (URISyntaxException e) { e.printStackTrace(); fail("Response URI is not well formed"); } } }.run(); }