org.apache.catalina.Realm Java Examples

The following examples show how to use org.apache.catalina.Realm. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Request.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Return <code>true</code> if the authenticated user principal
 * possesses the specified role name.
 *
 * @param role Role name to be validated
 */
@Override
public boolean isUserInRole(String role) {

    // Have we got an authenticated principal at all?
    if (userPrincipal == null) {
        return false;
    }

    // Identify the Realm we will use for checking role assignments
    if (context == null) {
        return false;
    }

    Realm realm = context.getRealm();
    if (realm == null) {
        return false;
    }

    // Check for a role defined directly as a <security-role>
    return (realm.hasRole(wrapper, userPrincipal, role));
}
 
Example #2
Source File: CombinedRealm.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare for the beginning of active use of the public methods of this
 * component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {
    // Start 'sub-realms' then this one
    Iterator<Realm> iter = realms.iterator();
    
    while (iter.hasNext()) {
        Realm realm = iter.next();
        if (realm instanceof Lifecycle) {
            try {
                ((Lifecycle) realm).start();
            } catch (LifecycleException e) {
                // If realm doesn't start can't authenticate against it
                iter.remove();
                log.error(sm.getString("combinedRealm.realmStartFail",
                        realm.getInfo()), e);
            }
        }
    }
    super.startInternal();
}
 
Example #3
Source File: Tomcat7Valve.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
public boolean authorize(Principal principal, List roles)
{
    Realm realm = valve.getContainer().getRealm();
    Iterator iter = roles.iterator();
    while (iter.hasNext())
    {
        String role = (String)iter.next();
        // For Tomcat 7, we need to get the wrapper from the request to support role mapping in the web.xml.
        // This is only supported for servlet endpoints. For NIO endpoints, the wrapper will be null.
        Wrapper wrapper = null;
        if (request != null)
        {
            // in the servlet case get the wrapper
            wrapper = request.getWrapper();
        }
        // for nio the wrapper will be null
        if (realm.hasRole(wrapper, principal, role))
            return true;
    }
    return false;
}
 
Example #4
Source File: RealmSF.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Store the specified Realm properties and child (Realm)
 *
 * @param aWriter
 *            PrintWriter to which we are storing
 * @param indent
 *            Number of spaces to indent this element
 * @param aRealm
 *            Realm whose properties are being stored
 *
 * @exception Exception
 *                if an exception occurs while storing
 */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aRealm,
        StoreDescription parentDesc) throws Exception {
    if (aRealm instanceof CombinedRealm) {
        CombinedRealm combinedRealm = (CombinedRealm) aRealm;

        // Store nested <Realm> element
        Realm[] realms = combinedRealm.getNestedRealms();
        storeElementArray(aWriter, indent, realms);
    }
    // Store nested <CredentialHandler> element
    CredentialHandler credentialHandler = ((Realm) aRealm).getCredentialHandler();
    if (credentialHandler != null) {
        storeElement(aWriter, indent, credentialHandler);
    }
}
 
Example #5
Source File: CombinedRealm.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare for the beginning of active use of the public methods of this
 * component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {
    // Start 'sub-realms' then this one
    Iterator<Realm> iter = realms.iterator();
    
    while (iter.hasNext()) {
        Realm realm = iter.next();
        if (realm instanceof Lifecycle) {
            try {
                ((Lifecycle) realm).start();
            } catch (LifecycleException e) {
                // If realm doesn't start can't authenticate against it
                iter.remove();
                log.error(sm.getString("combinedRealm.realmStartFail",
                        realm.getInfo()), e);
            }
        }
    }
    super.startInternal();
}
 
Example #6
Source File: MBeanUtils.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Deregister the MBean for this
 * <code>Realm</code> object.
 *
 * @param realm The Realm to be managed
 *
 * @exception Exception if an MBean cannot be deregistered
 * @deprecated  Unused. Will be removed in Tomcat 8.0.x
 */
@Deprecated
static void destroyMBean(Realm realm)
    throws Exception {

    String mname = createManagedName(realm);
    ManagedBean managed = registry.findManagedBean(mname);
    if (managed == null) {
        return;
    }
    String domain = managed.getDomain();
    if (domain == null)
        domain = mserver.getDefaultDomain();
    ObjectName oname = createObjectName(domain, realm);
    if( mserver.isRegistered(oname) )
        mserver.unregisterMBean(oname);

}
 
