Search in sources :

Example 16 with GenericPrincipal

use of org.apache.catalina.realm.GenericPrincipal in project tomcat by apache.

the class AuthenticatorBase method authenticateJaspic.

private boolean authenticateJaspic(Request request, Response response, JaspicState state, boolean requirePrincipal) {
    boolean cachedAuth = checkForCachedAuthentication(request, response, false);
    Subject client = new Subject();
    AuthStatus authStatus;
    try {
        authStatus = state.serverAuthContext.validateRequest(state.messageInfo, client, null);
    } catch (AuthException e) {
        log.debug(sm.getString("authenticator.loginFail"), e);
        return false;
    }
    request.setRequest((HttpServletRequest) state.messageInfo.getRequestMessage());
    response.setResponse((HttpServletResponse) state.messageInfo.getResponseMessage());
    if (authStatus == AuthStatus.SUCCESS) {
        GenericPrincipal principal = getPrincipal(client);
        if (log.isDebugEnabled()) {
            log.debug("Authenticated user: " + principal);
        }
        if (principal == null) {
            request.setUserPrincipal(null);
            request.setAuthType(null);
            if (requirePrincipal) {
                return false;
            }
        } else if (cachedAuth == false || !principal.getUserPrincipal().equals(request.getUserPrincipal())) {
            // Skip registration if authentication credentials were
            // cached and the Principal did not change.
            // Check to see if any of the JASPIC properties were set
            Boolean register = null;
            String authType = "JASPIC";
            // JASPIC API uses raw types
            @SuppressWarnings("rawtypes") Map map = state.messageInfo.getMap();
            String registerValue = (String) map.get("jakarta.servlet.http.registerSession");
            if (registerValue != null) {
                register = Boolean.valueOf(registerValue);
            }
            String authTypeValue = (String) map.get("jakarta.servlet.http.authType");
            if (authTypeValue != null) {
                authType = authTypeValue;
            }
            /*
                 * Need to handle three cases.
                 * See https://bz.apache.org/bugzilla/show_bug.cgi?id=64713
                 * 1. registerSession TRUE    always use session, always cache
                 * 2. registerSession NOT SET config for session, config for cache
                 * 3. registerSession FALSE   config for session, never cache
                 */
            if (register != null) {
                register(request, response, principal, authType, null, null, alwaysUseSession || register.booleanValue(), register.booleanValue());
            } else {
                register(request, response, principal, authType, null, null);
            }
        }
        request.setNote(Constants.REQ_JASPIC_SUBJECT_NOTE, client);
        return true;
    }
    return false;
}
Also used : GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) AuthStatus(jakarta.security.auth.message.AuthStatus) AuthException(jakarta.security.auth.message.AuthException) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) Map(java.util.Map) Subject(javax.security.auth.Subject)

Example 17 with GenericPrincipal

use of org.apache.catalina.realm.GenericPrincipal in project tomcat by apache.

the class TestCallbackHandlerImpl method testGroupPrincipalCallback.

@Test
public void testGroupPrincipalCallback() throws Exception {
    CallbackHandler callbackHandler = createCallbackHandler(null);
    Subject clientSubject = new Subject();
    CallerPrincipalCallback cpc = new CallerPrincipalCallback(clientSubject, "name");
    GroupPrincipalCallback gpc = new GroupPrincipalCallback(clientSubject, new String[] { "group1", "group2" });
    callbackHandler.handle(new Callback[] { cpc, gpc });
    Set<Object> credentials = clientSubject.getPrivateCredentials();
    Assert.assertTrue(credentials.size() == 1);
    GenericPrincipal gp = (GenericPrincipal) credentials.iterator().next();
    Assert.assertEquals("name", gp.getName());
    Assert.assertTrue(gp.hasRole("group1"));
    Assert.assertTrue(gp.hasRole("group2"));
}
Also used : CallerPrincipalCallback(jakarta.security.auth.message.callback.CallerPrincipalCallback) CallbackHandler(javax.security.auth.callback.CallbackHandler) GroupPrincipalCallback(jakarta.security.auth.message.callback.GroupPrincipalCallback) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) Subject(javax.security.auth.Subject) Test(org.junit.Test)

Example 18 with GenericPrincipal

use of org.apache.catalina.realm.GenericPrincipal in project tomcat70 by apache.

the class SerializablePrincipal method readPrincipal.

public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClassNotFoundException {
    String name = in.readUTF();
    boolean hasPwd = in.readBoolean();
    String pwd = null;
    if (hasPwd)
        pwd = in.readUTF();
    int size = in.readInt();
    String[] roles = new String[size];
    for (int i = 0; i < size; i++) roles[i] = in.readUTF();
    Principal userPrincipal = null;
    boolean hasUserPrincipal = in.readBoolean();
    if (hasUserPrincipal) {
        try {
            userPrincipal = (Principal) in.readObject();
        } catch (ClassNotFoundException e) {
            log.error(sm.getString("serializablePrincipal.readPrincipal.cnfe"), e);
            throw e;
        }
    }
    return new GenericPrincipal(name, pwd, Arrays.asList(roles), userPrincipal);
}
Also used : GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) Principal(java.security.Principal) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal)

Example 19 with GenericPrincipal

use of org.apache.catalina.realm.GenericPrincipal in project tomcat70 by apache.

the class AuthenticatorBase method logout.

@Override
public void logout(Request request) throws ServletException {
    Principal p = request.getPrincipal();
    if (p instanceof GenericPrincipal) {
        try {
            ((GenericPrincipal) p).logout();
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            log.debug(sm.getString("authenticator.tomcatPrincipalLogoutFail"), t);
        }
    }
    register(request, request.getResponse(), null, null, null, null);
}
Also used : GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) Principal(java.security.Principal)

