Java Code Examples for org.apache.catalina.realm.GenericPrincipal

The following examples show how to use org.apache.catalina.realm.GenericPrincipal. These examples are extracted from open source projects. 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 Project: Tomcat8-Source-Read   Source File: CallbackHandlerImpl.java    License: MIT License 6 votes vote down vote up
private Principal getPrincipal(Principal principal, String name, String[] groups) {
    // If the Principal is cached in the session JASPIC may simply return it
    if (principal instanceof GenericPrincipal) {
        return principal;
    }
    if (name == null && principal != null) {
        name = principal.getName();
    }
    if (name == null) {
        return null;
    }
    List<String> roles;
    if (groups == null || groups.length == 0) {
        roles = Collections.emptyList();
    } else {
        roles = Arrays.asList(groups);
    }

    return new GenericPrincipal(name, null, roles, principal);
}
 
Example 2
Source Project: tomee   Source File: TomcatSecurityService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isCallerInRole(final String role) {
    final Principal principal = getCallerPrincipal();
    if (TomcatUser.class.isInstance(principal)) {
        if ("**".equals(role)) {
            return true; // ie logged in through tomcat
        }

        final TomcatUser tomcatUser = (TomcatUser) principal;
        final GenericPrincipal genericPrincipal = (GenericPrincipal) tomcatUser.getTomcatPrincipal();
        final String[] roles = genericPrincipal.getRoles();
        if (roles != null) {
            for (final String userRole : roles) {
                if (userRole.equals(role)) {
                    return true;
                }
            }
        }
        return false;
    }
    return super.isCallerInRole(role);
}
 