Example #7
Source File: CombinedRealm.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return <code>null</code>.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 *  authenticating this username
 */
@Override
public Principal authenticate(String username, String credentials) {
    Principal authenticatedUser = null;
    
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
        }

        authenticatedUser = realm.authenticate(username, credentials);

        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
            }
            break;
        }
    }
    return authenticatedUser;
}
 
Example #8
Source File: CombinedRealm.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return <code>null</code>.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 *  authenticating this username
 */
@Override
public Principal authenticate(String username, String credentials) {
    Principal authenticatedUser = null;
    
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
        }

        authenticatedUser = realm.authenticate(username, credentials);

        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
            }
            break;
        }
    }
    return authenticatedUser;
}
 
Example #9
Source File: ContainerBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Return the Realm with which this Container is associated.  If there is
 * no associated Realm, return the Realm associated with our parent
 * Container (if any); otherwise return <code>null</code>.
 */
@Override
public Realm getRealm() {

    Lock l = realmLock.readLock();
    l.lock();
    try {
        if (realm != null)
            return realm;
        if (parent != null)
            return parent.getRealm();
        return null;
    } finally {
        l.unlock();
    }
}
 
Example #10
Source File: Request.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Return <code>true</code> if the authenticated user principal
 * possesses the specified role name.
 *
 * @param role Role name to be validated
 */
@Override
public boolean isUserInRole(String role) {

    // Have we got an authenticated principal at all?
    if (userPrincipal == null) {
        return false;
    }

    // Identify the Realm we will use for checking role assignments
    if (context == null) {
        return false;
    }

    Realm realm = context.getRealm();
    if (realm == null) {
        return false;
    }

    // Check for a role defined directly as a <security-role>
    return (realm.hasRole(wrapper, userPrincipal, role));
}
 
Example #11
Source File: CombinedRealm.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Prepare for the beginning of active use of the public methods of this
 * component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {
    // Start 'sub-realms' then this one
    Iterator<Realm> iter = realms.iterator();

    while (iter.hasNext()) {
        Realm realm = iter.next();
        if (realm instanceof Lifecycle) {
            try {
                ((Lifecycle) realm).start();
            } catch (LifecycleException e) {
                // If realm doesn't start can't authenticate against it
                iter.remove();
                log.error(sm.getString("combinedRealm.realmStartFail",
                        realm.getClass().getName()), e);
            }
        }
    }
    super.startInternal();
}
 
Example #12
Source File: CombinedRealm.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Delegate the backgroundProcess call to all sub-realms.
 */
@Override
public void backgroundProcess() {
    super.backgroundProcess();

    for (Realm r : realms) {
        r.backgroundProcess();
    }
}
 
Example #13
Source File: CombinedRealm.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Return the Principal associated with the specified user name otherwise
 * return <code>null</code>.
 *
 * @param username User name of the Principal to look up
 */
@Override
public Principal authenticate(String username) {
    Principal authenticatedUser = null;

    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username,
                    realm.getClass().getName()));
        }

        authenticatedUser = realm.authenticate(username);

        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username,
                        realm.getClass().getName()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess",
                        username, realm.getClass().getName()));
            }
            break;
        }
    }
    return authenticatedUser;
}
 
Example #14
Source File: CombinedRealm.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Set the Container with which this Realm has been associated.
 *
 * @param container The associated Container
 */
@Override
public void setContainer(Container container) {
    for(Realm realm : realms) {
        // Set the realmPath for JMX naming
        if (realm instanceof RealmBase) {
            ((RealmBase) realm).setRealmPath(
                    getRealmPath() + "/realm" + realms.indexOf(realm));
        }
        
        // Set the container for sub-realms. Mainly so logging works.
        realm.setContainer(container);
    }
    super.setContainer(container);
}
 
Example #15
Source File: CombinedRealm.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Add a realm to the list of realms that will be used to authenticate
 * users.
 */
public void addRealm(Realm theRealm) {
    realms.add(theRealm);
    
    if (log.isDebugEnabled()) {
        sm.getString("combinedRealm.addRealm", theRealm.getInfo(), 
                Integer.toString(realms.size()));
    }
}
 
