Example usage for javax.security.auth.message MessageInfo getMap

List of usage examples for javax.security.auth.message MessageInfo getMap

Introduction

In this page you can find the example usage for javax.security.auth.message MessageInfo getMap.

Prototype

public Map getMap();

Source Link

Document

Get (a reference to) the Map object of this MessageInfo.

Usage

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * Authenticate a received service request.
 * <p/>/*from   w  w w  .  j  a v a2  s  . c om*/
 * This method is called to transform the mechanism-specific request message
 * acquired by calling getRequestMessage (on messageInfo) into the validated
 * application message to be returned to the message processing runtime. If
 * the received message is a (mechanism-specific) meta-message, the method
 * implementation must attempt to transform the meta-message into a
 * corresponding mechanism-specific response message, or to the validated
 * application request message. The runtime will bind a validated
 * application message into the the corresponding service invocation.
 * <p>
 * This method conveys the outcome of its message processing either by
 * returning an AuthStatus value or by throwing an AuthException.
 * <p/>
 * From a performance point of view this method will be called twice for
 * each resource with a security constraint on it. Resources with no
 * security constraint do not result in a call to this method.
 * 
 * @param messageInfo
 *            A contextual object that encapsulates the client request and
 *            server response objects, and that may be used to save state
 *            across a sequence of calls made to the methods of this
 *            interface for the purpose of completing a secure message
 *            exchange.
 * @param clientSubject
 *            A Subject that represents the source of the service request.
 *            It is used by the method implementation to store Principals
 *            and credentials validated in the request.
 * @param serviceSubject
 *            A Subject that represents the recipient of the service
 *            request, or null. It may be used by the method implementation
 *            as the source of Principals or credentials to be used to
 *            validate the request. If the Subject is not null, the method
 *            implementation may add additional Principals or credentials
 *            (pertaining to the recipient of the service request) to the
 *            Subject.
 * @return An AuthStatus object representing the completion status of the
 *         processing performed by the method. The AuthStatus values that
 *         may be returned by this method are defined as follows:
 *         <p/>
 *         <ul>
 *         <li>AuthStatus.SUCCESS when the application request message was
 *         successfully validated. The validated request message is
 *         available by calling getRequestMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_SUCCESS to indicate that
 *         validation/processing of the request message successfully
 *         produced the secured application response message (in
 *         messageInfo). The secured response message is available by
 *         calling getResponseMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_CONTINUE to indicate that message validation
 *         is incomplete, and that a preliminary response was returned as
 *         the response message in messageInfo.
 *         <p/>
 *         When this status value is returned to challenge an application
 *         request message, the challenged request must be saved by the
 *         authentication module such that it can be recovered when the
 *         module's validateRequest message is called to process the request
 *         returned for the challenge.
 *         <p/>
 *         <li>AuthStatus.SEND_FAILURE to indicate that message validation
 *         failed and that an appropriate failure response message is
 *         available by calling getResponseMessage on messageInfo.
 *         </ul>
 * @throws AuthException When the message processing failed without
 *         establishing a failure response message (in messageInfo).
 */
