Example usage for javax.security.auth.message.callback CallerPrincipalCallback CallerPrincipalCallback

List of usage examples for javax.security.auth.message.callback CallerPrincipalCallback CallerPrincipalCallback

Introduction

In this page you can find the example usage for javax.security.auth.message.callback CallerPrincipalCallback CallerPrincipalCallback.

Prototype

public CallerPrincipalCallback(Subject s, String n) 

Source Link

Document

Create a CallerPrincipalCallback to set the container's representation of the caller principal.

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  av 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:com.yoshio3.modules.AzureADServerAuthModule.java

private AuthStatus getAuthResultFromServerAndSetSession(Subject clientSubject, HttpServletRequest httpRequest,
        Map<String, String> params, String currentUri) {
    try {// ww  w  . ja  va  2 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.MSPacSpnegoServerAuthModule.java

private boolean authorizeCaller(HttpServletRequest request, byte[] serviceToken, GSSName name,
        final Subject clientSubject) {

    // create Subject with principals from name
    final Subject kerberosServiceSubject = createSubject(name);

    final Set<Principal> kerberosServicePrincipals = kerberosServiceSubject.getPrincipals();

    if (kerberosServicePrincipals.size() > 0) {
        final Set<Principal> clientPrincipals = clientSubject.getPrincipals();

        clientPrincipals.addAll(kerberosServicePrincipals);

        // Pickup the first Principal as the caller
        final Principal caller = kerberosServicePrincipals.iterator().next();

        if (caller != null) {
            // Fetch the list of extra groups
            final Set<String> extraGroups = fetchExtraGroups(request, this.serviceSubject, this.options);

            // Let's add all the groups as valid Principal as part of the
            // clientSubject
            final String[] groups = buildGroupsFromPAC(serviceToken, this.serviceSubject, extraGroups);

            final List<String> groupList = Arrays.asList(groups);

            if (this.mandatoryGroups != null && this.mandatoryGroups.size() > 0) {
                // There was some mandatory group to check
                if (!groupList.containsAll(this.mandatoryGroups)) {
                    // None of the global constraint was found, so exiting
                    debug("Not all the mandatory groups required ({1}) where found in the user groups {0} so failing the authentication.",
                            groupList, this.mandatoryGroups);
                    return false;
                }/*from   w w  w . ja v a  2s .c  o  m*/
            }

            // Check global constraints
            if (this.smartcardSecuredUsersOnly || this.delegatedSecuredUsersOnly) {

                final List<String> contraintGroupList = new ArrayList<String>();
                if (this.smartcardSecuredUsersOnly) {
                    contraintGroupList.add(GROUP_SMARTCARD_AUTHENTICATED);
                }
                if (this.delegatedSecuredUsersOnly) {
                    contraintGroupList.add(GROUP_DELEGATED_AUTHENTICATED);
                }

                // Test if at least one of the constraints are matched
                if (Collections.disjoint(groupList, contraintGroupList)) {
                    // None of the global constraint was found, so exiting
                    debug("The global contrainted group {1} where not found in the user groups {0} so failing the authentication.",
                            groupList, contraintGroupList);
                    return false;
                }

            }

            final GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject,
                    groups);
            try {
                // notify caller for the groups
                this.handler.handle(new Callback[] { groupPrincipalCallback });
                debug("Groups found {0}", groupList);
            } catch (final IOException e) {
                LOG.log(Level.WARNING, "Unable to set the groups " + groupList, e);
            } catch (final UnsupportedCallbackException e) {
                LOG.log(Level.WARNING, "Unable to set the groups " + groupList, e);
            }
        }

        // Create the caller principal to pass to caller
        final CallerPrincipalCallback callerPrincipalCallback = new CallerPrincipalCallback(clientSubject,
                caller);

        try {
            // notify caller for the Principal
            this.handler.handle(new Callback[] { callerPrincipalCallback });
            debug("Caller principal is {0}", (Object) caller);
            return true;
        } catch (final IOException e) {
            LOG.log(Level.WARNING, "Unable to set caller principal {0}", e);
        } catch (final UnsupportedCallbackException e) {
            LOG.log(Level.WARNING, "Unable to set caller principal {0}", e);
        }
    }
    return false;
}

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  .  ja v  a  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;
}