Example #16
Source File: ConfTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void run() {
    try (final Container container = new Container(new Configuration().conf("ConfTest"))) {
        final StandardServer standardServer = TomcatHelper.getServer();
        final Realm engineRealm = standardServer.findServices()[0].getContainer().getRealm();
        assertTrue(String.valueOf(engineRealm), TomEERealm.class.isInstance(engineRealm));
        assertTrue(String.valueOf(engineRealm), JAASRealm.class.isInstance(TomEERealm.class.cast(engineRealm).getNestedRealms()[0]));
        final JAASRealm jaas = JAASRealm.class.cast(TomEERealm.class.cast(engineRealm).getNestedRealms()[0]);
        assertEquals("PropertiesLoginModule", jaas.getAppName());
        assertEquals("org.apache.openejb.core.security.jaas.UserPrincipal", jaas.getUserClassNames());
        assertEquals("org.apache.openejb.core.security.jaas.GroupPrincipal", jaas.getRoleClassNames());

        assertEquals("test", SystemInstance.get().getProperty("ConfTest.value"));
    }
}
 
Example #17
Source File: CombinedRealm.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure child Realms are destroyed when this Realm is destroyed.
 */
@Override
protected void destroyInternal() throws LifecycleException {
    for (Realm realm : realms) {
        if (realm instanceof Lifecycle) {
            ((Lifecycle) realm).destroy();
        }
    }
    super.destroyInternal();
}
 
Example #18
Source File: CombinedRealm.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Gracefully terminate the active use of the public methods of this
 * component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that needs to be reported
 */
 @Override
protected void stopInternal() throws LifecycleException {
    // Stop this realm, then the sub-realms (reverse order to start)
    super.stopInternal();
    for (Realm realm : realms) {
        if (realm instanceof Lifecycle) {
            ((Lifecycle) realm).stop();
        }
    }        
}
 
Example #19
Source File: DigestAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public Principal authenticate(Realm realm) {
    // Second MD5 digest used to calculate the digest :
    // MD5(Method + ":" + uri)
    String a2 = method + ":" + uri;

    byte[] buffer = ConcurrentMessageDigest.digestMD5(
            a2.getBytes(B2CConverter.ISO_8859_1));
    String md5a2 = MD5Encoder.encode(buffer);

    return realm.authenticate(userName, response, nonce, nc, cnonce,
            qop, realmName, md5a2);
}
 
Example #20
Source File: AuthenticatorBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts reauthentication to the <code>Realm</code> using
 * the credentials included in argument <code>entry</code>.
 *
 * @param ssoId identifier of SingleSignOn session with which the
 *              caller is associated
 * @param request   the request that needs to be authenticated
 */
protected boolean reauthenticateFromSSO(String ssoId, Request request) {

    if (sso == null || ssoId == null)
        return false;

    boolean reauthenticated = false;

    Container parent = getContainer();
    if (parent != null) {
        Realm realm = parent.getRealm();
        if (realm != null) {
            reauthenticated = sso.reauthenticate(ssoId, realm, request);
        }
    }

    if (reauthenticated) {
        associate(ssoId, request.getSessionInternal(true));

        if (log.isDebugEnabled()) {
            log.debug(" Reauthenticated cached principal '" +
                      request.getUserPrincipal().getName() +
                      "' with auth type '" +  request.getAuthType() + "'");
        }
    }

    return reauthenticated;
}
 
Example #21
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void addTomEERealm(final Engine engine) {
    final Realm realm = engine.getRealm();
    if (realm != null && !(realm instanceof TomEERealm) && (engine.getParent() == null || (!realm.equals(engine.getParent().getRealm())))) {
        final Realm tomeeRealm = tomeeRealm(realm);
        engine.setRealm(tomeeRealm);
        if (LifecycleState.STARTING_PREP.equals(engine.getState())) {
            try {
                Lifecycle.class.cast(tomeeRealm).start();
            } catch (final LifecycleException e) {
                throw new IllegalStateException(e);
            }
        }
    }
}
 
Example #22
Source File: JBossWebPrincipalFactoryTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Constructor constructor = JBossWebPrincipalFactory.findJBossGenericPrincipalConstructor();
    Assert.assertNotNull(constructor);
    Assert.assertEquals(Realm.class, constructor.getParameterTypes()[0]);
    Assert.assertEquals(String.class, constructor.getParameterTypes()[1]);
    Assert.assertEquals(List.class, constructor.getParameterTypes()[3]);
    Assert.assertEquals(Principal.class, constructor.getParameterTypes()[4]);
    Assert.assertEquals(Object.class, constructor.getParameterTypes()[6]);
    Assert.assertEquals(Subject.class, constructor.getParameterTypes()[8]);
}
 