@SuppressWarnings("unchecked")
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {

    // Extra check (disabled withour -ea) if mandatory value is consistent
    // with initialize phase
    assert messageInfo.getMap().containsKey(IS_MANDATORY_INFO_KEY) == this.mandatory;

    // Get the servlet context
    final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();

    // Invalidate any existing session to prevent session fixture attempt
    HttpSession session = request.getSession(false);
    if (session != null) {
        final SessionState state = (SessionState) session.getAttribute(MAGIC_SESSION_STATE_KEY);
        if (state == null) {
            // Session was not created by us, we will invalidate an existing
            // session that was not created by us
            session.invalidate();
            LOG.warning(
                    "An existing session was invalidated. This might be a session fixture attempt, so failing the authentication.");
            return AuthStatus.SEND_FAILURE;
        } else if (SessionState.ESTABLISHED.equals(state)) {
            // The context was already fully established once within this
            // session.
            return AuthStatus.SUCCESS;
        }
    }

    debugRequest(request);

    // should specify encoder
    final String authorization = request.getHeader(AUTHORIZATION_HEADER);

    if (authorization != null && authorization.startsWith(NEGOTIATE)) {

        final String negotiateString = authorization.substring(NEGOTIATE.length() + 1);

        final byte[] requestToken = Base64.decodeBase64(negotiateString);

        if (serviceSubject == null) {
            // If no service subject was provided by the container then set
            // a service subject
            // from the global context.
            serviceSubject = this.serviceSubject;
        }

        try {
            // Create a validation action
            byte[] gssToken = null;
            final KerberosValidateAction kva = new KerberosValidateAction(this.servicePrincipal, requestToken,
                    serviceSubject);
            try {
                // Validate using the service (server) Subject
                gssToken = Subject.doAs(this.serviceSubject, kva);
            } catch (final PrivilegedActionException e) {
                final GSSException gex = new GSSException(GSSException.DEFECTIVE_TOKEN);
                gex.initCause(e);
                gex.setMinor(GSSException.UNAVAILABLE, "Unable to perform Kerberos validation");
                throw gex;
            }

            if (kva.getContext() != null) {
                final String responseToken = Base64.encodeBase64String(gssToken);
                response.setHeader(AUTHENTICATION_HEADER, "Negotiate " + responseToken);
                debugToken("GSS Response token set to {0}", gssToken);
            }

            if (!kva.isEstablished()) {
                debug("GSS Dialog must continue to succeed");

                session.setAttribute(MAGIC_SESSION_STATE_KEY, SessionState.IN_PROGRESS);

                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return AuthStatus.SEND_CONTINUE;

            } else {

                final Oid mechId = kva.getMech();
                final GSSName name = kva.getSrcName();

                if (!authorizeCaller(request, requestToken, name, clientSubject)) {
                    return sendFailureMessage(response, "Failed to authorize the caller/client");
                }

                // As no valid session should exist anymore, simply create a
                // new one
                session = request.getSession(true);

                final Principal clientPrincipal = new KerberosPrincipal(
                        name.canonicalize(GSS_KRB5_MECH_OID).toString());

                updateSessionAndHeader(request, session, clientPrincipal);

                session.setAttribute(MAGIC_SESSION_STATE_KEY, SessionState.ESTABLISHED);
                /*
                 * Store the mechId in the MessageInfo to indicate which
                 * authentication mechanism was used successfully (JASPIC
                 * Requirement)
                 */
                messageInfo.getMap().put(AUTH_TYPE_INFO_KEY,
                        mechId != null ? mechId.toString() : "Undefined GSS Mechanism");

                debug("GSS Dialog is complete");

            }

        } catch (final GSSException gsse) {
            debug("GSS Dialog has failed : {0}", gsse);

            if (requestToken != null) {
                debug("Bad token detected {0}", gsse);
                debugToken("Bad token was {0}", requestToken);

                if (isNTLMToken(requestToken)) {
                    // There is a high probability it was a NTLM SPNEGO
                    // token
                    return sendFailureMessage(response, "No support for NTLM");
                }
            }

            // for other errors throw an AuthException
            final AuthException ae = new AuthException();
            ae.initCause(gsse);
            throw ae;
        }

    } else if (this.mandatory) {

        response.setHeader(AUTHENTICATION_HEADER, NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        debug("Negotiate was added to the HTTP header : {0}", NEGOTIATE);

        return AuthStatus.SEND_CONTINUE;

    } else if (authorization != null) {
        LOG.warning("An authorization header was ignored.");
    }

    return AuthStatus.SUCCESS;
}

From source file:com.yoshio3.modules.AzureADServerAuthModule.java

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {
    HttpServletRequest httpRequest = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse httpResponse = (HttpServletResponse) messageInfo.getResponseMessage();

    Callback[] callbacks;//from   ww  w  . j a v  a 2s . c  o m

    //Azure AD ??????????
    // if returning as a redirect after authenticating on Azure AD
    //???????????????
    //??????????????????????????
    // as there is no principal information, if authentication was successful add info to the principal
    Map<String, String> params = new HashMap<>();
    httpRequest.getParameterMap().keySet().stream().forEach(key -> {
        params.put(key, httpRequest.getParameterMap().get(key)[0]);
    });
    String currentUri = getCurrentUri(httpRequest);

    //?????????
    // if the authentication result is not included in the session
    if (!getSessionPrincipal(httpRequest)) {
        if (!isRedirectedRequestFromAuthServer(httpRequest, params)) {
            try {
                // Azure AD ? Redirect
                // redirect to Azure ID
                return redirectOpenIDServer(httpResponse, currentUri);
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "Invalid redirect URL", ex);
                return AuthStatus.SEND_FAILURE;
            }
        } else {
            // Azure AD ????????
            // if it's a request returning from Azure AD
            messageInfo.getMap().put("javax.servlet.http.registerSession", Boolean.TRUE.toString());
            messageInfo.getMap().put("javax.servlet.http.authType", "AzureADServerAuthModule");
            return getAuthResultFromServerAndSetSession(clientSubject, httpRequest, params, currentUri);
        }
    } else {
        try {
            //???????
            // if the authentication result is included in the session
            AzureADUserPrincipal sessionPrincipal = (AzureADUserPrincipal) httpRequest.getUserPrincipal();
            AuthenticationResult authenticationResult = sessionPrincipal.getAuthenticationResult();
            if (authenticationResult.getExpiresOnDate().before(new Date())) {
                //????????
                // if the authentication date is old - get an access token from the refresh token
                AuthenticationResult authResult = getAccessTokenFromRefreshToken(
                        authenticationResult.getRefreshToken(), currentUri);
                setSessionPrincipal(httpRequest, new AzureADUserPrincipal(authResult));
            }
            CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject,
                    sessionPrincipal);
            String[] groups = getGroupList(sessionPrincipal);
            GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, groups);

            callbacks = new Callback[] { callerCallBack, groupPrincipalCallback };
            handler.handle(callbacks);
            return AuthStatus.SUCCESS;
        } catch (Throwable ex) {
            LOGGER.log(Level.SEVERE, "Invalid Session Info", ex);
            return AuthStatus.SEND_FAILURE;
        }
    }
}

