Search in sources :

Example 1 with Authentication

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

the class AuthFilter method authenticateBearerToken.

private SecurityContext authenticateBearerToken(String token) throws AuthenticationException {
    if (token.startsWith(API_TOKEN_PREFIX)) {
        UserApiTokenCredentials credentials = new UserApiTokenCredentials(token);
        Authentication auth = userRegistry.authenticate(credentials);
        User user = userRegistry.get(auth.getUsername());
        if (user == null) {
            throw new AuthenticationException("User not found in registry");
        }
        return new UserSecurityContext(user, auth, "ApiToken");
    } else {
        Authentication auth = jwtHelper.verifyAndParseJwtAccessToken(token);
        return new JwtSecurityContext(auth);
    }
}
Also used : UserApiTokenCredentials(org.openhab.core.auth.UserApiTokenCredentials) User(org.openhab.core.auth.User) AuthenticationException(org.openhab.core.auth.AuthenticationException) Authentication(org.openhab.core.auth.Authentication)

Example 2 with Authentication

use of org.openhab.core.auth.Authentication 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 3 with Authentication

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

the class JwtHelper method verifyAndParseJwtAccessToken.

/**
 * Performs verifications on a JWT token, then parses it into a {@link AuthenticationException} instance
 *
 * @param jwt the base64-encoded JWT token from the request
 * @return the {@link Authentication} derived from the information in the token
 * @throws AuthenticationException
 */
public Authentication verifyAndParseJwtAccessToken(String jwt) throws AuthenticationException {
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30).setRequireSubject().setExpectedIssuer(ISSUER_NAME).setExpectedAudience(AUDIENCE).setVerificationKey(jwtWebKey.getKey()).setJwsAlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256).build();
    try {
        JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
        String username = jwtClaims.getSubject();
        List<String> roles = jwtClaims.getStringListClaimValue("role");
        String scope = jwtClaims.getStringClaimValue("scope");
        return new Authentication(username, roles.toArray(new String[roles.size()]), scope);
    } catch (InvalidJwtException | MalformedClaimException e) {
        throw new AuthenticationException("Error while processing JWT token", e);
    }
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtClaims(org.jose4j.jwt.JwtClaims) AuthenticationException(org.openhab.core.auth.AuthenticationException) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Authentication(org.openhab.core.auth.Authentication) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer)

Example 4 with Authentication

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

the class AuthenticationHandler method handle.

@Override
public void handle(final HttpServletRequest request, final HttpServletResponse response, final HandlerContext context) throws Exception {
    String requestUri = request.getRequestURI();
    if (this.enabled && isSecured(requestUri, request.getMethod())) {
        if (authenticationManager == null) {
            throw new AuthenticationException("Failed to authenticate request.");
        }
        int found = 0, failed = 0;
        for (CredentialsExtractor<HttpServletRequest> extractor : extractors) {
            Optional<Credentials> extracted = extractor.retrieveCredentials(request);
            if (extracted.isPresent()) {
                found++;
                Credentials credentials = extracted.get();
                try {
                    Authentication authentication = authenticationManager.authenticate(credentials);
                    request.setAttribute(Authentication.class.getName(), authentication);
                    context.execute(request, response);
                    return;
                } catch (AuthenticationException e) {
                    failed++;
                    if (logger.isDebugEnabled()) {
                        logger.debug("Failed to authenticate using credentials {}", credentials, e);
                    } else {
                        logger.info("Failed to authenticate using credentials {}", credentials);
                    }
                }
            }
        }
        throw new AuthenticationException("Could not authenticate request. Found " + found + " credentials in request out of which " + failed + " were invalid");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.openhab.core.auth.AuthenticationException) Authentication(org.openhab.core.auth.Authentication) Credentials(org.openhab.core.auth.Credentials)

Example 5 with Authentication

use of org.openhab.core.auth.Authentication 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

Authentication (org.openhab.core.auth.Authentication)7 AuthenticationException (org.openhab.core.auth.AuthenticationException)6 User (org.openhab.core.auth.User)4 UsernamePasswordCredentials (org.openhab.core.auth.UsernamePasswordCredentials)3 UserApiTokenCredentials (org.openhab.core.auth.UserApiTokenCredentials)2 LinkedHashMap (java.util.LinkedHashMap)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 JwtClaims (org.jose4j.jwt.JwtClaims)1 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)1 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)1 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)1 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)1 Credentials (org.openhab.core.auth.Credentials)1 GenericUser (org.openhab.core.auth.GenericUser)1 ManagedUser (org.openhab.core.auth.ManagedUser)1 UserApiToken (org.openhab.core.auth.UserApiToken)1