org.opensaml.messaging.context.MessageContext Java Examples

The following examples show how to use org.opensaml.messaging.context.MessageContext. 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: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
public String handleSsoGetRequestBase(HttpRequest request) {
    try {

        HttpServletRequest httpServletRequest = new FakeHttpServletRequest(request);

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();
        decoder.setParserPool(XMLObjectProviderRegistrySupport.getParserPool());
        decoder.setHttpServletRequest(httpServletRequest);
        decoder.initialize();
        decoder.decode();

        MessageContext<SAMLObject> messageContext = decoder.getMessageContext();

        if (!(messageContext.getMessage() instanceof AuthnRequest)) {
            throw new RuntimeException("Expected AuthnRequest; received: " + messageContext.getMessage());
        }

        AuthnRequest authnRequest = (AuthnRequest) messageContext.getMessage();

        return createSamlAuthResponse(authnRequest);
    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: SamlAuthSsoHandler.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public CompletionStage<Void> beforeInitiatingSso(ServiceRequestContext ctx, HttpRequest req,
                                                 MessageContext<AuthnRequest> message,
                                                 SamlIdentityProviderConfig idpConfig) {
    final QueryStringDecoder decoder = new QueryStringDecoder(req.path(), true);
    final List<String> ref = decoder.parameters().get("ref");
    if (ref == null || ref.isEmpty()) {
        return CompletableFuture.completedFuture(null);
    }

    final String relayState = ref.get(0);
    if (idpConfig.ssoEndpoint().bindingProtocol() == SamlBindingProtocol.HTTP_REDIRECT &&
        relayState.length() > 80) {
        return CompletableFuture.completedFuture(null);
    }

    final SAMLBindingContext sub = message.getSubcontext(SAMLBindingContext.class, true);
    assert sub != null : SAMLBindingContext.class.getName();
    sub.setRelayState(relayState);
    return CompletableFuture.completedFuture(null);
}
 
Example #3
Source File: MyAuthHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked when the SAML authentication process is finished and a user is authenticated. You can get
 * information about the authenticated user from the {@link Response}, especially his or her login name.
 * In this example, an email address is used as a login name. The login name is transferred to a web
 * browser via {@code Set-Cookie} header.
 */
@Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                   MessageContext<Response> message, @Nullable String sessionIndex,
                                   @Nullable String relayState) {
    final NameID nameId = getNameId(message.getMessage(), SamlNameIdFormat.EMAIL);
    final String username = nameId != null ? nameId.getValue() : null;
    if (username == null) {
        return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8,
                               "<html><body>Username is not found.</body></html>");
    }

    logger.info("{} user '{}' has been logged in.", ctx, username);

    final Cookie cookie = Cookie.builder("username", username)
                                .httpOnly(true)
                                .domain("localhost")
                                .maxAge(60)
                                .path("/")
                                .build();
    return HttpResponse.of(
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.HTML_UTF_8,
                               HttpHeaderNames.SET_COOKIE, cookie.toSetCookieHeader(false)),
            HttpData.ofUtf8("<html><body onLoad=\"window.location.href='/welcome'\"></body></html>"));
}
 
Example #4
Source File: HttpPostBindingUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an {@link AggregatedHttpRequest} which is received from the remote entity to
 * a {@link SAMLObject}.
 */
static <T extends SAMLObject> MessageContext<T> toSamlObject(AggregatedHttpRequest req, String name) {
    final SamlParameters parameters = new SamlParameters(req);
    final byte[] decoded;
    try {
        decoded = Base64.getMimeDecoder().decode(parameters.getFirstValue(name));
    } catch (IllegalArgumentException e) {
        throw new InvalidSamlRequestException(
                "failed to decode a base64 string of the parameter: " + name, e);
    }

    @SuppressWarnings("unchecked")
    final T message = (T) deserialize(decoded);

    final MessageContext<T> messageContext = new MessageContext<>();
    messageContext.setMessage(message);

    final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
    if (relayState != null) {
        final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
        assert context != null;
        context.setRelayState(relayState);
    }

    return messageContext;
}
 