From source file:org.forgerock.openam.authentication.modules.persistentcookie.PersistentCookieAuthModule.java

/**
 * Sets the required information that needs to be in the jwt.
 *
 * @param messageInfo {@inheritDoc}//from www .j  a va2  s.c  om
 * @param requestParamsMap {@inheritDoc}
 * @param request {@inheritDoc}
 * @param response {@inheritDoc}
 * @param ssoToken {@inheritDoc}
 * @throws AuthenticationException {@inheritDoc}
 */
@Override
public void onLoginSuccess(MessageInfo messageInfo, Map requestParamsMap, HttpServletRequest request,
        HttpServletResponse response, SSOToken ssoToken) throws AuthenticationException {
    try {
        Map<String, Object> contextMap = getServerAuthModule().getContextMap(messageInfo);

        contextMap.put(OPENAM_USER_CLAIM_KEY, ssoToken.getPrincipal().getName());
        contextMap.put(OPENAM_AUTH_TYPE_CLAIM_KEY, ssoToken.getAuthType());
        contextMap.put(OPENAM_SESSION_ID_CLAIM_KEY, ssoToken.getTokenID().toString());
        contextMap.put(OPENAM_REALM_CLAIM_KEY, ssoToken.getProperty(SSO_TOKEN_ORGANIZATION_PROPERTY_KEY));
        String jwtString = ssoToken.getProperty(JwtSessionModule.JWT_VALIDATED_KEY);
        if (jwtString != null) {
            messageInfo.getMap().put(JwtSessionModule.JWT_VALIDATED_KEY, Boolean.parseBoolean(jwtString));
        }
    } catch (SSOException e) {
        DEBUG.error("Could not secure response", e);
        throw new AuthenticationException(e.getLocalizedMessage());
    }
}

From source file:org.forgerock.openam.jaspi.modules.session.LocalSSOTokenSessionModule.java

