Search in sources :

Example 1 with UsernamePasswordCredentials

use of org.openhab.core.auth.UsernamePasswordCredentials in project openhab-core by openhab.

the class AuthFilter method authenticateBasicAuth.

private SecurityContext authenticateBasicAuth(String credentialString) throws AuthenticationException {
    final String cacheKey = getCacheKey(credentialString);
    if (cacheKey != null) {
        final UserSecurityContext cachedValue = authCache.get(cacheKey);
        if (cachedValue != null) {
            return cachedValue;
        }
    }
    String[] decodedCredentials = new String(Base64.getDecoder().decode(credentialString), StandardCharsets.UTF_8).split(":");
    if (decodedCredentials.length != 2) {
        throw new AuthenticationException("Invalid Basic authentication credential format");
    }
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(decodedCredentials[0], decodedCredentials[1]);
    Authentication auth = userRegistry.authenticate(credentials);
    User user = userRegistry.get(auth.getUsername());
    if (user == null) {
        throw new AuthenticationException("User not found in registry");
    }
    UserSecurityContext context = new UserSecurityContext(user, auth, "Basic");
    if (cacheKey != null) {
        authCache.put(cacheKey, context);
    }
    return context;
}
Also used : User(org.openhab.core.auth.User) AuthenticationException(org.openhab.core.auth.AuthenticationException) Authentication(org.openhab.core.auth.Authentication) UsernamePasswordCredentials(org.openhab.core.auth.UsernamePasswordCredentials)

Example 2 with UsernamePasswordCredentials

use of org.openhab.core.auth.UsernamePasswordCredentials in project openhab-core by openhab.

the class UserRegistryImplTest method testUserManagement.

@Test
public void testUserManagement() throws Exception {
    User user = registry.register("username", "password", Set.of("administrator"));
    registry.added(managedProviderMock, user);
    assertNotNull(user);
    registry.authenticate(new UsernamePasswordCredentials("username", "password"));
    registry.changePassword(user, "password2");
    registry.authenticate(new UsernamePasswordCredentials("username", "password2"));
    registry.remove(user.getName());
    registry.removed(managedProviderMock, user);
    user = registry.get("username");
    assertNull(user);
}
Also used : ManagedUser(org.openhab.core.auth.ManagedUser) User(org.openhab.core.auth.User) UsernamePasswordCredentials(org.openhab.core.auth.UsernamePasswordCredentials) Test(org.junit.jupiter.api.Test)

Example 3 with UsernamePasswordCredentials

use of org.openhab.core.auth.UsernamePasswordCredentials in project openhab-core by openhab.

the class JaasAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Credentials credentials) throws AuthenticationException {
    if (realmName == null) {
        // configuration is not yet ready or set
        realmName = DEFAULT_REALM;
    }
    if (!(credentials instanceof UsernamePasswordCredentials)) {
        throw new AuthenticationException("Unsupported credentials passed to provider.");
    }
    UsernamePasswordCredentials userCredentials = (UsernamePasswordCredentials) credentials;
    final String name = userCredentials.getUsername();
    final char[] password = userCredentials.getPassword().toCharArray();
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Principal userPrincipal = new GenericUser(name);
        Subject subject = new Subject(true, Set.of(userPrincipal), Collections.emptySet(), Set.of(userCredentials));
        Thread.currentThread().setContextClassLoader(ManagedUserLoginModule.class.getClassLoader());
        LoginContext loginContext = new LoginContext(realmName, subject, new CallbackHandler() {

            @Override
            public void handle(@NonNullByDefault({}) Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (Callback callback : callbacks) {
                    if (callback instanceof PasswordCallback) {
                        ((PasswordCallback) callback).setPassword(password);
                    } else if (callback instanceof NameCallback) {
                        ((NameCallback) callback).setName(name);
                    } else {
                        throw new UnsupportedCallbackException(callback);
                    }
                }
            }
        }, new ManagedUserLoginConfiguration());
        loginContext.login();
        return getAuthentication(name, loginContext.getSubject());
    } catch (LoginException e) {
        String message = e.getMessage();
        throw new AuthenticationException(message != null ? message : "An unexpected LoginException occurred");
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) AuthenticationException(org.openhab.core.auth.AuthenticationException) IOException(java.io.IOException) Subject(javax.security.auth.Subject) UsernamePasswordCredentials(org.openhab.core.auth.UsernamePasswordCredentials) LoginContext(javax.security.auth.login.LoginContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) GenericUser(org.openhab.core.auth.GenericUser) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Principal(java.security.Principal)

Example 4 with UsernamePasswordCredentials

use of org.openhab.core.auth.UsernamePasswordCredentials in project openhab-core by openhab.

the class AbstractAuthPageServlet method login.