Example #23
Source File: TomcatServiceConfig.java    From armeria with Apache License 2.0 5 votes vote down vote up
static String toString(Object holder, String serviceName, @Nullable String engineName,
                       @Nullable Path baseDir, @Nullable Realm realm, @Nullable String hostname,
                       Path docBase, @Nullable String jarRoot) {

    return holder.getClass().getSimpleName() +
           "(serviceName: " + serviceName +
           ", engineName: " + engineName +
           ", baseDir: " + baseDir +
           ", realm: " + (realm != null ? realm.getClass().getSimpleName() : "null") +
           ", hostname: " + hostname +
           ", docBase: " + docBase +
           (jarRoot != null ? ", jarRoot: " + jarRoot : "") +
           ')';
}
 
Example #24
Source File: Tomcat.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * For complex configurations, this accessor allows callers of this class
 * to obtain the simple realm created by default.
 * @return the simple in-memory realm created by default.
 * @deprecated Will be removed in Tomcat 8.0.x
 */
@Deprecated
public Realm getDefaultRealm() {
    if (defaultRealm == null) {
        initSimpleAuth();
    }
    return defaultRealm;
}
 
Example #25
Source File: TomcatSecurityService.java    From tomee with Apache License 2.0 5 votes vote down vote up
public TomcatUser(final Realm realm, final Principal tomcatPrincipal) {
    if (realm == null) {
        throw new NullPointerException("realm is null");
    }
    if (tomcatPrincipal == null) {
        throw new NullPointerException("tomcatPrincipal is null");
    }
    this.realm = realm;
    this.tomcatPrincipal = tomcatPrincipal;
}
 
Example #26
Source File: Embedded.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Set the default Realm for our Containers.
 *
 * @param realm The new default realm
 */
public void setRealm(Realm realm) {

    Realm oldRealm = this.realm;
    this.realm = realm;
    support.firePropertyChange("realm", oldRealm, this.realm);

}
 
Example #27
Source File: TomEERealm.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasRole(final Wrapper wrapper, final Principal principal, final String rawRole) {
    String role = rawRole;

    // Check for a role alias defined in a <security-role-ref> element
    if (wrapper != null) {
        final String realRole = wrapper.findSecurityReference(role);
        if (realRole != null) {
            role = realRole;
        }
    }

    if (principal == null || role == null) {
        return false;
    }

    if (principal instanceof  GenericPrincipal) {
        return ((GenericPrincipal) principal).hasRole(role);
    }

    for (final Realm realm : realms) { // when used implicitely (always?) realms.size == 1 so no need of a strategy
        if (realm.hasRole(wrapper, principal, rawRole)) {
            return true;
        }
    }
    return false;
}
 
Example #28
Source File: Embedded.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new instance of this class with specified properties.
 *
 * @param realm Realm implementation to be inherited by all components
 *  (unless overridden further down the container hierarchy)
 */
public Embedded(Realm realm) {

    super();
    setRealm(realm);
    setSecurityProtection();
    
}
 
Example #29
Source File: ContainerBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void destroyInternal() throws LifecycleException {

    if ((manager != null) && (manager instanceof Lifecycle)) {
        ((Lifecycle) manager).destroy();
    }
    Realm realm = getRealmInternal();
    if ((realm != null) && (realm instanceof Lifecycle)) {
        ((Lifecycle) realm).destroy();
    }
    if ((cluster != null) && (cluster instanceof Lifecycle)) {
        ((Lifecycle) cluster).destroy();
    }
    if ((loader != null) && (loader instanceof Lifecycle)) {
        ((Lifecycle) loader).destroy();
    }

    // Stop the Valves in our pipeline (including the basic), if any
    if (pipeline instanceof Lifecycle) {
        ((Lifecycle) pipeline).destroy();
    }

    // Remove children now this container is being destroyed
    for (Container child : findChildren()) {
        removeChild(child);
    }

    // Required if the child is destroyed directly.
    if (parent != null) {
        parent.removeChild(this);
    }

    // If init fails, this may be null
    if (startStopExecutor != null) {
        startStopExecutor.shutdownNow();
    }

    super.destroyInternal();
}
 
Example #30
Source File: TomcatValve.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
public boolean authorize(Principal principal, List roles)
{
    Realm realm = container.getRealm();
    Iterator iter = roles.iterator();
    while (iter.hasNext())
    {
        String role = (String)iter.next();
        if (realm.hasRole(principal, role))
            return true;
    }
    return false;
}