/**
 * Validates the request by attempting to retrieve the SSOToken ID from the cookies on the request.
 * If the SSOToken ID cookie is not present then the method returns AuthStatus.SEND_FAILURE, otherwise if it is
 * present it is then used to retrieve the actual SSOToken from the SSOTokenManager, if valid then
 * AuthStatus.SUCCESS will be returned, otherwise AuthStatus.SEND_FAILURE will be returned.
 *
 * @param request The HttpServletRequest.
 * @param messageInfo A contextual object that encapsulates the client request and server response objects, and
 *                    that may be used to save state across a sequence of calls made to the methods of this
 *                    interface for the purpose of completing a secure message exchange.
 * @param clientSubject A Subject that represents the source of the service request. It is used by the method
 *                      implementation to store Principals and credentials validated in the request.
 * @return AuthStatus.SUCCESS if the SSOToken ID is valid, otherwise AuthStatus.SEND_FAILURE.
 * @throws AuthException If there is a problem validating the request.
 *//*w w w  . j  a va  2s . c o  m*/
private AuthStatus validate(HttpServletRequest request, MessageInfo messageInfo, Subject clientSubject)
        throws AuthException {

    String tokenId = getRequestUtils().getTokenId(request);
    if (StringUtils.isEmpty(tokenId)) {
        tokenId = request.getHeader(getCookieHeaderName());
    }
    if (!StringUtils.isEmpty(tokenId)) {
        SSOToken ssoToken = getFactory().getTokenFromId(tokenId);

        if (ssoToken != null) {

            int authLevel;
            try {
                authLevel = ssoToken.getAuthLevel();
                String name = ssoToken.getPrincipal().getName();
                handler.handle(new Callback[] { new CallerPrincipalCallback(clientSubject, name) });

                clientSubject.getPrincipals().add(ssoToken.getPrincipal());
            } catch (SSOException e) {
                throw new AuthException(e.getMessage());
            } catch (UnsupportedCallbackException e) {
                throw new AuthException(e.getMessage());
            } catch (IOException e) {
                throw new AuthException(e.getMessage());
            }

            Map<String, Object> context = (Map<String, Object>) messageInfo.getMap()
                    .get("org.forgerock.authentication.context");
            context.put("authLevel", authLevel);
            context.put("tokenId", ssoToken.getTokenID().toString());
            //TODO add more properties to context map

            return AuthStatus.SUCCESS;
        }
    }
    return AuthStatus.SEND_FAILURE;
}

From source file:org.forgerock.openidm.jaspi.modules.IDMJaspiModuleWrapper.java

private Resource getAuthenticatedResource(String principalName, MessageInfo messageInfo)
        throws ResourceException {
    // see if the resource was stored in the MessageInfo by the Authenticator
    if (messageInfo.getMap().containsKey(AUTHENTICATED_RESOURCE)) {
        JsonValue resourceDetail = new JsonValue(messageInfo.getMap().get(AUTHENTICATED_RESOURCE));
        if (resourceDetail.isMap()) {
            return new Resource(resourceDetail.get(FIELD_CONTENT_ID).asString(),
                    resourceDetail.get(FIELD_CONTENT_REVISION).asString(), resourceDetail.get(FIELD_CONTENT));
        }//from   ww w .  j a  v  a  2s . c  om
    }

    // attempt to read the user object; will return null if any of the pieces are null
    return queryExecutor.apply(queryBuilder.forPrincipal(principalName).build());
}

From source file:org.forgerock.openidm.jaspi.modules.IDMJaspiModuleWrapper.java

private Map<String, Object> getContextMap(MessageInfo messageInfo) {
    return (Map<String, Object>) messageInfo.getMap().get(JaspiRuntime.ATTRIBUTE_AUTH_CONTEXT);
}

From source file:org.forgerock.openidm.jaspi.modules.IDMJaspiModuleWrapper.java

