io.undertow.security.idm.PasswordCredential Java Examples

The following examples show how to use io.undertow.security.idm.PasswordCredential. 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: 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 #2
Source File: GenericHeaderAuthenticationMechanism.java    From quarkus-http with Apache License 2.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 #3
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 #4
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 #5
Source File: MapIdentityManager.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean verifyCredential(Account account, Credential credential) {
    boolean match = false;
    if (credential instanceof PasswordCredential) {
        char[] password = ((PasswordCredential) credential).getPassword();
        User user = users.get(account.getPrincipal().getName());
        String expectedPassword = user.getPassword();
        try {
            match = HashUtil.validatePassword(password, expectedPassword);
            Arrays.fill(password, ' ');
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            logger.error("Exception:", e);
        }
    }
    if(logger.isDebugEnabled()) logger.debug("verfifyCredential = " + match);
    return match;
}
 
Example #6
Source File: CustomIdentityManager.java    From tutorials with MIT License 5 votes vote down vote up
private boolean verifyCredential(Account account, Credential credential) {
    if (credential instanceof PasswordCredential) {
        char[] password = ((PasswordCredential) credential).getPassword();
        char[] expectedPassword = users.get(account.getPrincipal().getName());

        return Arrays.equals(password, expectedPassword);
    }
    return false;
}
 
Example #7
Source File: MapIdentityManager.java    From quarkus-http 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 = users.get(account.getPrincipal().getName());

        return Arrays.equals(password, expectedPassword);
    }
    return false;
}
 
Example #8
Source File: RealmIdentityManager.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Account verify(String id, Credential credential) {
    if (id == null || id.length() == 0) {
        HttpServerLogger.ROOT_LOGGER.debug("Missing or empty username received, aborting account verification.");
        return null;
    }

    if (credential instanceof PasswordCredential) {
        return verify(id, (PasswordCredential) credential);
    } else if (credential instanceof DigestCredential) {
        return verify(id, (DigestCredential) credential);
    }

    throw HttpServerLogger.ROOT_LOGGER.invalidCredentialType(credential.getClass().getName());
}
 
Example #9
Source File: IdentityTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonValidVerify() {
    //given
    Identity identity = new Identity("foo", "abar");
    PasswordCredential credential = new PasswordCredential(password);

    //when
    Account account = identity.verify("foo", credential);
    
    //then
    assertThat(account, nullValue());
}
 
Example #10
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 #11
Source File: Identity.java    From mangooio with Apache License 2.0 5 votes vote down vote up
private boolean verifyCredential(Credential credential) {
    if (credential instanceof PasswordCredential) {
        return Arrays.equals(((PasswordCredential) credential).getPassword(), this.password); 
    }
    
    return false;
}
 
