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

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

Introduction

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

Prototype

AuthStatus SUCCESS

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

Click Source Link

Document

Indicates that the message processing by the authentication module was successful and that the runtime is to proceed with its normal processing of the resulting 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;//from  w ww  .  j  a v a  2 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.SimpleBasicServerAuthModule.java

/**
 * Authenticate a received service request.
 * <p/>//from   w w w. j a va2  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).
 */
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {
    // Get the servlet context
    final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
    final String auth = request.getHeader(AUTHORIZATION_HEADER);
    // Test prefix for HTTP BASIC Auth
    if (auth != null && StringUtils.startsWithIgnoreCase(auth, "basic ")) {
        // We might have a valid header, so try to decode it
        final String data = new String(Base64.decodeBase64(auth.substring(BASIC_PREFIX_LENGTH)), UTF_8);
        final int splitIndex = data.indexOf(':');
        if (splitIndex < 0) {
            return sendErrorAndAuthenticateRequest(request, response, "Wrong WWW-Authenticate header format");
        }
        final String username = data.substring(splitIndex);
        final char[] password = data.substring(splitIndex + 1, data.length()).toCharArray();

        // Prepare the JAAS callback to feed any LoginModule with user and password
        final NameCallback nameCallback = new NameCallback("username");
        nameCallback.setName(username);

        final PasswordCallback passwordCallback = new PasswordCallback(getRealm(request), false);
        passwordCallback.setPassword(password);

        final CallbackHandler delegatedHandler = new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    final Callback c = callbacks[i];
                    if (c instanceof NameCallback) {
                        ((NameCallback) c).setName(username);
                    } else if (c instanceof PasswordCallback) {
                        ((PasswordCallback) c).setPassword(password);
                    } else {
                        throw new UnsupportedOperationException(
                                String.format("Callback type %s (%s) is not supported yet.", c.getClass(), c));
                    }
                }
            }
        };

        if (this.jaasContextName == null) {
            throw new UnsupportedOperationException(
                    "No delegate JAAS context found. As per JASPIC JAAS Bridge profile, this parameter is requiered.");
        }

        try {
            // Create a new JAAS context with the delegated data & try to login
            final LoginContext context = new LoginContext(this.jaasContextName, delegatedHandler);
            context.login();

            // Get the authenticated subject from the JAAS context
            Subject authenticatedSubject = context.getSubject();

            final PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback(
                    authenticatedSubject, username, password);

            // notify JASPIC containerr for the name, password and subject
            this.handler.handle(new Callback[] { passwordValidationCallback });

        } catch (final LoginException ex) {
            // If there was any issue during the JAAS login, fail the process
            final AuthException aex = new AuthException(
                    String.format("Fail to login user %s with the delegated JAAS context %s", username,
                            this.jaasContextName));
            aex.initCause(ex);
        } catch (final IOException e) {
            LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e);
        } catch (final UnsupportedCallbackException e) {
            LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e);
        }

    } else if (this.mandatory) {
        return sendErrorAndAuthenticateRequest(request, response,
                "AuthModule was mandatory but no valid credential was provided");
    } else {
        LOG.info("No authentication was provided bu Basic AuthModule is not mandatory so return SUCCESS.");
    }

    return AuthStatus.SUCCESS;
}

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

private AuthStatus getAuthResultFromServerAndSetSession(Subject clientSubject, HttpServletRequest httpRequest,
        Map<String, String> params, String currentUri) {
    try {// w  ww  .ja v  a2 s . c  o m
        String fullUrl = currentUri
                + (httpRequest.getQueryString() != null ? "?" + httpRequest.getQueryString() : "");
        AuthenticationResponse authResponse = AuthenticationResponseParser.parse(new URI(fullUrl), params);
        //params ?? error ???????AuthenticationErrorResponse
        // if there is an error key in params, return AuthenticationErrorResponse
        //??? AuthenticationSuccessResponse ?
        // if it was successful, return AuthenticationSuccessResponse

        //??????
        // if authentication was successful
        if (authResponse instanceof AuthenticationSuccessResponse) {
            //???????
            // obtain the result from the response and save it in the session

            AuthenticationSuccessResponse authSuccessResponse = (AuthenticationSuccessResponse) authResponse;
            AuthenticationResult result = getAccessToken(authSuccessResponse.getAuthorizationCode(),
                    currentUri);
            AzureADUserPrincipal userPrincipal = new AzureADUserPrincipal(result);
            setSessionPrincipal(httpRequest, userPrincipal);

            //?
            // set the user principal
            String[] groups = getGroupList(userPrincipal);
            System.out.println(": " + Arrays.toString(groups));
            AzureADCallbackHandler azureCallBackHandler = new AzureADCallbackHandler(clientSubject, httpRequest,
                    userPrincipal);
            loginContext = new LoginContext(LOGIN_CONTEXT_NAME, azureCallBackHandler);
            loginContext.login();
            Subject subject = loginContext.getSubject();

            CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject, userPrincipal);
            GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, groups);

            Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback };
            handler.handle(callbacks);

            return AuthStatus.SUCCESS;
        } else {
            // ?????
            // if authentication failed
            AuthenticationErrorResponse authErrorResponse = (AuthenticationErrorResponse) authResponse;
            CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject,
                    (Principal) null);
            GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, null);

            Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback };
            handler.handle(callbacks);

            return AuthStatus.FAILURE;
        }
    } catch (Throwable ex) {
        CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject, (Principal) null);
        GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, null);

        Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback };
        try {
            handler.handle(callbacks);
        } catch (IOException | UnsupportedCallbackException ex1) {
            LOGGER.log(Level.SEVERE, null, ex1);
        }
        LOGGER.log(Level.SEVERE, null, ex);
        return AuthStatus.FAILURE;
    }
}

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

