io.undertow.security.idm.Account Java Examples

The following examples show how to use io.undertow.security.idm.Account. 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: LightIdentityManager.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public Account verify(String id, Credential credential) {
    if (credential instanceof LightPasswordCredential) {
        LightPasswordCredential passwordCredential = (LightPasswordCredential) credential;
        String clientAuthClass = passwordCredential.getClientAuthClass();
        if(logger.isDebugEnabled()) logger.debug("LightPasswordCredential with clientAuthClass = " + clientAuthClass);
        // get authenticator object.
        Class clazz = DefaultAuth.class;
        if(clientAuthClass != null && clientAuthClass.trim().length() > 0) {
            try {
                clazz = Class.forName(clientAuthClass);
            } catch (ClassNotFoundException e) {
                logger.error("Authenticate Class " + clientAuthClass + " not found.", e);
                return null;
            }
        }
        if(logger.isDebugEnabled()) logger.debug("Get Authenticator implementation from service factory with clazz = " + clazz);
        Authenticator authenticator = SingletonServiceFactory.getBean(Authenticator.class, clazz);
        return authenticator.authenticate(id, credential);
    }
    return null;
}
 
Example #2
Source File: Identity.java    From mangooio with Apache License 2.0 6 votes vote down vote up
private static Account getAccount(String username) {
    return new Account() {
        private static final long serialVersionUID = 5311970975103831035L;
        private transient Principal principal = () -> username;

        @Override
        public Principal getPrincipal() {
            return principal;
        }

        @Override
        public Set<String> getRoles() {
            return Collections.emptySet();
        }
    };
}
 
Example #3
Source File: SecurityContextImpl.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public boolean login(final String username, final String password) {

    UndertowLogger.SECURITY_LOGGER.debugf("Attempting programatic login for user %s for request %s", username, exchange);

    final Account account;
    if(System.getSecurityManager() == null) {
        account = identityManager.verify(username, new PasswordCredential(password.toCharArray()));
    } else {
        account = AccessController.doPrivileged(new PrivilegedAction<Account>() {
            @Override
            public Account run() {
                return identityManager.verify(username, new PasswordCredential(password.toCharArray()));
            }
        });
    }

    if (account == null) {
        return false;
    }

    authenticationComplete(account, programaticMechName, true);
    this.authenticationState = AuthenticationState.AUTHENTICATED;

    return true;
}
 
Example #4
Source File: ServletClientCertAuthTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public Account verify(Credential credential) {
    if (credential instanceof X509CertificateCredential) {
        final Principal p = ((X509CertificateCredential) credential).getCertificate().getSubjectX500Principal();
        if (certUsers.contains(p.getName())) {
            return new Account() {

                @Override
                public Principal getPrincipal() {
                    return p;
                }

                @Override
                public Set<String> getRoles() {
                    return Collections.singleton("role1");
                }

            };
        }

    }
    return null;
}
 
Example #5
Source File: SecurityContextImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean login(final String username, final String password) {

    UndertowLogger.SECURITY_LOGGER.debugf("Attempting programatic login for user %s for request %s", username, exchange);

    final Account account;
    if(System.getSecurityManager() == null) {
        account = identityManager.verify(username, new PasswordCredential(password.toCharArray()));
    } else {
        account = AccessController.doPrivileged(new PrivilegedAction<Account>() {
            @Override
            public Account run() {
                return identityManager.verify(username, new PasswordCredential(password.toCharArray()));
            }
        });
    }

    if (account == null) {
        return false;
    }

    authenticationComplete(account, programaticMechName, true);
    this.authenticationState = AuthenticationState.AUTHENTICATED;

    return true;
}
 