Example #5
Source File: Saml10ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Encode response and pass it onto the outbound transport.
 * Uses {@link CasHTTPSOAP11Encoder} to handle encoding.
 *
 * @param httpResponse the http response
 * @param httpRequest the http request
 * @param samlMessage the saml response
 * @throws Exception the exception in case encoding fails.
 */
public void encodeSamlResponse(final HttpServletResponse httpResponse,
                               final HttpServletRequest httpRequest,
                               final Response samlMessage) throws Exception {

    final HTTPSOAP11Encoder encoder = new CasHTTPSOAP11Encoder();
    final MessageContext<SAMLObject> context = new MessageContext();
    context.setMessage(samlMessage);
    encoder.setHttpServletResponse(httpResponse);
    encoder.setMessageContext(context);
    encoder.initialize();
    encoder.prepareContext();
    encoder.encode();
}
 
Example #6
Source File: SamlAuthSsoHandler.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                   MessageContext<Response> message, @Nullable String sessionIndex,
                                   @Nullable String relayState) {
    final Response response = requireNonNull(message, "message").getMessage();
    final String username = Optional.ofNullable(findLoginNameFromSubjects(response))
                                    .orElseGet(() -> findLoginNameFromAttributes(response));
    if (Strings.isNullOrEmpty(username)) {
        return loginFailed(ctx, req, message,
                           new IllegalStateException("Cannot get a username from the response"));
    }

    final String sessionId = sessionIdGenerator.get();
    final Session session =
            new Session(sessionId, loginNameNormalizer.apply(username), sessionValidDuration);

    final String redirectionScript;
    if (!Strings.isNullOrEmpty(relayState)) {
        redirectionScript = "window.location.href='/#" + relayState + '\'';
    } else {
        redirectionScript = "window.location.href='/'";
    }
    return HttpResponse.from(loginSessionPropagator.apply(session).thenApply(
            unused -> HttpResponse.of(HttpStatus.OK, MediaType.HTML_UTF_8, getHtmlWithOnload(
                    "localStorage.setItem('sessionId','" + sessionId + "')",
                    redirectionScript))));
}
 
Example #7
Source File: SamlAuthSsoHandler.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse loginFailed(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                @Nullable MessageContext<Response> message, Throwable cause) {
    final HttpStatus status =
            cause instanceof InvalidSamlRequestException ? HttpStatus.BAD_REQUEST
                                                         : HttpStatus.INTERNAL_SERVER_ERROR;
    return HttpApiUtil.newResponse(ctx, status, cause);
}
 
Example #8
Source File: AuthenticationHandlerSAML2.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private boolean validateRelayState(HttpServletRequest req, MessageContext messageContext) {
    SAMLBindingContext bindingContext = messageContext.getSubcontext(SAMLBindingContext.class, true);
    String reportedRelayState = bindingContext.getRelayState();
    SessionStorage relayStateStore = new SessionStorage(saml2ConfigService.getSaml2SessionAttr());
    String savedRelayState = relayStateStore.getString(req);
    if (savedRelayState == null || savedRelayState.isEmpty()){
        return false;
    } else if (savedRelayState.equals(reportedRelayState)){
        return true;
    }
    return false;
}
 
Example #9
Source File: MyAuthHandler.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked when a single sign-on request is rejected from the identity provider.
 */
@Override
public HttpResponse loginFailed(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                @Nullable MessageContext<Response> message, Throwable cause) {
    return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8,
                           "<html><body>Login failed.</body></html>");
}
 
Example #10
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                   MessageContext<Response> message, @Nullable String sessionIndex,
                                   @Nullable String relayState) {
    return HttpResponse.of(headersWithLocation(firstNonNull(relayState, "/"))
                                   .toBuilder()
                                   .add(HttpHeaderNames.SET_COOKIE, setCookie)
                                   .build());
}
 
