Java Code Examples for javax.ws.rs.core.MultivaluedMap#getFirst()
The following examples show how to use
javax.ws.rs.core.MultivaluedMap#getFirst() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OAuthUtils.java From cxf with Apache License 2.0 | 6 votes |
public static boolean checkRequestURI(String servletPath, String uri) { boolean wildcard = uri.endsWith("*"); String theURI = wildcard ? uri.substring(0, uri.length() - 1) : uri; try { URITemplate template = new URITemplate(theURI); MultivaluedMap<String, String> map = new MetadataMap<>(); if (template.match(servletPath, map)) { String finalGroup = map.getFirst(URITemplate.FINAL_MATCH_GROUP); if (wildcard || StringUtils.isEmpty(finalGroup) || "/".equals(finalGroup)) { return true; } } } catch (Exception ex) { // ignore } return false; }
Example 2
Source File: OAuthUtils.java From cxf with Apache License 2.0 | 6 votes |
public static boolean checkRequestURI(String servletPath, String uri) { boolean wildcard = uri.endsWith("*"); String theURI = wildcard ? uri.substring(0, uri.length() - 1) : uri; try { URITemplate template = new URITemplate(theURI); MultivaluedMap<String, String> map = new MetadataMap<>(); if (template.match(servletPath, map)) { String finalGroup = map.getFirst(URITemplate.FINAL_MATCH_GROUP); if (wildcard || StringUtils.isEmpty(finalGroup) || "/".equals(finalGroup)) { return true; } } } catch (Exception ex) { // ignore } return false; }
Example 3
Source File: CategoryResourceTest.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
@Test public void shouldGetCategoryPicture() throws IOException { final Response response = target(CATEGORY_ID).path("picture").request().get(); assertEquals(OK_200, response.getStatus()); MultivaluedMap<String, Object> headers = response.getHeaders(); String contentType = (String) headers.getFirst(HttpHeader.CONTENT_TYPE.asString()); String etag = (String) headers.getFirst("ETag"); assertEquals(mockImage.getType(), contentType); File result = response.readEntity(File.class); byte[] fileContent = Files.readAllBytes(Paths.get(result.getAbsolutePath())); assertTrue(Arrays.equals(fileContent, apiLogoContent)); String expectedTag = '"'+Integer.toString(new String(fileContent).hashCode())+'"'; assertEquals(expectedTag, etag); // test Cache final Response cachedResponse = target(CATEGORY_ID).path("picture").request().header(HttpHeader.IF_NONE_MATCH.asString(), etag).get(); assertEquals(NOT_MODIFIED_304, cachedResponse.getStatus()); }
Example 4
Source File: OidcClientCodeRequestFilter.java From cxf with Apache License 2.0 | 6 votes |
private void validateIdToken(IdToken idToken, MultivaluedMap<String, String> state) { String nonce = state.getFirst(IdToken.NONCE_CLAIM); String tokenNonce = idToken.getNonce(); if (nonce != null && (tokenNonce == null || !nonce.equals(tokenNonce))) { throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST); } if (maxAgeOffset != null) { long authTime = Long.parseLong(state.getFirst(MAX_AGE_PARAMETER)); Long tokenAuthTime = idToken.getAuthenticationTime(); if (tokenAuthTime > authTime) { throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST); } } String acr = idToken.getAuthenticationContextRef(); // Skip the check if the acr is not set given it is a voluntary claim if (acr != null && authenticationContextRef != null && !authenticationContextRef.contains(acr)) { throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST); } }
Example 5
Source File: DefaultRestService.java From amforeas with GNU General Public License v3.0 | 6 votes |
public Response find (String alias, String resource, String pk, String col, String arg, MultivaluedMap<String, String> queryParams) { if (!aclManager.validate(alias, resource, ACLFilter.READ)) { return new ErrorResponse(resource, Response.Status.METHOD_NOT_ALLOWED).getResponse(); } PerformanceLogger p = PerformanceLogger.start(PerformanceLogger.Code.READ); var limit = LimitParam.valueOf(queryParams, this.getPageSize(queryParams)); var order = OrderParam.valueOf(queryParams, pk); var columns = queryParams.getFirst("columns"); Response response = null; try { response = factory.getRESTController(alias).findResources(resource, col, arg, limit, order, columns).getResponse(); } catch (IllegalArgumentException e) { response = new ErrorResponse(alias, Response.Status.BAD_REQUEST, e.getMessage()).getResponse(); } finally { if (response != null) { u.addRead(p.end(), response.getStatus()); } } return response; }
Example 6
Source File: AuthorizationEndpoint.java From keycloak-protocol-cas with Apache License 2.0 | 6 votes |
@GET public Response build() { MultivaluedMap<String, String> params = session.getContext().getUri().getQueryParameters(); String service = params.getFirst(CASLoginProtocol.SERVICE_PARAM); boolean renew = params.containsKey(CASLoginProtocol.RENEW_PARAM); boolean gateway = params.containsKey(CASLoginProtocol.GATEWAY_PARAM); checkSsl(); checkRealm(); checkClient(service); authenticationSession = createAuthenticationSession(client, null); updateAuthenticationSession(); // So back button doesn't work CacheControlUtil.noBackButtonCacheControlHeader(); if (renew) { authenticationSession.setClientNote(CASLoginProtocol.RENEW_PARAM, "true"); } this.event.event(EventType.LOGIN); return handleBrowserAuthenticationRequest(authenticationSession, new CASLoginProtocol(session, realm, session.getContext().getUri(), headers, event), gateway, false); }
Example 7
Source File: KeycloakSmsAuthenticator.java From keycloak-sms-authenticator with Eclipse Public License 2.0 | 5 votes |
protected CODE_STATUS validateCode(AuthenticationFlowContext context) { CODE_STATUS result = CODE_STATUS.INVALID; logger.debug("validateCode called ... "); MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); String enteredCode = formData.getFirst(SMSAuthenticatorContstants.ANSW_SMS_CODE); String expectedCode = SMSAuthenticatorUtil.getCredentialValue(context.getUser(), SMSAuthenticatorContstants.USR_CRED_MDL_SMS_CODE); String expTimeString = SMSAuthenticatorUtil.getCredentialValue(context.getUser(), SMSAuthenticatorContstants.USR_CRED_MDL_SMS_EXP_TIME); logger.debug("Expected code = " + expectedCode + " entered code = " + enteredCode); if(expectedCode != null) { result = enteredCode.equals(expectedCode) ? CODE_STATUS.VALID : CODE_STATUS.INVALID; long now = new Date().getTime(); logger.debug("Valid code expires in " + (Long.parseLong(expTimeString) - now) + " ms"); if(result == CODE_STATUS.VALID) { if (Long.parseLong(expTimeString) < now) { logger.debug("Code is expired !!"); result = CODE_STATUS.EXPIRED; } } } logger.debug("result : " + result); return result; }
Example 8
Source File: AuthorizationCodeGrantHandler.java From cxf with Apache License 2.0 | 5 votes |
public ServerAccessToken createAccessToken(Client client, MultivaluedMap<String, String> params) throws OAuthServiceException { // Get the grant representation from the provider String codeValue = params.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE); ServerAuthorizationCodeGrant grant = ((AuthorizationCodeDataProvider)getDataProvider()).removeCodeGrant(codeValue); if (grant == null) { return null; } // check it has not expired, the client ids are the same if (OAuthUtils.isExpired(grant.getIssuedAt(), grant.getExpiresIn())) { throw new OAuthServiceException(OAuthConstants.INVALID_GRANT); } if (!grant.getClient().getClientId().equals(client.getClientId())) { throw new OAuthServiceException(OAuthConstants.INVALID_GRANT); } // redirect URIs must match too String expectedRedirectUri = grant.getRedirectUri(); String providedRedirectUri = params.getFirst(OAuthConstants.REDIRECT_URI); if (providedRedirectUri != null) { if (!providedRedirectUri.equals(expectedRedirectUri)) { throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST); } } else if (expectedRedirectUri == null && !isCanSupportPublicClients() || expectedRedirectUri != null && (client.getRedirectUris().size() != 1 || !client.getRedirectUris().contains(expectedRedirectUri))) { throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST); } String clientCodeVerifier = params.getFirst(OAuthConstants.AUTHORIZATION_CODE_VERIFIER); String clientCodeChallenge = grant.getClientCodeChallenge(); if (!compareCodeVerifierWithChallenge(client, clientCodeVerifier, clientCodeChallenge)) { throw new OAuthServiceException(OAuthConstants.INVALID_GRANT); } List<String> audiences = getAudiences(client, params, grant.getAudience()); return doCreateAccessToken(client, grant, getSingleGrantType(), clientCodeVerifier, audiences); }
Example 9
Source File: DockerEndpoint.java From keycloak with Apache License 2.0 | 5 votes |
@GET public Response build() { ProfileHelper.requireFeature(Profile.Feature.DOCKER); final MultivaluedMap<String, String> params = session.getContext().getUri().getQueryParameters(); account = params.getFirst(DockerAuthV2Protocol.ACCOUNT_PARAM); if (account == null) { logger.debug("Account parameter not provided by docker auth. This is techincally required, but not actually used since " + "username is provided by Basic auth header."); } service = params.getFirst(DockerAuthV2Protocol.SERVICE_PARAM); if (service == null) { throw new ErrorResponseException("invalid_request", "service parameter must be provided", Response.Status.BAD_REQUEST); } client = realm.getClientByClientId(service); if (client == null) { logger.errorv("Failed to lookup client given by service={0} parameter for realm: {1}.", service, realm.getName()); throw new ErrorResponseException("invalid_client", "Client specified by 'service' parameter does not exist", Response.Status.BAD_REQUEST); } scope = params.getFirst(DockerAuthV2Protocol.SCOPE_PARAM); checkSsl(); checkRealm(); final AuthorizationEndpointRequest authRequest = AuthorizationEndpointRequestParserProcessor.parseRequest(event, session, client, params); authenticationSession = createAuthenticationSession(client, authRequest.getState()); updateAuthenticationSession(); // So back button doesn't work CacheControlUtil.noBackButtonCacheControlHeader(); return handleBrowserAuthenticationRequest(authenticationSession, new DockerAuthV2Protocol(session, realm, session.getContext().getUri(), headers, event.event(login)), false, false); }
Example 10
Source File: RegistrationUserCreation.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void success(FormContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); String email = formData.getFirst(Validation.FIELD_EMAIL); String username = formData.getFirst(RegistrationPage.FIELD_USERNAME); if (context.getRealm().isRegistrationEmailAsUsername()) { username = formData.getFirst(RegistrationPage.FIELD_EMAIL); } context.getEvent().detail(Details.USERNAME, username) .detail(Details.REGISTER_METHOD, "form") .detail(Details.EMAIL, email) ; UserModel user = context.getSession().users().addUser(context.getRealm(), username); user.setEnabled(true); user.setEmail(email); context.getAuthenticationSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, username); AttributeFormDataProcessor.process(formData, context.getRealm(), user); context.setUser(user); context.getEvent().user(user); context.getEvent().success(); context.newEvent().event(EventType.LOGIN); context.getEvent().client(context.getAuthenticationSession().getClient().getClientId()) .detail(Details.REDIRECT_URI, context.getAuthenticationSession().getRedirectUri()) .detail(Details.AUTH_METHOD, context.getAuthenticationSession().getProtocol()); String authType = context.getAuthenticationSession().getAuthNote(Details.AUTH_TYPE); if (authType != null) { context.getEvent().detail(Details.AUTH_TYPE, authType); } }
Example 11
Source File: BulkExtractTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Test public void testEdOrgFullExtract() throws IOException, ParseException { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); Entity mockedEntity = mockBulkExtractEntity(null); Mockito.when(edOrgHelper.byId(eq("ONE"))).thenReturn(mockedEntity); Map<String, Object> authBody = new HashMap<String, Object>(); authBody.put("applicationId", "App1"); authBody.put(ApplicationAuthorizationResource.EDORG_IDS, ApplicationAuthorizationResourceTest.getAuthList("ONE")); Entity mockAppAuth = Mockito.mock(Entity.class); Mockito.when(mockAppAuth.getBody()).thenReturn(authBody); Mockito.when(mockMongoEntityRepository.findOne(eq("applicationAuthorization"), Mockito.any(NeutralQuery.class))) .thenReturn(mockAppAuth); Response res = bulkExtract.getEdOrgExtract(CONTEXT, req, "ONE"); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf(INPUT_FILE_NAME) > 0); Object entity = res.getEntity(); assertNotNull(entity); StreamingOutput out = (StreamingOutput) entity; ByteArrayOutputStream os = new ByteArrayOutputStream(); out.write(os); os.flush(); byte[] responseData = os.toByteArray(); String s = new String(responseData); assertEquals(BULK_DATA, s); }
Example 12
Source File: BulkExtractTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Test public void testHeadTenant() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext context = new HttpRequestContextAdapter() { @Override public String getMethod() { return "HEAD"; } }; Response res = bulkExtract.getEdOrgExtractResponse(context, null, null); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf(INPUT_FILE_NAME) > 0); Object entity = res.getEntity(); assertNull(entity); }
Example 13
Source File: SAMLEndpoint.java From keycloak with Apache License 2.0 | 5 votes |
@Override protected boolean containsUnencryptedSignature(SAMLDocumentHolder documentHolder) { MultivaluedMap<String, String> encodedParams = session.getContext().getUri().getQueryParameters(false); String algorithm = encodedParams.getFirst(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY); String signature = encodedParams.getFirst(GeneralConstants.SAML_SIGNATURE_REQUEST_KEY); return algorithm != null && signature != null; }
Example 14
Source File: MetricsRestServiceImpl.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
protected void applyQueryParams(MetricsQuery query, MultivaluedMap<String, String> queryParameters) { DateConverter dateConverter = new DateConverter(); dateConverter.setObjectMapper(objectMapper); if(queryParameters.getFirst(QUERY_PARAM_START_DATE) != null) { Date startDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_START_DATE)); query.startDate(startDate); } if(queryParameters.getFirst(QUERY_PARAM_END_DATE) != null) { Date endDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_END_DATE)); query.endDate(endDate); } IntegerConverter intConverter = new IntegerConverter(); intConverter.setObjectMapper(objectMapper); if (queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT) != null) { int firstResult = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT)); query.offset(firstResult); } if (queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS) != null) { int maxResults = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS)); query.limit(maxResults); } if(queryParameters.getFirst(QUERY_PARAM_AGG_BY_REPORTER) != null) { query.aggregateByReporter(); } }
Example 15
Source File: ConsoleUpdatePassword.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void processAction(RequiredActionContext context) { EventBuilder event = context.getEvent(); MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); event.event(EventType.UPDATE_PASSWORD); String passwordNew = formData.getFirst(PASSWORD_NEW); String passwordConfirm = formData.getFirst(PASSWORD_CONFIRM); EventBuilder errorEvent = event.clone().event(EventType.UPDATE_PASSWORD_ERROR) .client(context.getAuthenticationSession().getClient()) .user(context.getAuthenticationSession().getAuthenticatedUser()); if (Validation.isBlank(passwordNew)) { context.challenge(challenge(context).message(Messages.MISSING_PASSWORD)); errorEvent.error(Errors.PASSWORD_MISSING); return; } else if (!passwordNew.equals(passwordConfirm)) { context.challenge(challenge(context).message(Messages.NOTMATCH_PASSWORD)); errorEvent.error(Errors.PASSWORD_CONFIRM_ERROR); return; } try { context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), UserCredentialModel.password(passwordNew, false)); context.success(); } catch (ModelException me) { errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED); context.challenge(challenge(context).text(me.getMessage())); return; } catch (Exception ape) { errorEvent.detail(Details.REASON, ape.getMessage()).error(Errors.PASSWORD_REJECTED); context.challenge(challenge(context).text(ape.getMessage())); return; } }
Example 16
Source File: RegistrationPassword.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void success(FormContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); String password = formData.getFirst(RegistrationPage.FIELD_PASSWORD); UserModel user = context.getUser(); try { context.getSession().userCredentialManager().updateCredential(context.getRealm(), user, UserCredentialModel.password(formData.getFirst("password"), false)); } catch (Exception me) { user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); } }
Example 17
Source File: AccountFormService.java From keycloak with Apache License 2.0 | 4 votes |
/** * Update account information. * <p> * Form params: * <p> * firstName * lastName * email * * @param formData * @return */ @Path("/") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response processAccountUpdate(final MultivaluedMap<String, String> formData) { if (auth == null) { return login(null); } auth.require(AccountRoles.MANAGE_ACCOUNT); String action = formData.getFirst("submitAction"); if (action != null && action.equals("Cancel")) { setReferrerOnPage(); return account.createResponse(AccountPages.ACCOUNT); } csrfCheck(formData); UserModel user = auth.getUser(); event.event(EventType.UPDATE_PROFILE).client(auth.getClient()).user(auth.getUser()); List<FormMessage> errors = Validation.validateUpdateProfileForm(realm, formData); if (errors != null && !errors.isEmpty()) { setReferrerOnPage(); return account.setErrors(Status.OK, errors).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT); } try { updateUsername(formData.getFirst("username"), user, session); updateEmail(formData.getFirst("email"), user, session, event); user.setFirstName(formData.getFirst("firstName")); user.setLastName(formData.getFirst("lastName")); AttributeFormDataProcessor.process(formData, realm, user); event.success(); setReferrerOnPage(); return account.setSuccess(Messages.ACCOUNT_UPDATED).createResponse(AccountPages.ACCOUNT); } catch (ReadOnlyException roe) { setReferrerOnPage(); return account.setError(Response.Status.BAD_REQUEST, Messages.READ_ONLY_USER).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT); } catch (ModelDuplicateException mde) { setReferrerOnPage(); return account.setError(Response.Status.CONFLICT, mde.getMessage()).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT); } }
Example 18
Source File: TokenSecurityContextFilter.java From openscoring with GNU Affero General Public License v3.0 | 4 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { SecurityContext requestSecurityContext = requestContext.getSecurityContext(); SecurityContext securityContext = new SecurityContext(){ @Override public Principal getUserPrincipal(){ return Anonymous.INSTANCE; } @Override public boolean isUserInRole(String role){ String token = getToken(); String roleToken; switch(role){ case Roles.USER: roleToken = getUserToken(); break; case Roles.ADMIN: roleToken = getAdminToken(); break; default: return false; } return (roleToken).equals(token) || (roleToken).equals(""); } @Override public boolean isSecure(){ return requestSecurityContext != null && requestSecurityContext.isSecure(); } @Override public String getAuthenticationScheme(){ return "TOKEN"; } private String getToken(){ Map<String, Cookie> cookies = requestContext.getCookies(); MultivaluedMap<String, String> headers = requestContext.getHeaders(); Cookie tokenCookie = cookies.get("token"); if(tokenCookie != null){ return tokenCookie.getValue(); } String authorizationHeader = headers.getFirst(HttpHeaders.AUTHORIZATION); if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")){ return authorizationHeader.substring("Bearer ".length()); } return null; } }; requestContext.setSecurityContext(securityContext); }
Example 19
Source File: LogoutEndpoint.java From keycloak with Apache License 2.0 | 4 votes |
/** * Logout a session via a non-browser invocation. Similar signature to refresh token except there is no grant_type. * You must pass in the refresh token and * authenticate the client if it is not public. * * If the client is a confidential client * you must include the client-id and secret in an Basic Auth Authorization header. * * If the client is a public client, then you must include a "client_id" form parameter. * * returns 204 if successful, 400 if not with a json error response. * * @return */ @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response logoutToken() { MultivaluedMap<String, String> form = request.getDecodedFormParameters(); checkSsl(); event.event(EventType.LOGOUT); ClientModel client = authorizeClient(); String refreshToken = form.getFirst(OAuth2Constants.REFRESH_TOKEN); if (refreshToken == null) { event.error(Errors.INVALID_TOKEN); throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "No refresh token", Response.Status.BAD_REQUEST); } RefreshToken token = null; try { // KEYCLOAK-6771 Certificate Bound Token token = tokenManager.verifyRefreshToken(session, realm, client, request, refreshToken, false); boolean offline = TokenUtil.TOKEN_TYPE_OFFLINE.equals(token.getType()); UserSessionModel userSessionModel; if (offline) { UserSessionManager sessionManager = new UserSessionManager(session); userSessionModel = sessionManager.findOfflineUserSession(realm, token.getSessionState()); } else { userSessionModel = session.sessions().getUserSession(realm, token.getSessionState()); } if (userSessionModel != null) { checkTokenIssuedAt(token, userSessionModel); logout(userSessionModel, offline); } } catch (OAuthErrorException e) { // KEYCLOAK-6771 Certificate Bound Token if (MtlsHoKTokenUtil.CERT_VERIFY_ERROR_DESC.equals(e.getDescription())) { event.error(Errors.NOT_ALLOWED); throw new ErrorResponseException(e.getError(), e.getDescription(), Response.Status.UNAUTHORIZED); } else { event.error(Errors.INVALID_TOKEN); throw new ErrorResponseException(e.getError(), e.getDescription(), Response.Status.BAD_REQUEST); } } return Cors.add(request, Response.noContent()).auth().allowedOrigins(session, client).allowedMethods("POST").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build(); }
Example 20
Source File: RefreshTokenGrantTypeHandler.java From tutorials with MIT License | 4 votes |
@Override public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception { String refreshToken = params.getFirst("refresh_token"); if (refreshToken == null || "".equals(refreshToken)) { throw new WebApplicationException("invalid_grant"); } //Decode refresh token SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken); JWSVerifier verifier = getJWSVerifier(); if (!signedRefreshToken.verify(verifier)) { throw new WebApplicationException("Invalid refresh token."); } if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) { throw new WebApplicationException("Refresh token expired."); } String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id"); if (!clientId.equals(refreshTokenClientId)) { throw new WebApplicationException("Invalid client_id."); } //At this point, the refresh token is valid and not yet expired //So create a new access token from it. String subject = signedRefreshToken.getJWTClaimsSet().getSubject(); String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope"); String requestedScopes = params.getFirst("scope"); if (requestedScopes != null && !requestedScopes.isEmpty()) { Set<String> rScopes = new HashSet(Arrays.asList(requestedScopes.split(" "))); Set<String> aScopes = new HashSet(Arrays.asList(approvedScopes.split(" "))); if (!aScopes.containsAll(rScopes)) { JsonObject error = Json.createObjectBuilder() .add("error", "Invalid_request") .add("error_description", "Requested scopes should be a subset of the original scopes.") .build(); Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build(); throw new WebApplicationException(response); } } else { requestedScopes = approvedScopes; } String accessToken = getAccessToken(clientId, subject, requestedScopes); return Json.createObjectBuilder() .add("token_type", "Bearer") .add("access_token", accessToken) .add("expires_in", expiresInMin * 60) .add("scope", requestedScopes) .add("refresh_token", refreshToken) .build(); }