use of org.openhab.core.auth.Authentication in project openhab-core by openhab.
the class ExpiringUserSecurityContextCacheTest method createValues.
private Map<String, UserSecurityContext> createValues(int count) {
Map<String, UserSecurityContext> map = new LinkedHashMap<>();
for (int i = 0; i < count; i++) {
String userName = "user" + i;
UserSecurityContext userSecurityContext = new UserSecurityContext(new GenericUser(userName), new Authentication(userName), userName + " token");
map.put("key" + i, userSecurityContext);
}
return map;
}
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