Example #6
Source File: CachedAuthenticatedSessionMechanism.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public AuthenticationMechanismOutcome runCached(final HttpServerExchange exchange, final SecurityContext securityContext, final AuthenticatedSessionManager sessionManager) {
    AuthenticatedSession authSession = sessionManager.lookupSession(exchange);
    if (authSession != null) {
        Account account = getIdentityManager(securityContext).verify(authSession.getAccount());
        if (account != null) {
            securityContext.authenticationComplete(account, authSession.getMechanism(), false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            sessionManager.clearSession(exchange);
            // We know we had a previously authenticated account but for some reason the IdentityManager is no longer
            // accepting it, we now
            return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
        }
    } else {
        // It is possible an AuthenticatedSessionManager could have been available even if there was no chance of it
        // loading a session.
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }

}
 
Example #7
Source File: CachedAuthenticatedSessionMechanism.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public AuthenticationMechanismOutcome runCached(final HttpServerExchange exchange, final SecurityContext securityContext, final AuthenticatedSessionManager sessionManager) {
    AuthenticatedSession authSession = sessionManager.lookupSession(exchange);
    if (authSession != null) {
        Account account = getIdentityManager(securityContext).verify(authSession.getAccount());
        if (account != null) {
            securityContext.authenticationComplete(account, authSession.getMechanism(), false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            sessionManager.clearSession(exchange);
            // We know we had a previously authenticated account but for some reason the IdentityManager is no longer
            // accepting it, we now
            return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
        }
    } else {
        // It is possible an AuthenticatedSessionManager could have been available even if there was no chance of it
        // loading a session.
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }

}
 
Example #8
Source File: DefaultAuthorizationManager.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isUserInRole(String role, Account account, ServletInfo servletInfo, HttpServletRequest request, Deployment deployment) {

    final Map<String, Set<String>> principalVersusRolesMap = deployment.getDeploymentInfo().getPrincipalVersusRolesMap();
    final Set<String> roles = principalVersusRolesMap.get(account.getPrincipal().getName());
    //TODO: a more efficient imple
    for (SecurityRoleRef ref : servletInfo.getSecurityRoleRefs()) {
        if (ref.getRole().equals(role)) {
            if (roles != null && roles.contains(ref.getLinkedRole())) {
                return true;
            }
            return account.getRoles().contains(ref.getLinkedRole());
        }
    }
    if (roles != null && roles.contains(role)) {
        return true;
    }
    return account.getRoles().contains(role);
}
 
Example #9
Source File: CustomIdentityManager.java    From tutorials with MIT License 6 votes vote down vote up
private Account getAccount(final String id) {
    if (users.containsKey(id)) {
        return new Account() {

            private static final long serialVersionUID = 1L;

            private final Principal principal = () -> id;

            @Override
            public Principal getPrincipal() {
                return principal;
            }

            @Override
            public Set<String> getRoles() {
                return Collections.emptySet();
            }
        };
    }
    return null;
}
 
Example #10
Source File: DefaultAuthenticator.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
private Account getAccount(final String id) {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    if (users.containsKey(id)) {
        return new Account() {
            private Set<String> roles = parseRoles(users.get(id).getRoles());
            private final Principal principal = () -> id;
            @Override
            public Principal getPrincipal() {
                return principal;
            }
            @Override
            public Set<String> getRoles() { return roles; }
        };
    }
    return null;
}
 
Example #11
Source File: MapIdentityManager.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private Account getAccount(final String id) {
    if (users.containsKey(id)) {
        return new Account() {

            private final Principal principal = new Principal() {

                @Override
                public String getName() {
                    return id;
                }
            };

            @Override
            public Principal getPrincipal() {
                return principal;
            }

            @Override
            public Set<String> getRoles() {
                return Collections.emptySet();
            }

        };
    }
    return null;
}
 
Example #12
Source File: UndertowSamlAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void completeAuthentication(final SamlSession samlSession) {
    Account undertowAccount = new Account() {
        @Override
        public Principal getPrincipal() {
            return samlSession.getPrincipal();
        }

        @Override
        public Set<String> getRoles() {
            return samlSession.getRoles();
        }
    };
    securityContext.authenticationComplete(undertowAccount, "KEYCLOAK-SAML", false);

}
 
Example #13
Source File: GenericHeaderAuthenticationMechanism.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    String principal = getPrincipal(exchange);
    if(principal == null) {
        return NOT_ATTEMPTED;
    }
    String session = getSession(exchange);
    if(session == null) {
        return NOT_ATTEMPTED;
    }
    Account account = identityManager.verify(principal, new PasswordCredential(session.toCharArray()));
    if(account == null) {
        securityContext.authenticationFailed(UndertowMessages.MESSAGES.authenticationFailed(principal), mechanismName);
        return NOT_AUTHENTICATED;
    }
    securityContext.authenticationComplete(account, mechanismName, false);
    return AUTHENTICATED;
}
 
Example #14
Source File: SingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
    SecurityContext sc = exchange.getSecurityContext();
    Account account = sc.getAuthenticatedAccount();
    if (account != null) {
        try (SingleSignOn sso = singleSignOnManager.createSingleSignOn(account, sc.getMechanismName())) {
            Session session = getSession(exchange);
            registerSessionIfRequired(sso, session);
            exchange.getResponseCookies().put(cookieName, new CookieImpl(cookieName, sso.getId()).setHttpOnly(httpOnly).setSecure(secure).setDomain(domain).setPath(path));
        }
    }
    return factory.create();
}
 
