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);
}
}
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;
}
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);
}
}
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");
}
}
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");
}
Aggregations