/**
 * Secure a service response before sending it to the client.
 * <p/>//from w w  w. j  a v a  2 s .  co  m
 * This method is called to transform the response message acquired by
 * calling getResponseMessage (on messageInfo) into the mechanism-specific
 * form to be sent by the runtime.
 * <p>
 * This method conveys the outcome of its message processing either by
 * returning an AuthStatus value or by throwing an AuthException.
 * 
 * @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 serviceSubject
 *            A Subject that represents the source of the service response,
 *            or null. It may be used by the method implementation to
 *            retrieve Principals and credentials necessary to secure the
 *            response. If the Subject is not null, the method
 *            implementation may add additional Principals or credentials
 *            (pertaining to the source of the service response) 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.SEND_SUCCESS when the application response message
 *         was successfully secured. The secured response message may be
 *         obtained by calling getResponseMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_CONTINUE to indicate that the application
 *         response message (within messageInfo) was replaced with a
 *         security message that should elicit a security-specific response
 *         (in the form of a request) from the peer.
 *         <p/>
 *         This status value serves to inform the calling runtime that (to
 *         successfully complete the message exchange) it will need to be
 *         capable of continuing the message dialog by processing at least
 *         one additional request/response exchange (after having sent the
 *         response message returned in messageInfo).
 *         <p/>
 *         When this status value is returned, the application response must
 *         be saved by the authentication module such that it can be
 *         recovered when the module's validateRequest message is called to
 *         process the elicited response.
 *         <p/>
 *         <li>AuthStatus.SEND_FAILURE to indicate that a failure occurred
 *         while securing the response message and that an appropriate
 *         failure response message is available by calling
 *         getResponseMeessage on messageInfo.
 *         </ul>
 * @throws AuthException When the message processing failed without
 *         establishing a failure response message (in messageInfo).
 */
public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException {
    // nothing to do but go thru
    return AuthStatus.SUCCESS;
}

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

/**
 * Authenticate a received service request.
 * <p/>//from ww  w.j  av  a 2  s  .c o m
 * 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: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.
 *///from  w  ww  .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.auth.modules.IDMAuthModuleWrapper.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.//  w w w.j  ava2  s .com
 *
 * @param messageInfo {@inheritDoc}
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @return {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public Promise<AuthStatus, AuthenticationException> validateRequest(final MessageInfoContext messageInfo,
        final Subject clientSubject, Subject serviceSubject) {

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

    return authModule.validateRequest(messageInfo, clientSubject, serviceSubject)
            .then(new Function<AuthStatus, AuthStatus, AuthenticationException>() {
                @Override
                public AuthStatus apply(AuthStatus authStatus) throws AuthenticationException {
                    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 AuthenticationException(
                                "Underlying Server Auth Module has not set the client subject's principal!");
                    }

                    // user is authenticated; populate security context

                    try {
                        final ResourceResponse 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()) {
                            throw new AuthenticationException("Failed pass-through authentication of "
                                    + principalName + " on " + queryOnResource + ":" + e.getMessage(), e);
                        }
                        // role calculation failed
                        return SEND_FAILURE;
                    }

                    return authStatus;
                }
            });
}

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.//  w  ww .  j  a v a 2s  .  co 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  ww w.jav  a 2s .  c o  m
 * @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.PassthroughModule.java

/**
 * Validates the client's request by passing through the request to be authenticated against a OpenICF Connector.
 *
 * @param messageInfo {@inheritDoc}//from  w w w .jav  a 2 s .c  om
 * @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");
    }
}