Example #12
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 #13
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 #14
Source File: BasicAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {

    List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {

                String base64Challenge = current.substring(PREFIX_LENGTH);
                String plainChallenge = null;
                try {
                    ByteBuffer decode = FlexBase64.decode(base64Challenge);

                    Charset charset = this.charset;
                    if(!userAgentCharsets.isEmpty()) {
                        String ua = exchange.getRequestHeaders().getFirst(Headers.USER_AGENT);
                        if(ua != null) {
                            for (Map.Entry<Pattern, Charset> entry : userAgentCharsets.entrySet()) {
                                if(entry.getKey().matcher(ua).find()) {
                                    charset = entry.getValue();
                                    break;
                                }
                            }
                        }
                    }

                    plainChallenge = new String(decode.array(), decode.arrayOffset(), decode.limit(), charset);
                    UndertowLogger.SECURITY_LOGGER.debugf("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, exchange);
                } catch (IOException e) {
                    UndertowLogger.SECURITY_LOGGER.debugf(e, "Failed to decode basic auth header %s in %s", base64Challenge, exchange);
                }
                int colonPos;
                if (plainChallenge != null && (colonPos = plainChallenge.indexOf(COLON)) > -1) {
                    String userName = plainChallenge.substring(0, colonPos);
                    char[] password = plainChallenge.substring(colonPos + 1).toCharArray();

                    IdentityManager idm = getIdentityManager(securityContext);
                    PasswordCredential credential = new PasswordCredential(password);
                    try {
                        final AuthenticationMechanismOutcome result;
                        Account account = idm.verify(userName, credential);
                        if (account != null) {
                            securityContext.authenticationComplete(account, name, false);
                            result = AuthenticationMechanismOutcome.AUTHENTICATED;
                        } else {
                            securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
                            result = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
                        }
                        return result;
                    } finally {
                        clear(password);
                    }
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #15
Source File: FormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
        UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
        // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }

    try {
        final FormData data = parser.parseBlocking();
        final FormData.FormValue jUsername = data.getFirst("j_username");
        final FormData.FormValue jPassword = data.getFirst("j_password");
        if (jUsername == null || jPassword == null) {
            UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
        final String userName = jUsername.getValue();
        final String password = jPassword.getValue();
        AuthenticationMechanismOutcome outcome = null;
        PasswordCredential credential = new PasswordCredential(password.toCharArray());
        try {
            IdentityManager identityManager = getIdentityManager(securityContext);
            Account account = identityManager.verify(userName, credential);
            if (account != null) {
                securityContext.authenticationComplete(account, name, true);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
            }
        } finally {
            if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                handleRedirectBack(exchange);
                exchange.endExchange();
            }
            return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: BasicAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
/**
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {

    List<String> authHeaders = exchange.getRequestHeaders(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {

                String base64Challenge = current.substring(PREFIX_LENGTH);
                String plainChallenge = null;
                try {
                    ByteBuf decode = FlexBase64.decode(base64Challenge);

                    Charset charset = this.charset;
                    if(!userAgentCharsets.isEmpty()) {
                        String ua = exchange.getRequestHeader(HttpHeaderNames.USER_AGENT);
                        if(ua != null) {
                            for (Map.Entry<Pattern, Charset> entry : userAgentCharsets.entrySet()) {
                                if(entry.getKey().matcher(ua).find()) {
                                    charset = entry.getValue();
                                    break;
                                }
                            }
                        }
                    }

                    plainChallenge = new String(decode.array(), decode.arrayOffset(), decode.writerIndex(), charset);
                    UndertowLogger.SECURITY_LOGGER.debugf("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, exchange);
                } catch (IOException e) {
                    UndertowLogger.SECURITY_LOGGER.debugf(e, "Failed to decode basic auth header %s in %s", base64Challenge, exchange);
                }
                int colonPos;
                if (plainChallenge != null && (colonPos = plainChallenge.indexOf(COLON)) > -1) {
                    String userName = plainChallenge.substring(0, colonPos);
                    char[] password = plainChallenge.substring(colonPos + 1).toCharArray();

                    IdentityManager idm = getIdentityManager(securityContext);
                    PasswordCredential credential = new PasswordCredential(password);
                    try {
                        final AuthenticationMechanismOutcome result;
                        Account account = idm.verify(userName, credential);
                        if (account != null) {
                            securityContext.authenticationComplete(account, name, false);
                            result = AuthenticationMechanismOutcome.AUTHENTICATED;
                        } else {
                            securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
                            result = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
                        }
                        return result;
                    } finally {
                        clear(password);
                    }
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #17
Source File: FormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
        UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
        // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }

    try {
        final FormData data = parser.parseBlocking();
        if (data == null) {
            UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
            // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }

        final FormData.FormValue jUsername = data.getFirst("j_username");
        final FormData.FormValue jPassword = data.getFirst("j_password");
        if (jUsername == null || jPassword == null) {
            UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
        final String userName = jUsername.getValue();
        final String password = jPassword.getValue();
        AuthenticationMechanismOutcome outcome = null;
        PasswordCredential credential = new PasswordCredential(password.toCharArray());
        try {
            IdentityManager identityManager = getIdentityManager(securityContext);
            Account account = identityManager.verify(userName, credential);
            if (account != null) {
                securityContext.authenticationComplete(account, name, true);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
            }
        } finally {
            if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                handleRedirectBack(exchange);
                exchange.endExchange();
            }
            return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}