Example usage for javax.security.auth.message AuthStatus SEND_FAILURE

List of usage examples for javax.security.auth.message AuthStatus SEND_FAILURE

Introduction

In this page you can find the example usage for javax.security.auth.message AuthStatus SEND_FAILURE.

Prototype

AuthStatus SEND_FAILURE

To view the source code for javax.security.auth.message AuthStatus SEND_FAILURE.

Click Source Link

Document

Indicates that the message processing by the authentication module was NOT successful, that the module replaced the application message with an error message, and that the runtime is to proceed by sending the error message.

Usage

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;/*w ww.  j  ava2 s  . 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:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * Authenticate a received service request.
 * <p/>/*from   w  w w  .ja  va  2 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:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * Sends a failure message in the response
 * //  w  w  w. ja  v  a2 s .co  m
 * @param response
 * @param message
 * @return
 */
protected AuthStatus sendFailureMessage(HttpServletResponse response, String message) {

    try {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
    } catch (final Throwable t) {
        // status code has been set, and proper AuthStatus will be returned
        LOG.log(Level.WARNING, "Fail to set FORBIDDEN status {0}", t);
    }
    return AuthStatus.SEND_FAILURE;
}

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.
 */// ww  w  .  jav a  2  s.  co 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

/**
 * Provides IDM specific authentication process handling, by setting whether to log the client's IP address,
 * and then calls the underlying auth module's validateRequest method. If the auth module returns
 * SUCCESS, based on the authentication configuration will perform role calculation and, if present, will run the
 * augment security context script.// ww  w  . j av  a2  s  . c  o  m
 *
 * @param messageInfo {@inheritDoc}
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @return {@inheritDoc}
 * @throws AuthException {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {

    // Add this properties so the AuditLogger knows whether to log the client IP in the header.
    setClientIPAddress(messageInfo);

    final AuthStatus authStatus = authModule.validateRequest(messageInfo, clientSubject, serviceSubject);

    if (!AuthStatus.SUCCESS.equals(authStatus)) {
        return authStatus;
    }

    String principalName = null;
    for (Principal principal : clientSubject.getPrincipals()) {
        if (principal.getName() != null) {
            principalName = principal.getName();
            break;
        }
    }

    if (principalName == null) {
        // As per Jaspi spec, the module developer MUST ensure that the client
        // subject's principal is set when the module returns SUCCESS.
        throw new JaspiAuthException(
                "Underlying Server Auth Module has not set the client subject's principal!");
    }

    // user is authenticated; populate security context

    try {
        final Resource resource = getAuthenticatedResource(principalName, messageInfo);

        final SecurityContextMapper securityContextMapper = SecurityContextMapper.fromMessageInfo(messageInfo)
                .setAuthenticationId(principalName);

        // Calculate (and set) roles if not already set
        if (securityContextMapper.getRoles() == null || securityContextMapper.getRoles().isEmpty()) {
            roleCalculator.calculateRoles(principalName, securityContextMapper, resource);
        }

        // set "resource" (component) if not already set
        if (securityContextMapper.getResource() == null) {
            securityContextMapper.setResource(queryOnResource);
        }

        // set "user id" (authorization.id) if not already set
        if (securityContextMapper.getUserId() == null) {
            if (resource != null) {
                // assign authorization id from resource if present
                securityContextMapper.setUserId(resource.getId() != null ? resource.getId()
                        : resource.getContent().get(FIELD_CONTENT_ID).asString());
            } else {
                // set to principal otherwise
                securityContextMapper.setUserId(principalName);
            }
        }

        // run the augmentation script, if configured (will no-op if none specified)
        augmentationScriptExecutor.executeAugmentationScript(augmentScript, properties, securityContextMapper);

    } catch (ResourceException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed role calculation for {} on {}.", principalName, queryOnResource, e);
        }
        if (e.isServerError()) { // HTTP server-side error; AuthException sadly does not accept cause
            throw new JaspiAuthException("Failed pass-through authentication of " + principalName + " on "
                    + queryOnResource + ":" + e.getMessage(), e);
        }
        // role calculation failed
        return AuthStatus.SEND_FAILURE;
    }

    return authStatus;
}

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

/**
 * Validates the request by authenticating against either the client certificate in the request, internally or
 * Basic Authentication from the request header internally.
 *
 * @param messageInfo {@inheritDoc}//from  w  w w .ja va2  s.  c om
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @param authData {@inheritDoc}
 * @return {@inheritDoc}
 */