protected User login(String username, String password) throws AuthenticationException {
    // consecutive failures in seconds
    if (lastAuthenticationFailure != null && lastAuthenticationFailure.isAfter(Instant.now().minus(Duration.ofSeconds(authenticationFailureCount)))) {
        throw new AuthenticationException("Too many consecutive login attempts");
    }
    // Authenticate the user with the supplied credentials
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    Authentication auth = authProvider.authenticate(credentials);
    logger.debug("Login successful: {}", auth.getUsername());
    lastAuthenticationFailure = null;
    authenticationFailureCount = 0;
    User user = userRegistry.get(auth.getUsername());
    if (user == null) {
        throw new AuthenticationException("User not found");
    }
    return user;
}
Also used : User(org.openhab.core.auth.User) AuthenticationException(org.openhab.core.auth.AuthenticationException) Authentication(org.openhab.core.auth.Authentication) UsernamePasswordCredentials(org.openhab.core.auth.UsernamePasswordCredentials)

Example 5 with UsernamePasswordCredentials

use of org.openhab.core.auth.UsernamePasswordCredentials in project openhab-core by openhab.

the class UserRegistryImpl method authenticate.

@Override
public Authentication authenticate(Credentials credentials) throws AuthenticationException {
    if (credentials instanceof UsernamePasswordCredentials) {
        UsernamePasswordCredentials usernamePasswordCreds = (UsernamePasswordCredentials) credentials;
        User user = get(usernamePasswordCreds.getUsername());
        if (user == null) {
            throw new AuthenticationException("User not found: " + usernamePasswordCreds.getUsername());
        }
        ManagedUser managedUser = (ManagedUser) user;
        String hashedPassword = hash(usernamePasswordCreds.getPassword(), managedUser.getPasswordSalt(), PASSWORD_ITERATIONS).get();
        if (!hashedPassword.equals(managedUser.getPasswordHash())) {
            throw new AuthenticationException("Wrong password for user " + usernamePasswordCreds.getUsername());
        }
        return new Authentication(managedUser.getName(), managedUser.getRoles().stream().toArray(String[]::new));
    } else if (credentials instanceof UserApiTokenCredentials) {
        UserApiTokenCredentials apiTokenCreds = (UserApiTokenCredentials) credentials;
        String[] apiTokenParts = apiTokenCreds.getApiToken().split("\\.");
        if (apiTokenParts.length != 3 || !APITOKEN_PREFIX.equals(apiTokenParts[0])) {
            throw new AuthenticationException("Invalid API token format");
        }
        for (User user : getAll()) {
            ManagedUser managedUser = (ManagedUser) user;
            for (UserApiToken userApiToken : managedUser.getApiTokens()) {
                // only check if the name in the token matches
                if (!userApiToken.getName().equals(apiTokenParts[1])) {
                    continue;
                }
                String[] existingTokenHashAndSalt = userApiToken.getApiToken().split(":");
                String incomingTokenHash = hash(apiTokenCreds.getApiToken(), existingTokenHashAndSalt[1], APITOKEN_ITERATIONS).get();
                if (incomingTokenHash.equals(existingTokenHashAndSalt[0])) {
                    return new Authentication(managedUser.getName(), managedUser.getRoles().stream().toArray(String[]::new), userApiToken.getScope());
                }
            }
        }
        throw new AuthenticationException("Unknown API token");
    }
    throw new IllegalArgumentException("Invalid credential type");
}
Also used : UserApiTokenCredentials(org.openhab.core.auth.UserApiTokenCredentials) ManagedUser(org.openhab.core.auth.ManagedUser) User(org.openhab.core.auth.User) AuthenticationException(org.openhab.core.auth.AuthenticationException) ManagedUser(org.openhab.core.auth.ManagedUser) Authentication(org.openhab.core.auth.Authentication) UserApiToken(org.openhab.core.auth.UserApiToken) UsernamePasswordCredentials(org.openhab.core.auth.UsernamePasswordCredentials)

Aggregations

UsernamePasswordCredentials (org.openhab.core.auth.UsernamePasswordCredentials)5 AuthenticationException (org.openhab.core.auth.AuthenticationException)4 User (org.openhab.core.auth.User)4 Authentication (org.openhab.core.auth.Authentication)3 ManagedUser (org.openhab.core.auth.ManagedUser)2 IOException (java.io.IOException)1 Principal (java.security.Principal)1 Subject (javax.security.auth.Subject)1 Callback (javax.security.auth.callback.Callback)1 CallbackHandler (javax.security.auth.callback.CallbackHandler)1 NameCallback (javax.security.auth.callback.NameCallback)1 PasswordCallback (javax.security.auth.callback.PasswordCallback)1 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)1 LoginContext (javax.security.auth.login.LoginContext)1 LoginException (javax.security.auth.login.LoginException)1 Test (org.junit.jupiter.api.Test)1 GenericUser (org.openhab.core.auth.GenericUser)1 UserApiToken (org.openhab.core.auth.UserApiToken)1 UserApiTokenCredentials (org.openhab.core.auth.UserApiTokenCredentials)1