Example 3
Source Project: keycloak   Source File: CatalinaSessionTokenStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void saveAccountInfo(OidcKeycloakAccount account) {
    RefreshableKeycloakSecurityContext securityContext = (RefreshableKeycloakSecurityContext) account.getKeycloakSecurityContext();
    Set<String> roles = account.getRoles();
    GenericPrincipal principal = principalFactory.createPrincipal(request.getContext().getRealm(), account.getPrincipal(), roles);

    SerializableKeycloakAccount sAccount = new SerializableKeycloakAccount(roles, account.getPrincipal(), securityContext);
    Session session = request.getSessionInternal(true);
    session.setPrincipal(principal);
    session.setAuthType("KEYCLOAK");
    session.getSession().setAttribute(SerializableKeycloakAccount.class.getName(), sAccount);
    session.getSession().setAttribute(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
    String username = securityContext.getToken().getSubject();
    log.fine("userSessionManagement.login: " + username);
    this.sessionManagement.login(session);
}
 
Example 4
Source Project: keycloak   Source File: CatalinaCookieTokenStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isCached(RequestAuthenticator authenticator) {
    // Assuming authenticatedPrincipal set by previous call of checkCurrentToken() during this request
    if (authenticatedPrincipal != null) {
        log.fine("remote logged in already. Establish state from cookie");
        RefreshableKeycloakSecurityContext securityContext = authenticatedPrincipal.getKeycloakSecurityContext();

        if (!securityContext.getRealm().equals(deployment.getRealm())) {
            log.fine("Account from cookie is from a different realm than for the request.");
            return false;
        }

        securityContext.setCurrentRequestInfo(deployment, this);
        Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
        GenericPrincipal principal = principalFactory.createPrincipal(request.getContext().getRealm(), authenticatedPrincipal, roles);

        request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
        request.setUserPrincipal(principal);
        request.setAuthType("KEYCLOAK");
        return true;
    } else {
        return false;
    }
}
 
Example 5
Source Project: keycloak   Source File: GenericPrincipalFactory.java    License: Apache License 2.0 6 votes vote down vote up
public GenericPrincipal createPrincipal(Realm realm, final Principal identity, final Set<String> roleSet) {
    Subject subject = new Subject();
    Set<Principal> principals = subject.getPrincipals();
    principals.add(identity);
    Group[] roleSets = getRoleSets(roleSet);
    for (int g = 0; g < roleSets.length; g++) {
        Group group = roleSets[g];
        String name = group.getName();
        Group subjectGroup = createGroup(name, principals);
        // Copy the group members to the Subject group
        Enumeration<? extends Principal> members = group.members();
        while (members.hasMoreElements()) {
            Principal role = (Principal) members.nextElement();
            subjectGroup.addMember(role);
        }
    }
    
    Principal userPrincipal = getPrincipal(subject);
    List<String> rolesAsStringList = new ArrayList<String>();
    rolesAsStringList.addAll(roleSet);
    GenericPrincipal principal = createPrincipal(userPrincipal, rolesAsStringList);
    return principal;
}
 
Example 6
Source Project: keycloak   Source File: CatalinaSamlSessionStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void saveAccount(SamlSession account) {
    Session session = request.getSessionInternal(true);
    session.getSession().setAttribute(SamlSession.class.getName(), account);
    GenericPrincipal principal = (GenericPrincipal) session.getPrincipal();
    // in clustered environment in JBossWeb, principal is not serialized or saved
    if (principal == null) {
        principal = principalFactory.createPrincipal(request.getContext().getRealm(), account.getPrincipal(), account.getRoles());
        session.setPrincipal(principal);
        session.setAuthType("KEYCLOAK-SAML");

    }
    request.setUserPrincipal(principal);
    request.setAuthType("KEYCLOAK-SAML");
    String newId = changeSessionId(session);
    idMapperUpdater.map(idMapper, account.getSessionIndex(), account.getPrincipal().getSamlSubject(), newId);

}
 
Example 7
Source Project: teamengine   Source File: PBKDF2Realm.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the Principal associated with the specified username and
 * credentials, if one exists in the user data store; otherwise return null.
 */
@Override
public Principal authenticate(String username, String credentials) {
    GenericPrincipal principal = (GenericPrincipal) getPrincipal(username);
    if (null != principal) {
        try {
            if (!PasswordStorage.verifyPassword(credentials, principal.getPassword())) {
                principal = null;
            }
        } catch (CannotPerformOperationException | InvalidHashException e) {
            LOGR.log(Level.WARNING, e.getMessage());
            principal = null;
        }
    }
    return principal;
}
 
Example 8
Source Project: Tomcat8-Source-Read   Source File: AuthenticatorBase.java    License: MIT License 5 votes vote down vote up
private GenericPrincipal getPrincipal(Subject subject) {
    if (subject == null) {
        return null;
    }

    Set<GenericPrincipal> principals = subject.getPrivateCredentials(GenericPrincipal.class);
    if (principals.isEmpty()) {
        return null;
    }

    return principals.iterator().next();
}
 
Example 9
Source Project: Tomcat7.0.67   Source File: SerializablePrincipal.java    License: Apache License 2.0 5 votes vote down vote up
public static SerializablePrincipal createPrincipal(GenericPrincipal principal)
{
    if ( principal==null) return null;
    return new SerializablePrincipal(principal.getName(),
                                     principal.getPassword(),
                                     principal.getRoles()!=null?Arrays.asList(principal.getRoles()):null,
                                     principal.getUserPrincipal()!=principal?principal.getUserPrincipal():null);
}
 
Example 10
Source Project: Tomcat7.0.67   Source File: SerializablePrincipal.java    License: Apache License 2.0 5 votes vote down vote up
public static void writePrincipal(GenericPrincipal p, ObjectOutput out)
        throws IOException {
    out.writeUTF(p.getName());
    out.writeBoolean(p.getPassword()!=null);
    if ( p.getPassword()!= null ) out.writeUTF(p.getPassword());
    String[] roles = p.getRoles();
    if ( roles == null ) roles = new String[0];
    out.writeInt(roles.length);
    for ( int i=0; i<roles.length; i++ ) out.writeUTF(roles[i]);
    boolean hasUserPrincipal = (p != p.getUserPrincipal() &&
            p.getUserPrincipal() instanceof Serializable);
    out.writeBoolean(hasUserPrincipal);
    if (hasUserPrincipal) out.writeObject(p.getUserPrincipal());
}
 
Example 11
Source Project: Tomcat7.0.67   Source File: DeltaRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * convert principal at SerializablePrincipal for backup nodes.
 * Only support principals from type {@link GenericPrincipal GenericPrincipal}
 * @param p Session principal
 * @see GenericPrincipal
 */
public void setPrincipal(Principal p) {
    int action = (p==null)?ACTION_REMOVE:ACTION_SET;
    SerializablePrincipal sp = null;
    if ( p != null ) {
        if(p instanceof GenericPrincipal) {
            sp = SerializablePrincipal.createPrincipal((GenericPrincipal)p);
            if(log.isDebugEnabled())
                log.debug(sm.getString("deltaRequest.showPrincipal", p.getName() , getSessionId()));
        } else
            log.error(sm.getString("deltaRequest.wrongPrincipalClass",p.getClass().getName()));
    }
    addAction(TYPE_PRINCIPAL,action,NAME_PRINCIPAL,sp);
}
 
Example 12
Source Project: Tomcat7.0.67   Source File: Request.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object get(Request request, String name) {
    if (request.userPrincipal instanceof GenericPrincipal) {
        return ((GenericPrincipal) request.userPrincipal)
                .getGssCredential();
    }
    return null;
}
 
Example 13
Source Project: jwala   Source File: JwalaAuthenticationProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param authentication
 * @return Authentication
 */
@Override
public Authentication authenticate(Authentication authentication) {
    Realm realm;
    Set<GrantedAuthority> auths = new HashSet<>();
    try {
        realm = getTomcatContextRealm();
        if(realm instanceof NullRealm) {
            throw new ProviderNotFoundException("No Realms configured for Jwala to Authenticate");
        }
        Principal principal = realm.authenticate(authentication.getName(),
                authentication.getCredentials().toString());
        if (principal == null) {
            throw new BadCredentialsException("Username or Password not found.");
        } else {
            if (principal instanceof GenericPrincipal) {
                String[] roles = ((GenericPrincipal) principal).getRoles();
                for (String role : roles) {
                    auths.add(new SimpleGrantedAuthority(role));
                }
            }
            GrantedAuthoritiesMapperImpl grantedAuthoritiesMapper = new GrantedAuthoritiesMapperImpl();
            return new UsernamePasswordAuthenticationToken(authentication.getName(),
                    authentication.getCredentials(), grantedAuthoritiesMapper.mapAuthorities(auths));
        }
    } catch (AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException e) {
        LOGGER.error("Error getting realms", e);
        throw new ProviderNotFoundException(e.getMessage());
    }
}
 
Example 14
Source Project: scipio-erp   Source File: ScipioRealm.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Principal getPrincipal(String username) {
    List<String> roles = new ArrayList<>();
    return new GenericPrincipal(username,
            getPassword(username),
            roles);
}
 
Example 15
Source Project: tomcatsrc   Source File: SerializablePrincipal.java    License: Apache License 2.0 5 votes vote down vote up
public static SerializablePrincipal createPrincipal(GenericPrincipal principal)
{
    if ( principal==null) return null;
    return new SerializablePrincipal(principal.getName(),
                                     principal.getPassword(),
                                     principal.getRoles()!=null?Arrays.asList(principal.getRoles()):null,
                                     principal.getUserPrincipal()!=principal?principal.getUserPrincipal():null);
}
 
Example 16
Source Project: tomcatsrc   Source File: SerializablePrincipal.java    License: Apache License 2.0 5 votes vote down vote up
public static void writePrincipal(GenericPrincipal p, ObjectOutput out)
        throws IOException {
    out.writeUTF(p.getName());
    out.writeBoolean(p.getPassword()!=null);
    if ( p.getPassword()!= null ) out.writeUTF(p.getPassword());
    String[] roles = p.getRoles();
    if ( roles == null ) roles = new String[0];
    out.writeInt(roles.length);
    for ( int i=0; i<roles.length; i++ ) out.writeUTF(roles[i]);
    boolean hasUserPrincipal = (p != p.getUserPrincipal() &&
            p.getUserPrincipal() instanceof Serializable);
    out.writeBoolean(hasUserPrincipal);
    if (hasUserPrincipal) out.writeObject(p.getUserPrincipal());
}
 
Example 17
Source Project: tomcatsrc   Source File: DeltaRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * convert principal at SerializablePrincipal for backup nodes.
 * Only support principals from type {@link GenericPrincipal GenericPrincipal}
 * @param p Session principal
 * @see GenericPrincipal
 */
public void setPrincipal(Principal p) {
    int action = (p==null)?ACTION_REMOVE:ACTION_SET;
    SerializablePrincipal sp = null;
    if ( p != null ) {
        if(p instanceof GenericPrincipal) {
            sp = SerializablePrincipal.createPrincipal((GenericPrincipal)p);
            if(log.isDebugEnabled())
                log.debug(sm.getString("deltaRequest.showPrincipal", p.getName() , getSessionId()));
        } else
            log.error(sm.getString("deltaRequest.wrongPrincipalClass",p.getClass().getName()));
    }
    addAction(TYPE_PRINCIPAL,action,NAME_PRINCIPAL,sp);
}
 
Example 18
Source Project: tomcatsrc   Source File: Request.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object get(Request request, String name) {
    if (request.userPrincipal instanceof GenericPrincipal) {
        return ((GenericPrincipal) request.userPrincipal)
                .getGssCredential();
    }
    return null;
}
 
Example 19
Source Project: flex-blazeds   Source File: Tomcat7Valve.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
public Principal convertPrincipal(Principal principal)
{
    if (principal instanceof GenericPrincipal)
    {
        return principal;
    }
    else
    {
        // We need to do the converting
        if (principal instanceof AbstractUser)
        {
            AbstractUser abstractUser = (AbstractUser) principal;
            List<String> roles = new ArrayList<String> ();
            Iterator roleIterator = abstractUser.getRoles();
            while (roleIterator.hasNext())
            {
                Role role = (Role) roleIterator.next();
                roles.add(role.getName());
            }
            String userName = abstractUser.getUsername();
            String password = abstractUser.getPassword();
            return new GenericPrincipal(userName, password, roles);
            
        }
        else
        {
            // no
            return principal;
        }
    }
}
 
Example 20
Source Project: tomee   Source File: TomEESecurityContext.java    License: Apache License 2.0 5 votes vote down vote up
public static void registerContainerAboutLogin(final Principal principal, final Set<String> groups) {
    final SecurityService securityService = SystemInstance.get().getComponent(SecurityService.class);
    if (TomcatSecurityService.class.isInstance(securityService)) {
        final TomcatSecurityService tomcatSecurityService = (TomcatSecurityService) securityService;
        final Request request = OpenEJBSecurityListener.requests.get();
        final GenericPrincipal genericPrincipal =
                new GenericPrincipal(principal.getName(), null, new ArrayList<>(groups), principal);
        tomcatSecurityService.enterWebApp(request.getWrapper().getRealm(),
                                          genericPrincipal,
                                          request.getWrapper().getRunAs());
    }
}
 
Example 21
Source Project: tomee   Source File: TomEERealm.java    License: 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 22
Source Project: tomee   Source File: CdiEventRealmTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void userPassword() {
    final GenericPrincipal gp = getGenericPrincipal(new CdiEventRealm().authenticate("john", "secret"));
    assertEquals("john", gp.getName());
    assertEquals("", gp.getPassword());
    assertEquals(1, gp.getRoles().length);
    assertEquals("admin", gp.getRoles()[0]);
}
 
Example 23
Source Project: tomee   Source File: CdiEventRealmTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void digest() {
    final GenericPrincipal gp = getGenericPrincipal(new CdiEventRealm().authenticate("ryan", "md5", "nonce", "nc", "cnonce", "qop", "realm", "md5a2"));
    final String[] actual = gp.getRoles();
    final String[] expected = new String[] {"ryan", "md5", "nonce", "nc", "cnonce", "qop", "realm", "md5a2"};

    Arrays.sort(actual);
    Arrays.sort(expected);

    assertArrayEquals(actual, expected);
}
 
Example 24
Source Project: tomee   Source File: CdiEventRealmTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void gss() {
    final GenericPrincipal gp = getGenericPrincipal(new CdiEventRealm().authenticate(mock(GSSContext.class), false));
    assertEquals("gss", gp.getName());
    assertEquals("", gp.getPassword());
    assertEquals(1, gp.getRoles().length);
    assertEquals("dummy", gp.getRoles()[0]);
}
 
Example 25
Source Project: tomee   Source File: CdiEventRealmTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void ssl() {
    X509Certificate cert = mock(X509Certificate.class);
    GenericPrincipal expected = new GenericPrincipal("john", "doe", Arrays.asList("test"));
    when(cert.getSubjectDN()).thenReturn(expected);
    final GenericPrincipal gp = getGenericPrincipal(new CdiEventRealm().authenticate(new X509Certificate[] { cert }));
    assertEquals(expected, gp);
    assertEquals("john", gp.getName());
    assertEquals("doe", gp.getPassword());
    assertEquals(1, gp.getRoles().length);
    assertEquals("test", gp.getRoles()[0]);
}
 
Example 26
Source Project: tomee   Source File: CdiEventRealmTest.java    License: Apache License 2.0 5 votes vote down vote up
public void authenticate(@Observes final DigestAuthenticationEvent event) {
    final List<String> roles = new ArrayList<>();
    roles.add(event.getCnonce());
    roles.add(event.getDigest());
    roles.add(event.getMd5a2());
    roles.add(event.getNc());
    roles.add(event.getNonce());
    roles.add(event.getQop());
    roles.add(event.getRealm());
    roles.add(event.getUsername());
    event.setPrincipal(new GenericPrincipal(event.getUsername(), "", roles));
}
 
Example 27
Source Project: keycloak   Source File: KeycloakAuthenticatorValve.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected GenericPrincipalFactory createPrincipalFactory() {
    return new GenericPrincipalFactory() {
        @Override
        protected GenericPrincipal createPrincipal(Principal userPrincipal, List<String> roles) {
            return new GenericPrincipal(userPrincipal.getName(), null, roles, userPrincipal, null);
        }
    };
}
 
Example 28
Source Project: keycloak   Source File: CatalinaSessionTokenStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isCached(RequestAuthenticator authenticator) {
    Session session = request.getSessionInternal(false);
    if (session == null) return false;
    SerializableKeycloakAccount account = (SerializableKeycloakAccount) session.getSession().getAttribute(SerializableKeycloakAccount.class.getName());
    if (account == null) {
        return false;
    }

    log.fine("remote logged in already. Establish state from session");

    RefreshableKeycloakSecurityContext securityContext = account.getKeycloakSecurityContext();

    if (!deployment.getRealm().equals(securityContext.getRealm())) {
        log.fine("Account from cookie is from a different realm than for the request.");
        cleanSession(session);
        return false;
    }

    securityContext.setCurrentRequestInfo(deployment, this);
    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
    GenericPrincipal principal = (GenericPrincipal) session.getPrincipal();
    // in clustered environment in JBossWeb, principal is not serialized or saved
    if (principal == null) {
        principal = principalFactory.createPrincipal(request.getContext().getRealm(), account.getPrincipal(), account.getRoles());
        session.setPrincipal(principal);
        session.setAuthType("KEYCLOAK");

    }
    request.setUserPrincipal(principal);
    request.setAuthType("KEYCLOAK");

    restoreRequest();
    return true;
}
 
Example 29
Source Project: keycloak   Source File: KeycloakAuthenticatorValve.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected GenericPrincipalFactory createPrincipalFactory() {
    return new GenericPrincipalFactory() {
        @Override
        protected GenericPrincipal createPrincipal(Principal userPrincipal, List<String> roles) {
            return new GenericPrincipal(userPrincipal.getName(), null, roles, userPrincipal, null);
        }
    };
}
 
Example 30
Source Project: keycloak   Source File: CatalinaUserSessionManagement.java    License: Apache License 2.0 5 votes vote down vote up
public void sessionEvent(SessionEvent event) {
    // We only care about session destroyed events
    if (!Session.SESSION_DESTROYED_EVENT.equals(event.getType()))
        return;

    // Look up the single session id associated with this session (if any)
    Session session = event.getSession();
    log.debugf("Session %s destroyed", session.getId());

    GenericPrincipal principal = (GenericPrincipal) session.getPrincipal();
    if (principal == null) return;
    session.setPrincipal(null);
    session.setAuthType(null);
}