Example #11
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Void> beforeInitiatingSso(ServiceRequestContext ctx, HttpRequest req,
                                                 MessageContext<AuthnRequest> message,
                                                 SamlIdentityProviderConfig idpConfig) {
    message.getSubcontext(SAMLBindingContext.class, true)
           .setRelayState(req.path());
    return CompletableFuture.completedFuture(null);
}
 
Example #12
Source File: SamlAssertionConsumerFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, AggregatedHttpRequest req,
                          String defaultHostname, SamlPortConfig portConfig) {
    try {
        final MessageContext<Response> messageContext;
        if (cfg.endpoint().bindingProtocol() == SamlBindingProtocol.HTTP_REDIRECT) {
            messageContext = HttpRedirectBindingUtil.toSamlObject(req, SAML_RESPONSE,
                                                                  idpConfigs, defaultIdpConfig);
        } else {
            messageContext = HttpPostBindingUtil.toSamlObject(req, SAML_RESPONSE);
        }

        final String endpointUri = cfg.endpoint().toUriString(portConfig.scheme().uriText(),
                                                              defaultHostname, portConfig.port());
        final Response response = messageContext.getMessage();
        final Assertion assertion = getValidatedAssertion(response, endpointUri);

        // Find a session index which is sent by an identity provider.
        final String sessionIndex = assertion.getAuthnStatements().stream()
                                             .map(AuthnStatement::getSessionIndex)
                                             .filter(Objects::nonNull)
                                             .findFirst().orElse(null);

        final SAMLBindingContext bindingContext = messageContext.getSubcontext(SAMLBindingContext.class);
        final String relayState = bindingContext != null ? bindingContext.getRelayState() : null;

        return ssoHandler.loginSucceeded(ctx, req, messageContext, sessionIndex, relayState);
    } catch (SamlException e) {
        return ssoHandler.loginFailed(ctx, req, null, e);
    }
}
 