Example 20 with GenericPrincipal

use of org.apache.catalina.realm.GenericPrincipal in project tomcat70 by apache.

the class StandardSessionContext method expire.

/**
 * Perform the internal processing required to invalidate this session,
 * without triggering an exception if the session has already expired.
 *
 * @param notify Should we notify listeners about the demise of
 *  this session?
 */
public void expire(boolean notify) {
    // isValid is false
    if (!isValid)
        return;
    synchronized (this) {
        // entered as per bug 56339
        if (expiring || !isValid)
            return;
        if (manager == null)
            return;
        // Mark this session as "being expired"
        expiring = true;
        // Notify interested application event listeners
        // FIXME - Assumes we call listeners in reverse order
        Context context = (Context) manager.getContainer();
        // The call to expire() may not have been triggered by the webapp.
        // Make sure the webapp's class loader is set when calling the
        // listeners
        ClassLoader oldTccl = null;
        if (context.getLoader() != null && context.getLoader().getClassLoader() != null) {
            oldTccl = Thread.currentThread().getContextClassLoader();
            if (Globals.IS_SECURITY_ENABLED) {
                PrivilegedAction<Void> pa = new PrivilegedSetTccl(context.getLoader().getClassLoader());
                AccessController.doPrivileged(pa);
            } else {
                Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());
            }
        }
        try {
            Object[] listeners = context.getApplicationLifecycleListeners();
            if (notify && (listeners != null)) {
                HttpSessionEvent event = new HttpSessionEvent(getSession());
                for (int i = 0; i < listeners.length; i++) {
                    int j = (listeners.length - 1) - i;
                    if (!(listeners[j] instanceof HttpSessionListener))
                        continue;
                    HttpSessionListener listener = (HttpSessionListener) listeners[j];
                    try {
                        context.fireContainerEvent("beforeSessionDestroyed", listener);
                        listener.sessionDestroyed(event);
                        context.fireContainerEvent("afterSessionDestroyed", listener);
                    } catch (Throwable t) {
                        ExceptionUtils.handleThrowable(t);
                        try {
                            context.fireContainerEvent("afterSessionDestroyed", listener);
                        } catch (Exception e) {
                        // Ignore
                        }
                        manager.getContainer().getLogger().error(sm.getString("standardSession.sessionEvent"), t);
                    }
                }
            }
        } finally {
            if (oldTccl != null) {
                if (Globals.IS_SECURITY_ENABLED) {
                    PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldTccl);
                    AccessController.doPrivileged(pa);
                } else {
                    Thread.currentThread().setContextClassLoader(oldTccl);
                }
            }
        }
        if (ACTIVITY_CHECK) {
            accessCount.set(0);
        }
        // Remove this session from our manager's active sessions
        manager.remove(this, true);
        // Notify interested session event listeners
        if (notify) {
            fireSessionEvent(Session.SESSION_DESTROYED_EVENT, null);
        }
        // Call the logout method
        if (principal instanceof GenericPrincipal) {
            GenericPrincipal gp = (GenericPrincipal) principal;
            try {
                gp.logout();
            } catch (Exception e) {
                manager.getContainer().getLogger().error(sm.getString("standardSession.logoutfail"), e);
            }
        }
        // We have completed expire of this session
        setValid(false);
        expiring = false;
        // Unbind any objects associated with this session
        String[] keys = keys();
        if (oldTccl != null) {
            if (Globals.IS_SECURITY_ENABLED) {
                PrivilegedAction<Void> pa = new PrivilegedSetTccl(context.getLoader().getClassLoader());
                AccessController.doPrivileged(pa);
            } else {
                Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());
            }
        }
        try {
            for (int i = 0; i < keys.length; i++) {
                removeAttributeInternal(keys[i], notify);
            }
        } finally {
            if (oldTccl != null) {
                if (Globals.IS_SECURITY_ENABLED) {
                    PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldTccl);
                    AccessController.doPrivileged(pa);
                } else {
                    Thread.currentThread().setContextClassLoader(oldTccl);
                }
            }
        }
    }
}
Also used : Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) StandardContext(org.apache.catalina.core.StandardContext) HttpSessionListener(javax.servlet.http.HttpSessionListener) IOException(java.io.IOException) NotSerializableException(java.io.NotSerializableException) WriteAbortedException(java.io.WriteAbortedException) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) HttpSessionEvent(javax.servlet.http.HttpSessionEvent) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Aggregations

GenericPrincipal (org.apache.catalina.realm.GenericPrincipal)33 Principal (java.security.Principal)12 Subject (javax.security.auth.Subject)9 Test (org.junit.Test)9 Session (org.apache.catalina.Session)5 ArrayList (java.util.ArrayList)4 CdiEventRealm (org.apache.tomee.catalina.realm.CdiEventRealm)4 CallerPrincipalCallback (jakarta.security.auth.message.callback.CallerPrincipalCallback)3 CallbackHandler (javax.security.auth.callback.CallbackHandler)3 KeycloakSecurityContext (org.keycloak.KeycloakSecurityContext)3 RefreshableKeycloakSecurityContext (org.keycloak.adapters.RefreshableKeycloakSecurityContext)3 GroupPrincipalCallback (jakarta.security.auth.message.callback.GroupPrincipalCallback)2 PasswordValidationCallback (jakarta.security.auth.message.callback.PasswordValidationCallback)2 IOException (java.io.IOException)2 ObjectInputStream (java.io.ObjectInputStream)2 ObjectOutputStream (java.io.ObjectOutputStream)2 Callback (javax.security.auth.callback.Callback)2 HttpSession (javax.servlet.http.HttpSession)2 CallerPrincipal (org.apache.openejb.spi.CallerPrincipal)2 AuthException (jakarta.security.auth.message.AuthException)1