Example #15
Source File: ServerSentEventConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @return The principal that was associated with the SSE request
 */
public Principal getPrincipal() {
    Account account = getAccount();
    if (account != null) {
        return account.getPrincipal();
    }
    return null;
}
 
Example #16
Source File: Identity.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Override
public Account verify(String username, Credential credential) {
    Account account = null;
    if (this.username.equals(username) && verifyCredential(credential)) {
        account = getAccount(username);
    }

    return account;
}
 
Example #17
Source File: InMemorySingleSignOnManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SingleSignOn createSingleSignOn(Account account, String mechanism) {
    String id = SECURE_RANDOM_SESSION_ID_GENERATOR.createSessionId();
    SingleSignOn entry = new SimpleSingleSignOnEntry(id, account, mechanism);
    this.ssoEntries.put(id, entry);
    if(log.isTraceEnabled()) {
        log.tracef("Creating SSO ID %s for Principal %s and Roles %s.", id, account.getPrincipal().getName(), account.getRoles().toString());
    }
    return entry;
}
 
Example #18
Source File: CustomIdentityManager.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Account verify(String id, Credential credential) {
    Account account = getAccount(id);
    if (account != null && verifyCredential(account, credential)) {
        return account;
    }
    return null;
}
 
Example #19
Source File: AuthConfiguration.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Account verify(String id, Credential credential) {
    if(!(credential instanceof PasswordCredential)) {
        return null;
    }
    PasswordCredential pc = (PasswordCredential) credential;
    char[] pwdArr = pc.getPassword();
    if(pwdArr != null && passwordEncoder.matches(new String(pwdArr), encodedPass)) {
        return new AccountImpl(id);
    }
    return null;
}
 
Example #20
Source File: ClientCertAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
    SSLSessionInfo sslSession = exchange.getConnection().getSslSessionInfo();
    if (sslSession != null) {
        try {
            Certificate[] clientCerts = getPeerCertificates(exchange, sslSession, securityContext);
            if (clientCerts[0] instanceof X509Certificate) {
                Credential credential = new X509CertificateCredential((X509Certificate) clientCerts[0]);

                IdentityManager idm = getIdentityManager(securityContext);
                Account account = idm.verify(credential);
                if (account != null) {
                    securityContext.authenticationComplete(account, name, false);
                    return AuthenticationMechanismOutcome.AUTHENTICATED;
                }
            }
        } catch (SSLPeerUnverifiedException e) {
            // No action - this mechanism can not attempt authentication without peer certificates so allow it to drop out
            // to NOT_ATTEMPTED.
        }
    }

    /*
     * For ClientCert we do not have a concept of a failed authentication, if the client did use a key then it was deemed
     * acceptable for the connection to be established, this mechanism then just 'attempts' to use it for authentication but
     * does not mandate success.
     */

    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #21
Source File: AsyncWebSocketHttpServerExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isUserInRole(String role) {
    SecurityContext sc = exchange.getSecurityContext();
    if(sc == null) {
        return false;
    }
    Account authenticatedAccount = sc.getAuthenticatedAccount();
    if(authenticatedAccount == null) {
        return false;
    }
    return authenticatedAccount.getRoles().contains(role);
}
 