@Override
protected AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject,
        AuthData authData) {

    HttpServletRequest req = (HttpServletRequest) messageInfo.getRequestMessage();
    boolean authenticated;

    final String headerLogin = req.getHeader(HEADER_USERNAME);
    String basicAuth = req.getHeader("Authorization");
    // if we see the certificate port this request is for client auth only
    if (allowClientCertOnly(req)) {
        authenticated = authenticateUsingClientCert(req, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else if (headerLogin != null) {
        authenticated = authenticateUser(req, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else if (basicAuth != null) {
        authenticated = authenticateUsingBasicAuth(basicAuth, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else {
        //Auth failure will be logged in IDMServerAuthModule super type.
        return AuthStatus.SEND_FAILURE;
    }
    authData.setResource(queryOnResource);
    logger.debug("Found valid session for {} id {} with roles {}", authData.getUsername(), authData.getUserId(),
            authData.getRoles());

    if (authenticated) {
        clientSubject.getPrincipals().add(new Principal() {
            public String getName() {
                return headerLogin;
            }
        });
    }

    return authenticated ? AuthStatus.SUCCESS : AuthStatus.SEND_FAILURE;
}

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

/**
 * Uses the IWA authentication module with fall through to the Passthrough authentication module to validate the
 * request.//from   ww w  .j ava  2  s.com
 *
 * If the OpenIDM username header has been set then Passthrough is used.
 * If the OpenIDM username header is not set the IWA is used.
 * If IWA fails then Passthrough is used.
 * If Passthrough fails then the method returns AuthStatus.SEND_FAILURE.
 * If either Passthrough or IWA succeeds then the method return AuthStatus.SUCCESS.
 *
 * @param messageInfo {@inheritDoc}
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @param authData {@inheritDoc}
 * @return {@inheritDoc}
 * @throws AuthException If there is a problem performing the authentication.
 */
@Override
protected AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject,
        AuthData authData) throws AuthException {

    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    //Set pass through auth resource on request so can be accessed by authnPopulateContext.js script.
    passthroughModule.setPassThroughAuthOnRequest(messageInfo);

    String xOpenIDMUsername = request.getHeader("X-OpenIDM-Username");
    String xOpenIdmPassword = request.getHeader("X-OpenIDM-Password");
    if (!StringUtils.isEmpty(xOpenIDMUsername) && !StringUtils.isEmpty(xOpenIdmPassword)) {
        // skip straight to ad passthrough
        LOGGER.debug("IWAPassthroughModule: Have OpenIDM username, falling back to AD Passthrough");
        return passthroughModule.validateRequest(messageInfo, clientSubject, serviceSubject, authData);
    }

    AuthStatus authStatus = super.validateRequest(messageInfo, clientSubject, serviceSubject, authData);

    if (AuthStatus.SEND_FAILURE.equals(authStatus)) {
        return passthroughModule.validateRequest(messageInfo, clientSubject, serviceSubject, authData);
    } else {
        return authStatus;
    }
}

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

/**
 * Validates the client's request by passing through the request to be authenticated against a OpenICF Connector.
 *
 * @param messageInfo {@inheritDoc}//  www.  j av a 2s  .c  o m
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @param authData {@inheritDoc}
 * @return {@inheritDoc}
 * @throws AuthException If there is a problem performing the authentication.
 */
@Override
protected AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject,
        AuthData authData) throws AuthException {

    LOGGER.debug("PassthroughModule: validateRequest START");

    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();

    try {
        LOGGER.debug("PassthroughModule: Delegating call to internal AuthFilter");
        //Set pass through auth resource on request so can be accessed by authnPopulateContext.js script.
        setPassThroughAuthOnRequest(messageInfo);

        final String username = request.getHeader("X-OpenIDM-Username");
        String password = request.getHeader("X-OpenIDM-Password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            LOGGER.debug("Failed authentication, missing or empty headers");
            //Auth failure will be logged in IDMServerAuthModule super type.
            return AuthStatus.SEND_FAILURE;
        }

        authData.setUsername(username);
        clientSubject.getPrincipals().add(new Principal() {
            public String getName() {
                return username;
            }
        });
        boolean authenticated = passthroughAuthenticator.authenticate(authData, password);

        if (authenticated) {
            LOGGER.debug("PassthroughModule: Authentication successful");
            LOGGER.debug("Found valid session for {} id {} with roles {}", authData.getUsername(),
                    authData.getUserId(), authData.getRoles());

            //Auth success will be logged in IDMServerAuthModule super type.
            return AuthStatus.SUCCESS;
        } else {
            LOGGER.debug("PassthroughModule: Authentication failed");
            //Auth failure will be logged in IDMServerAuthModule super type.
            return AuthStatus.SEND_FAILURE;
        }
    } finally {
        LOGGER.debug("PassthroughModule: validateRequest END");
    }
}