Search in sources :

Example 1 with AuthenticationException

use of org.openhab.core.auth.AuthenticationException in project openhab-addons by openhab.

the class GoogleCloudAPI method getAccessToken.

/**
 * Fetches the OAuth2 tokens from Google Cloud Platform if the auth-code is set in the configuration. If successful
 * the auth-code will be removed from the configuration.
 *
 * @throws AuthenticationException
 * @throws CommunicationException
 */
@SuppressWarnings("null")
private void getAccessToken() throws AuthenticationException, CommunicationException {
    String authcode = config.authcode;
    if (authcode != null && !authcode.isEmpty()) {
        logger.debug("Trying to get access and refresh tokens.");
        try {
            oAuthService.getAccessTokenResponseByAuthorizationCode(authcode, GCP_REDIRECT_URI);
        } catch (OAuthException | OAuthResponseException e) {
            logger.debug("Error fetching access token: {}", e.getMessage(), e);
            throw new AuthenticationException("Error fetching access token. Invalid authcode? Please generate a new one.");
        } catch (IOException e) {
            throw new CommunicationException(String.format("An unexpected IOException occurred: %s", e.getMessage()));
        }
        config.authcode = null;
        try {
            Configuration serviceConfig = configAdmin.getConfiguration(GoogleTTSService.SERVICE_PID);
            Dictionary<String, Object> configProperties = serviceConfig.getProperties();
            if (configProperties != null) {
                configProperties.put(GoogleTTSService.PARAM_AUTHCODE, "");
                serviceConfig.update(configProperties);
            }
        } catch (IOException e) {
            // should not happen
            logger.warn("Failed to update configuration for Google Cloud TTS service. Please clear the 'authcode' configuration parameter manualy.");
        }
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) CommunicationException(org.openhab.core.i18n.CommunicationException) Configuration(org.osgi.service.cm.Configuration) AuthenticationException(org.openhab.core.auth.AuthenticationException) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException)

Example 2 with AuthenticationException

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

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

the class ManagedUserLoginModule method login.

@Override
public boolean login() throws LoginException {
    try {
        // try to get the UserRegistry instance
        BundleContext bundleContext = FrameworkUtil.getBundle(UserRegistry.class).getBundleContext();
        ServiceReference<UserRegistry> serviceReference = bundleContext.getServiceReference(UserRegistry.class);
        userRegistry = bundleContext.getService(serviceReference);
    } catch (Exception e) {
        logger.error("Cannot initialize the ManagedLoginModule", e);
        throw new LoginException("Authorization failed");
    }
    try {
        Credentials credentials = (Credentials) this.subject.getPrivateCredentials().iterator().next();
        userRegistry.authenticate(credentials);
        return true;
    } catch (AuthenticationException e) {
        throw new LoginException(e.getMessage());
    }
}
Also used : AuthenticationException(org.openhab.core.auth.AuthenticationException) UserRegistry(org.openhab.core.auth.UserRegistry) LoginException(javax.security.auth.login.LoginException) LoginException(javax.security.auth.login.LoginException) AuthenticationException(org.openhab.core.auth.AuthenticationException) Credentials(org.openhab.core.auth.Credentials) BundleContext(org.osgi.framework.BundleContext)

Example 4 with AuthenticationException

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

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

Aggregations

AuthenticationException (org.openhab.core.auth.AuthenticationException)16 User (org.openhab.core.auth.User)7 Authentication (org.openhab.core.auth.Authentication)6 IOException (java.io.IOException)4 ManagedUser (org.openhab.core.auth.ManagedUser)4 UsernamePasswordCredentials (org.openhab.core.auth.UsernamePasswordCredentials)4 CommunicationException (org.openhab.core.i18n.CommunicationException)3 File (java.io.File)2 LoginException (javax.security.auth.login.LoginException)2 Credentials (org.openhab.core.auth.Credentials)2 UserApiTokenCredentials (org.openhab.core.auth.UserApiTokenCredentials)2 FileNotFoundException (java.io.FileNotFoundException)1 PrintWriter (java.io.PrintWriter)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