/**
 * If the request contains the X-OpenIDM-NoSession header, sets the skipSession property on the MessageInfo,
 * and then calls the underlying auth module's secureResponse method.
 *
 * @param messageInfo {@inheritDoc}/*w ww  . j  a v  a2  s.  co m*/
 * @param serviceSubject {@inheritDoc}
 * @return {@inheritDoc}
 * @throws AuthException {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {

    final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    final String noSession = request.getHeader(NO_SESSION);

    if (Boolean.parseBoolean(noSession)) {
        messageInfo.getMap().put("skipSession", true);
    }

    return authModule.secureResponse(messageInfo, serviceSubject);
}

From source file:org.forgerock.openidm.jaspi.modules.PassthroughModule.java

/**
 * Set pass through auth resource in context map on request so can be accessed by authnPopulateContext.js script.
 *
 * @param messageInfo The MessageInfo./*from   www.j  a v  a  2 s .c  o  m*/
 */
@SuppressWarnings("unchecked")
void setPassThroughAuthOnRequest(MessageInfo messageInfo) {
    Map<String, Object> contextMap = (Map<String, Object>) messageInfo.getMap()
            .get(IDMServerAuthModule.CONTEXT_REQUEST_KEY);
    contextMap.put("passThroughAuth", passThroughAuth);
    if (propertyMapping != null) {
        contextMap.put("propertyMapping", propertyMapping.getObject());
    }
}

From source file:org.forgerock.tinker.authentication.modules.persistentcookie.PersistentCookieAuthModule.java

/**
 * Sets the required information that needs to be in the jwt.
 *
 * @param messageInfo {@inheritDoc}//from   w w  w.j  ava 2  s . c  o m
 * @param requestParamsMap {@inheritDoc}
 * @param request {@inheritDoc}
 * @param response {@inheritDoc}
 * @param ssoToken {@inheritDoc}
 * @throws AuthenticationException {@inheritDoc}
 */
@Override
public void onLoginSuccess(MessageInfo messageInfo, Map requestParamsMap, HttpServletRequest request,
        HttpServletResponse response, SSOToken ssoToken) throws AuthenticationException {

    try {
        Map<String, Object> contextMap = getServerAuthModule().getContextMap(messageInfo);

        contextMap.put(OPENAM_USER_CLAIM_KEY, ssoToken.getPrincipal().getName());
        contextMap.put(OPENAM_AUTH_TYPE_CLAIM_KEY, ssoToken.getAuthType());
        contextMap.put(OPENAM_SESSION_ID_CLAIM_KEY, ssoToken.getTokenID().toString());
        contextMap.put(OPENAM_REALM_CLAIM_KEY, ssoToken.getProperty(SSO_TOKEN_ORGANIZATION_PROPERTY_KEY));
        contextMap.put(OPENAM_CLIENT_IP_CLAIM_KEY, ClientUtils.getClientIPAddress(request));

        String jwtString = ssoToken.getProperty(JwtSessionModule.JWT_VALIDATED_KEY);
        if (jwtString != null) {
            messageInfo.getMap().put(JwtSessionModule.JWT_VALIDATED_KEY, Boolean.parseBoolean(jwtString));
        }

        // Change Start : Output data to message debug
        DEBUG.message("TINKER: PersistentCookieAuthenticationModule.onLoginSuccess().");
        DEBUG.message("OPENAM_USER_CLAIM_KEY=" + ssoToken.getPrincipal().getName());
        DEBUG.message("OPENAM_AUTH_TYPE_CLAIM_KEY=" + ssoToken.getAuthType());
        DEBUG.message("OPENAM_SESSION_ID_CLAIM_KEY=" + ssoToken.getTokenID().toString());
        DEBUG.message("OPENAM_REALM_CLAIM_KEY=" + ssoToken.getProperty(SSO_TOKEN_ORGANIZATION_PROPERTY_KEY));
        DEBUG.message("OPENAM_CLIENT_IP_CLAIM_KEY=" + ClientUtils.getClientIPAddress(request));
        DEBUG.message("TINKER_OPENAM_PWD_CHANGED_TIME=" + ssoToken.getProperty("TINKER_PWD_CHANGED_TIME"));

        final Jwt jwt_inspect = getServerAuthModule().validateJwtSessionCookie(messageInfo);
        JwtClaimsSet claimsSet = jwt_inspect.getClaimsSet();

        if (claimsSet != null) {
            DEBUG.message("jwt.getPrincipal()=" + claimsSet.getPrincipal());
            DEBUG.message("jwt.getIssuer()=" + claimsSet.getIssuer());
            DEBUG.message("jwt.getNotBeforeTime()=" + claimsSet.getNotBeforeTime().toString());
            DEBUG.message("jwt.getExpirationTime()=" + claimsSet.getExpirationTime().toString());
            DEBUG.message("jwt.getIssuedAtTime()=" + claimsSet.getIssuedAtTime().toString());
        }
        // Change End
    } catch (SSOException e) {
        DEBUG.error("Could not secure response", e);
        throw new AuthenticationException(e.getLocalizedMessage());
    }
}