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

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

Introduction

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

Prototype

public GroupPrincipalCallback(Subject s, String[] g) 

Source Link

Document

Create a GroupPrincipalCallback to establish the container's representation of the corresponding group principals within the Subject.

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;/* ww w. j a va  2  s .  c  om*/

    //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.j  a v  a2s  .com
        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;
                }/* w w  w  . j  a  va2s .  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;
}