@Override public U generate(final WebContext context, final U profile) { final String rmeValue = context.getRequestParameter(rememberMeParameterName); if (rememberMeValue.equals(rmeValue)) { profile.setRemembered(true); } return profile; }
/** * Gets client id and client secret. * * @param context the context * @return the client id and client secret */ protected Pair<String, String> getClientIdAndClientSecret(final WebContext context) { val extractor = new BasicAuthExtractor(); val upc = extractor.extract(context); if (upc != null) { return Pair.of(upc.getUsername(), upc.getPassword()); } val clientId = context.getRequestParameter(OAuth20Constants.CLIENT_ID); val clientSecret = context.getRequestParameter(OAuth20Constants.CLIENT_SECRET); return Pair.of(clientId, clientSecret); } }
protected byte[] getBase64DecodedMessage() throws MessageDecodingException { String encodedMessage = null; for (final String parameter : SAML_PARAMETERS) { encodedMessage = this.context.getRequestParameter(parameter); if (CommonHelper.isNotBlank(encodedMessage)) { break; } } if (Strings.isNullOrEmpty(encodedMessage)) { encodedMessage = this.context.getRequestContent(); } if (Strings.isNullOrEmpty(encodedMessage)) { throw new MessageDecodingException("Request did not contain either a SAMLRequest parameter, a SAMLResponse parameter, " + "a logoutRequest parameter or a body content"); } else { if (encodedMessage.contains("<")) { logger.trace("Raw SAML message:\n{}", encodedMessage); return encodedMessage.getBytes(StandardCharsets.UTF_8); } else { final byte[] decodedBytes = Base64Support.decode(encodedMessage); logger.trace("Decoded SAML message:\n{}", new String(decodedBytes, StandardCharsets.UTF_8)); return decodedBytes; } } }
@Override protected void clientInit() { configuration.setApi(new OrcidApi20()); configuration.setProfileDefinition(new OrcidProfileDefinition()); configuration.setTokenAsHeader(true); configuration.setHasBeenCancelledFactory(ctx -> { final String error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); final String errorDescription = ctx.getRequestParameter(OAuthCredentialsException.ERROR_DESCRIPTION); // user has denied permissions if ("access_denied".equals(error) && "User denied access".equals(errorDescription)) { return true; } else { return false; } }); super.clientInit(); }
@Override protected OAuth10Credentials getOAuthCredentials(final WebContext context) { final String tokenParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_TOKEN); final String verifierParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_VERIFIER); if (tokenParameter != null && verifierParameter != null) { // get request token from session final OAuth1RequestToken tokenSession = (OAuth1RequestToken) context .getSessionStore().get(context, configuration.getRequestTokenSessionAttributeName(client.getName())); logger.debug("tokenRequest: {}", tokenSession); final String token = OAuthEncoder.decode(tokenParameter); final String verifier = OAuthEncoder.decode(verifierParameter); logger.debug("token: {} / verifier: {}", token, verifier); return new OAuth10Credentials(tokenSession, token, verifier); } else { final String message = "No credential found"; throw new OAuthCredentialsException(message); } } }
public void destroySession(WebContext context) { final PlayWebContext webContext = (PlayWebContext) context; final String logoutRequest = context.getRequestParameter("logoutRequest"); logger.debug("logoutRequest: {}", logoutRequest); final String ticket = StringUtils.substringBetween(logoutRequest, "SessionIndex>", "</"); logger.debug("extract ticket: {}", ticket); final String sessionId = (String) Cache.get(ticket); Cache.remove(ticket); webContext.getJavaSession().put(Pac4jConstants.SESSION_ID, sessionId); final ProfileManager profileManager = new ProfileManager(webContext); profileManager.remove(true); }
@Override protected void clientInit() { configuration.setApi(HiOrgServerApi20.instance()); configuration.setProfileDefinition(new HiOrgServerProfileDefinition()); configuration.setHasBeenCancelledFactory(ctx -> { final String error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); final String errorDescription = ctx.getRequestParameter(OAuthCredentialsException.ERROR_DESCRIPTION); // user has denied permissions if ("access_denied".equals(error)) { logger.debug(errorDescription); return true; } else { return false; } }); configuration.setWithState(true); defaultLogoutActionBuilder((ctx, profile, targetUrl) -> RedirectAction.redirect(LOGOUT_URL)); super.clientInit(); }
@Override protected void validateCredentials(final UsernamePasswordCredentials credentials, final OAuthRegisteredService registeredService, final WebContext context) { val codeVerifier = credentials.getPassword(); val code = context.getRequestParameter(OAuth20Constants.CODE); val token = this.ticketRegistry.getTicket(code, OAuthCode.class); if (token == null || token.isExpired()) { LOGGER.error("Provided code [{}] is either not found in the ticket registry or has expired", code); throw new CredentialsException("Invalid token: " + code); } val method = StringUtils.defaultString(token.getCodeChallengeMethod(), "plain"); val hash = calculateCodeVerifierHash(method, codeVerifier); if (!hash.equalsIgnoreCase(token.getCodeChallenge())) { LOGGER.error("Code verifier [{}] does not match the challenge [{}]", hash, token.getCodeChallenge()); throw new CredentialsException("Code verification does not match the challenge assigned to: " + token.getId()); } LOGGER.debug("Validated code verifier using verification method [{}]", method); }
@Override public C extract(final WebContext context) { final boolean hasBeenCancelled = (Boolean) configuration.getHasBeenCancelledFactory().apply(context); // check if the authentication has been cancelled if (hasBeenCancelled) { logger.debug("authentication has been cancelled by user"); return null; } // check errors try { boolean errorFound = false; final OAuthCredentialsException oauthCredentialsException = new OAuthCredentialsException("Failed to retrieve OAuth credentials, error parameters found"); for (final String key : OAuthCredentialsException.ERROR_NAMES) { final String value = context.getRequestParameter(key); if (value != null) { errorFound = true; oauthCredentialsException.setErrorMessage(key, value); } } if (errorFound) { throw oauthCredentialsException; } else { return getOAuthCredentials(context); } } catch (final OAuthException e) { throw new TechnicalException(e); } }
@Override protected void clientInit() { CommonHelper.assertNotBlank("fields", getConfiguration().getFields()); configuration.setApi(FacebookApi.instance()); configuration.setProfileDefinition(new FacebookProfileDefinition()); configuration.setHasBeenCancelledFactory(ctx -> { final String error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); final String errorReason = ctx.getRequestParameter(OAuthCredentialsException.ERROR_REASON); // user has denied permissions if ("access_denied".equals(error) && "user_denied".equals(errorReason)) { return true; } else { return false; } }); configuration.setWithState(true); defaultProfileCreator(new FacebookProfileCreator(configuration, this)); super.clientInit(); }
if (configuration.isWithState()) { final String stateParameter = context.getRequestParameter(OAuth20Configuration.STATE_REQUEST_PARAMETER); final String codeParameter = context.getRequestParameter(OAuth20Configuration.OAUTH_CODE); if (codeParameter != null) { final String code = OAuthEncoder.decode(codeParameter);
@Override protected void clientInit() { CommonHelper.assertNotBlank("scope", getConfiguration().getScope()); CommonHelper.assertNotBlank("fields", getConfiguration().getFields()); configuration.setApi(LinkedInApi20.instance()); configuration.setProfileDefinition(new LinkedIn2ProfileDefinition()); configuration.setWithState(true); configuration.setHasBeenCancelledFactory(ctx -> { final String error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); final String errorDescription = ctx.getRequestParameter(OAuthCredentialsException.ERROR_DESCRIPTION); // user has denied permissions if ("access_denied".equals(error) && ("the+user+denied+your+request".equals(errorDescription) || "the user denied your request" .equals(errorDescription))) { return true; } else { return false; } }); defaultLogoutActionBuilder((ctx, profile, targetUrl) -> RedirectAction.redirect("https://www.linkedin.com/uas/logout")); super.clientInit(); }
@Override protected void clientInit() { CommonHelper.assertNotNull("scope", this.scope); if (this.scope == null) this.scope = WeiboScope.EMAIL; this.scopeValue = this.scope.toString().toLowerCase(); configuration.setApi(new WeiboApi20()); configuration.setScope(scopeValue); configuration.setProfileDefinition(new WeiboProfileDefinition()); configuration.setWithState(true); configuration.setHasBeenCancelledFactory(ctx -> { final String error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); if ("access_denied".equals(error)) { return true; } return false; }); super.clientInit(); }
@Override protected void doDecode() throws MessageDecodingException { final SAML2MessageContext messageContext = new SAML2MessageContext(); if (ContextHelper.isPost(context)) { final String relayState = this.context.getRequestParameter("RelayState"); logger.debug("Decoded SAML relay state of: {}", relayState); SAMLBindingSupport.setRelayState(messageContext, relayState); final byte[] base64DecodedMessage = this.getBase64DecodedMessage(); final XMLObject xmlObject = this.unmarshallMessage(new ByteArrayInputStream(base64DecodedMessage)); final SAMLObject inboundMessage; if (xmlObject instanceof Envelope) { Envelope soapMessage = (Envelope) xmlObject; messageContext.getSOAP11Context().setEnvelope(soapMessage); try { new SAMLSOAPDecoderBodyHandler().invoke(messageContext); } catch (final MessageHandlerException e) { throw new MessageDecodingException("Cannot decode SOAP envelope", e); } } else { inboundMessage = (SAMLObject) xmlObject; messageContext.setMessage(inboundMessage); } logger.debug("Decoded SAML message"); this.populateBindingContext(messageContext); this.setMessageContext(messageContext); } else { throw new MessageDecodingException("This message decoder only supports the HTTP POST method"); } }
val redirectUri = context.getRequestParameter(OAuth20Constants.REDIRECT_URI); val service = StringUtils.isNotBlank(redirectUri) ? this.webApplicationServiceFactory.createService(redirectUri)
@Override protected void clientInit() { configuration.setApi(getApi()); configuration.setProfileDefinition(new TwitterProfileDefinition(includeEmail)); configuration.setHasBeenCancelledFactory(ctx -> { final String denied = ctx.getRequestParameter("denied"); if (CommonHelper.isNotBlank(denied)) { return true; } else { return false; } }); defaultLogoutActionBuilder((ctx, profile, targetUrl) -> RedirectAction.redirect("https://twitter.com/logout")); super.clientInit(); }
@Override protected UsernamePasswordCredentials retrieveCredentials(final WebContext context) { CommonHelper.assertNotNull("credentialsExtractor", getCredentialsExtractor()); CommonHelper.assertNotNull("authenticator", getAuthenticator()); final String username = context.getRequestParameter(this.usernameParameter); UsernamePasswordCredentials credentials; try { // retrieve credentials credentials = getCredentialsExtractor().extract(context); logger.debug("usernamePasswordCredentials: {}", credentials); if (credentials == null) { throw handleInvalidCredentials(context, username, "Username and password cannot be blank -> return to the form with error", MISSING_FIELD_ERROR); } // validate credentials getAuthenticator().validate(credentials, context); } catch (final CredentialsException e) { throw handleInvalidCredentials(context, username, "Credentials validation fails -> return to the form with error", computeErrorMessage(e)); } return credentials; }
public Result logout() { CommonHelper.assertNotBlank(Pac4jConstants.DEFAULT_URL, this.defaultUrl); CommonHelper.assertNotBlank(Pac4jConstants.LOGOUT_URL_PATTERN, this.logoutUrlPattern); final WebContext context = new PlayWebContext(ctx(), config.getSessionStore()); final ProfileManager manager = new ProfileManager(context); manager.logout(); ctx().session().remove(Pac4jConstants.SESSION_ID); final String url = context.getRequestParameter(Pac4jConstants.URL); if (url == null) { return ok(); } else { if (Pattern.matches(this.logoutUrlPattern, url)) { return redirect(url); } else { return redirect(this.defaultUrl); } } }
@Override protected void clientInit() { CommonHelper.assertNotNull("scope", this.scope); final String scopeValue; if (this.scope == Google2Scope.EMAIL) { scopeValue = this.EMAIL_SCOPE; } else if (this.scope == Google2Scope.PROFILE) { scopeValue = this.PROFILE_SCOPE; } else { scopeValue = this.PROFILE_SCOPE + " " + this.EMAIL_SCOPE; } configuration.setApi(GoogleApi20.instance()); configuration.setProfileDefinition(new Google2ProfileDefinition()); configuration.setScope(scopeValue); configuration.setWithState(true); configuration.setHasBeenCancelledFactory(ctx -> { final String error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); // user has denied permissions if ("access_denied".equals(error)) { return true; } return false; }); defaultLogoutActionBuilder(new GoogleLogoutActionBuilder<>()); super.clientInit(); }
@Override public SAML2Credentials extract(final WebContext context) { final boolean logoutEndpoint = context.getRequestParameter(SAML2ServiceProviderMetadataResolver.LOGOUT_ENDPOINT_PARAMETER) != null; final SAML2MessageContext samlContext = this.contextProvider.buildContext(context); if (logoutEndpoint) { // SAML logout request/response this.logoutProfileHandler.receive(samlContext); // return a logout response if necessary final LogoutResponse logoutResponse = this.saml2LogoutResponseBuilder.build(samlContext); this.saml2LogoutResponseMessageSender.sendMessage(samlContext, logoutResponse, samlContext.getSAMLBindingContext().getRelayState()); final Pac4jSAMLResponse adapter = samlContext.getProfileRequestContextOutboundMessageTransportResponse(); if (spLogoutResponseBindingType.equalsIgnoreCase(SAMLConstants.SAML2_POST_BINDING_URI)) { final String content = adapter.getOutgoingContent(); throw HttpAction.ok(context, content); } else { final String location = adapter.getRedirectUrl(); throw HttpAction.redirect(context, location); } } else { // SAML authn response final SAML2Credentials credentials = (SAML2Credentials) this.profileHandler.receive(samlContext); return credentials; } }