Example #13
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void handleSloGetRequestBase(HttpRequest request) {
    try {

        HttpServletRequest httpServletRequest = new FakeHttpServletRequest(request);

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();
        decoder.setParserPool(XMLObjectProviderRegistrySupport.getParserPool());
        decoder.setHttpServletRequest(httpServletRequest);
        decoder.initialize();
        decoder.decode();

        MessageContext<SAMLObject> messageContext = decoder.getMessageContext();

        if (!(messageContext.getMessage() instanceof LogoutRequest)) {
            throw new RuntimeException("Expected LogoutRequest; received: " + messageContext.getMessage());
        }

        LogoutRequest logoutRequest = (LogoutRequest) messageContext.getMessage();

        SAML2HTTPRedirectDeflateSignatureSecurityHandler signatureSecurityHandler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
        SignatureValidationParameters validationParams = new SignatureValidationParameters();
        SecurityParametersContext securityParametersContext = messageContext
                .getSubcontext(SecurityParametersContext.class, true);

        SAMLPeerEntityContext peerEntityContext = messageContext.getSubcontext(SAMLPeerEntityContext.class, true);
        peerEntityContext.setEntityId(idpEntityId);
        peerEntityContext.setRole(org.opensaml.saml.saml2.metadata.SPSSODescriptor.DEFAULT_ELEMENT_NAME);

        SAMLProtocolContext protocolContext = messageContext.getSubcontext(SAMLProtocolContext.class, true);
        protocolContext.setProtocol(SAMLConstants.SAML20P_NS);

        validationParams.setSignatureTrustEngine(buildSignatureTrustEngine(this.spSignatureCertificate));
        securityParametersContext.setSignatureValidationParameters(validationParams);
        signatureSecurityHandler.setHttpServletRequest(httpServletRequest);
        signatureSecurityHandler.initialize();
        signatureSecurityHandler.invoke(messageContext);

        if (!this.authenticateUser.equals(logoutRequest.getNameID().getValue())) {
            throw new RuntimeException("Unexpected NameID in LogoutRequest: " + logoutRequest);
        }

    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException
            | MessageHandlerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse loginFailed(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                @Nullable MessageContext<Response> message, Throwable cause) {
    // Handle as an error so that a test client can detect the failure.
    return HttpResponse.of(HttpStatus.BAD_REQUEST);
}
 
Example #15
Source File: HttpRedirectBindingUtil.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Converts an {@link AggregatedHttpRequest} which is received from the remote entity to
 * a {@link SAMLObject}.
 */
@SuppressWarnings("unchecked")
static <T extends SAMLObject> MessageContext<T> toSamlObject(
        AggregatedHttpRequest req, String name,
        Map<String, SamlIdentityProviderConfig> idpConfigs,
        @Nullable SamlIdentityProviderConfig defaultIdpConfig) {
    requireNonNull(req, "req");
    requireNonNull(name, "name");
    requireNonNull(idpConfigs, "idpConfigs");

    final SamlParameters parameters = new SamlParameters(req);
    final T message = (T) fromDeflatedBase64(parameters.getFirstValue(name));

    final MessageContext<T> messageContext = new MessageContext<>();
    messageContext.setMessage(message);

    final Issuer issuer;
    if (message instanceof RequestAbstractType) {
        issuer = ((RequestAbstractType) message).getIssuer();
    } else if (message instanceof StatusResponseType) {
        issuer = ((StatusResponseType) message).getIssuer();
    } else {
        throw new InvalidSamlRequestException(
                "invalid message type: " + message.getClass().getSimpleName());
    }

    // Use the default identity provider config if there's no issuer.
    final SamlIdentityProviderConfig config;
    if (issuer != null) {
        final String idpEntityId = issuer.getValue();
        config = idpConfigs.get(idpEntityId);
        if (config == null) {
            throw new InvalidSamlRequestException(
                    "a message from unknown identity provider: " + idpEntityId);
        }
    } else {
        if (defaultIdpConfig == null) {
            throw new InvalidSamlRequestException("failed to get an Issuer element");
        }
        config = defaultIdpConfig;
    }

    // If this message is sent via HTTP-redirect binding protocol, its signature parameter should
    // be validated.
    validateSignature(config.signingCredential(), parameters, name);

    final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
    if (relayState != null) {
        final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
        assert context != null;
        context.setRelayState(relayState);
    }

    return messageContext;
}
 
Example #16
Source File: SamlDecorator.java    From armeria with Apache License 2.0 4 votes vote down vote up
private MessageContextAndIdpConfig(MessageContext<AuthnRequest> messageContext,
                                   SamlIdentityProviderConfig idpConfig) {
    this.messageContext = messageContext;
    this.idpConfig = idpConfig;
}
 
Example #17
Source File: AuthenticationHandlerSAML2.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
/**
     * Extracts session based credentials from the request. Returns
     * <code>null</code> if the secure user data is not present either in the HTTP Session.
     */
    @Override
    public AuthenticationInfo extractCredentials(final HttpServletRequest httpServletRequest,
                                                 final HttpServletResponse httpServletResponse)  {
// 1. If the request is POST to the ACS URL, it needs to extract the Auth Info from the SAML data POST'ed
        if (saml2ConfigService.getSaml2SPEnabled() ) {
            String reqURI = httpServletRequest.getRequestURI();
            if (reqURI.equals(saml2ConfigService.getAcsPath())){
                doClassloading();
                MessageContext messageContext = decodeHttpPostSamlResp(httpServletRequest);
                boolean relayStateIsOk = validateRelayState(httpServletRequest, messageContext);
                // If relay state from request = relay state from session))
                if (relayStateIsOk) {
                    Response response = (Response) messageContext.getMessage();
                    EncryptedAssertion encryptedAssertion = response.getEncryptedAssertions().get(0);
                    Assertion assertion = decryptAssertion(encryptedAssertion);
                    verifyAssertionSignature(assertion);
                    if (validateSaml2Conditions(httpServletRequest, assertion)){
                        logger.debug("Decrypted Assertion: ");
                        Helpers.logSAMLObject(assertion);
                        User extUser = doUserManagement(assertion);
                        AuthenticationInfo newAuthInfo = this.buildAuthInfo(extUser);
                        return newAuthInfo;
                    }
                    logger.error("Validation of SubjectConfirmation failed");
                }
                return null;
// 2.  try credentials from the session
            } else {
                // Request context is not the ACS path, so get the authInfo from session.
                String authData = authStorage.getString(httpServletRequest);
                if (authData != null) {
                    if (tokenStore.isValid(authData)) {
                        return buildAuthInfo(authData);
                    } else {
                        // clear the token from the session, its invalid and we should get rid of it
                        // so that the invalid cookie isn't present on the authN operation.
                        authStorage.clear(httpServletRequest, httpServletResponse);
                        if ( AuthUtil.isValidateRequest(httpServletRequest)) {
                            // signal the requestCredentials method a previous login failure
                            httpServletRequest.setAttribute(FAILURE_REASON, SamlReason.TIMEOUT);
                            return AuthenticationInfo.FAIL_AUTH;
                        }
                    }
                }
            }
        }
        return null;
    }
 
Example #18
Source File: SamlSingleLogoutHandler.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Invoked when the single logout request is succeeded. It can do the local logout using session indexes
 * containing in the {@link LogoutRequest}.
 *
 * @param ctx the {@link ServiceRequestContext} of {@code req}
 * @param req the {@link AggregatedHttpRequest} being handled
 * @param message the {@link MessageContext} of the {@link LogoutRequest} received from the identity
 */
CompletionStage<Void> logoutSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                      MessageContext<LogoutRequest> message);
 
Example #19
Source File: SamlSingleSignOnHandler.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Invoked when the single sign-on is failed. It should return an {@link HttpResponse} which sends
 * to the client in response to the incoming {@code req}. Sending an error HTML page is one of the
 * examples.
 *
 * @param ctx the {@link ServiceRequestContext} of {@code req}
 * @param req the {@link AggregatedHttpRequest} being handled
 * @param message the {@link MessageContext} of the {@link Response} received from the identity provider.
 *                {@code null} if the content of the {@code req} was failed to be parsed as a
 *                {@link Response} message.
 * @param cause the reason of the failure
 */
HttpResponse loginFailed(ServiceRequestContext ctx, AggregatedHttpRequest req,
                         @Nullable MessageContext<Response> message,
                         Throwable cause);
 
Example #20
Source File: SamlSingleSignOnHandler.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Invoked when the single sign-on is succeeded. It should return an {@link HttpResponse} which sends
 * to the client in response to the incoming {@code req}.
 *
 * @param ctx the {@link ServiceRequestContext} of {@code req}
 * @param req the {@link AggregatedHttpRequest} being handled
 * @param message the {@link MessageContext} of the {@link Response} received from the identity provider
 * @param sessionIndex the retrieved value from the {@link Response} message. {@code null} if it is omitted.
 * @param relayState the string which is sent with the {@link AuthnRequest} message and is returned
 *                   with the {@link Response} message. {@code null} if it is omitted.
 */
HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                            MessageContext<Response> message,
                            @Nullable String sessionIndex,
                            @Nullable String relayState);
 
Example #21
Source File: SamlSingleSignOnHandler.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Invoked before the service provider sends an authentication request to an identity provider.
 *
 * @param ctx the {@link ServiceRequestContext} of {@code req}
 * @param req the {@link Request} being handled
 * @param message the {@link MessageContext} of the {@link AuthnRequest} being sent to the identity
 *                provider
 * @param idpConfig the configuration of the identity provider that the request is sending to
 */
default CompletionStage<Void> beforeInitiatingSso(ServiceRequestContext ctx, HttpRequest req,
                                                  MessageContext<AuthnRequest> message,
                                                  SamlIdentityProviderConfig idpConfig) {
    return CompletableFuture.completedFuture(null);
}