Example #22
Source File: IdentityTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidVerify() {
    //given
    Identity identity = new Identity("foo", "bar");
    PasswordCredential credential = new PasswordCredential(password);

    //when
    Account account = identity.verify("foo", credential);
    
    //then
    assertThat(account, not(nullValue()));
    assertThat(account.getPrincipal().getName(), equalTo("foo"));
}
 
Example #23
Source File: MapIdentityManager.java    From proteus with Apache License 2.0 5 votes vote down vote up
private Account getAccount(final String id)
{
    if (identities.containsKey(id)) {
        return new UserAccount(id);
    }

    return null;
}
 
Example #24
Source File: MapIdentityManager.java    From proteus with Apache License 2.0 5 votes vote down vote up
private boolean verifyCredential(Account account, Credential credential)
{
    if (credential instanceof PasswordCredential) {
        char[] password = ((PasswordCredential) credential).getPassword();
        char[] expectedPassword = identities.get(account.getPrincipal().getName());

        return Arrays.equals(password, expectedPassword);
    }

    return false;
}
 
Example #25
Source File: MapIdentityManager.java    From proteus with Apache License 2.0 5 votes vote down vote up
@Override
public Account verify(String id, Credential credential)
{
    Account account = getAccount(id);

    if ((account != null) && verifyCredential(account, credential)) {
        return account;
    }

    return null;
}
 
Example #26
Source File: DatawaveAuthenticationMechanism.java    From datawave with Apache License 2.0 5 votes vote down vote up
private AuthenticationMechanismOutcome authenticated(HttpServerExchange exchange, SecurityContext securityContext, Account account) {
    if (exchange.getRequestHeaders().contains(HEADER_PROXIED_ENTITIES)) {
        exchange.getResponseHeaders().add(HEADER_PROXIED_ENTITIES_ACCEPTED, "true");
    }
    
    securityContext.authenticationComplete(account, name, false);
    addTimingRequestHeaders(exchange);
    return AuthenticationMechanismOutcome.AUTHENTICATED;
}
 
Example #27
Source File: AuthenticationTestBase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
protected static String getAuthenticatedUser(final HttpServerExchange exchange) {
    SecurityContext context = exchange.getSecurityContext();
    if (context != null) {
        Account account = context.getAuthenticatedAccount();
        if (account != null) {
            // An account must always return a Principal otherwise it is not an Account.
            return account.getPrincipal().getName();
        }
    }

    return null;
}
 
Example #28
Source File: DefaultAuthenticator.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public Account authenticate(String id, Credential credential) {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    Account account = getAccount(id);
    if (credential instanceof LightPasswordCredential) {
        LightPasswordCredential passwordCredential = (LightPasswordCredential)credential;
        char[] password = passwordCredential.getPassword();
        String clientAuthClass = passwordCredential.getClientAuthClass();
        String userType = passwordCredential.getUserType();

        User user = users.get(account.getPrincipal().getName());
        String expectedPassword = user.getPassword();
        boolean match = false;
        try {
            match = HashUtil.validatePassword(password, expectedPassword);
            Arrays.fill(password, ' ');
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            logger.error("Exception:", e);
            return null;
        }
        if(!match) return null;
    } else if(credential instanceof LightGSSContextCredential) {
        return new Account() {
            private Set<String> roles = LdapUtil.authorize(id);
            private final Principal principal = () -> id;
            @Override
            public Principal getPrincipal() {
                return principal;
            }
            @Override
            public Set<String> getRoles() { return roles; }
        };
    }
    return account;
}
 
Example #29
Source File: ServerSentEventConnection.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @return The account that was associated with the SSE request
 */
public Account getAccount() {
    SecurityContext sc = exchange.getSecurityContext();
    if (sc != null) {
        return sc.getAuthenticatedAccount();
    }
    return null;
}
 
Example #30
Source File: MapIdentityManager.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Account verify(String id, Credential credential) {
    Account account = getAccount(id);
    if (account != null && verifyCredential(account, credential)) {
        return account;
    }

    return null;
}