Search in sources :

Example 1 with OAuthGrant

use of org.openremote.model.auth.OAuthGrant in project openremote by openremote.

the class WebsocketAgentProtocol method doCreateIoClient.

@Override
protected WebsocketIOClient<String> doCreateIoClient() throws Exception {
    String uriStr = agent.getConnectUri().orElseThrow(() -> new IllegalArgumentException("Missing or invalid connectUri: " + agent));
    URI uri = new URI(uriStr);
    /* We're going to fail hard and fast if optional meta items are incorrectly configured */
    Optional<OAuthGrant> oAuthGrant = agent.getOAuthGrant();
    Optional<UsernamePassword> usernameAndPassword = agent.getUsernamePassword();
    Optional<ValueType.MultivaluedStringMap> headers = agent.getConnectHeaders();
    Optional<WebsocketSubscription[]> subscriptions = agent.getConnectSubscriptions();
    if (!oAuthGrant.isPresent() && usernameAndPassword.isPresent()) {
        String authValue = BasicAuthHelper.createHeader(usernameAndPassword.get().getUsername(), usernameAndPassword.get().getPassword());
        headers = Optional.of(headers.map(h -> {
            h.remove(HttpHeaders.AUTHORIZATION);
            h.replace(HttpHeaders.AUTHORIZATION, Collections.singletonList(authValue));
            return h;
        }).orElseGet(() -> {
            ValueType.MultivaluedStringMap h = new ValueType.MultivaluedStringMap();
            h.put(HttpHeaders.AUTHORIZATION, Collections.singletonList(authValue));
            return h;
        }));
    }
    clientHeaders = headers.orElse(null);
    WebsocketIOClient<String> websocketClient = new WebsocketIOClient<>(uri, headers.orElse(null), oAuthGrant.orElse(null));
    Map<String, List<String>> finalHeaders = headers.orElse(null);
    subscriptions.ifPresent(websocketSubscriptions -> addProtocolConnectedTask(() -> doSubscriptions(finalHeaders, websocketSubscriptions)));
    return websocketClient;
}
Also used : java.util(java.util) DEFAULT_CONTENT_TYPE(org.openremote.agent.protocol.http.HTTPProtocol.DEFAULT_CONTENT_TYPE) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) URISyntaxException(java.net.URISyntaxException) AttributeRef(org.openremote.model.attribute.AttributeRef) ValueUtil(org.openremote.model.util.ValueUtil) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) Supplier(java.util.function.Supplier) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) Attribute(org.openremote.model.attribute.Attribute) AbstractNettyIOClientProtocol(org.openremote.agent.protocol.io.AbstractNettyIOClientProtocol) AttributeEvent(org.openremote.model.attribute.AttributeEvent) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TextUtil(org.openremote.model.util.TextUtil) URI(java.net.URI) HttpHeaders(org.apache.http.HttpHeaders) OAuthGrant(org.openremote.model.auth.OAuthGrant) ValueType(org.openremote.model.value.ValueType) DEFAULT_HTTP_METHOD(org.openremote.agent.protocol.http.HTTPProtocol.DEFAULT_HTTP_METHOD) Pair(org.openremote.model.util.Pair) Invocation(javax.ws.rs.client.Invocation) Logger(java.util.logging.Logger) Entity(javax.ws.rs.client.Entity) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) BasicAuthHelper(org.jboss.resteasy.util.BasicAuthHelper) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Response(javax.ws.rs.core.Response) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ChannelHandler(io.netty.channel.ChannelHandler) WebTargetBuilder.createClient(org.openremote.container.web.WebTargetBuilder.createClient) UsernamePassword(org.openremote.model.auth.UsernamePassword) ProtocolUtil(org.openremote.model.protocol.ProtocolUtil) AttributeExecuteStatus(org.openremote.model.attribute.AttributeExecuteStatus) ValueType(org.openremote.model.value.ValueType) URI(java.net.URI) UsernamePassword(org.openremote.model.auth.UsernamePassword) OAuthGrant(org.openremote.model.auth.OAuthGrant)

Example 2 with OAuthGrant

use of org.openremote.model.auth.OAuthGrant in project openremote by openremote.

the class HTTPProtocol method doStart.

@Override
protected void doStart(Container container) throws Exception {
    String baseUri = agent.getBaseURI().orElseThrow(() -> new IllegalArgumentException("Missing or invalid base URI attribute: " + this));
    if (baseUri.endsWith("/")) {
        baseUri = baseUri.substring(0, baseUri.length() - 1);
    }
    URI uri;
    try {
        uri = new URIBuilder(baseUri).build();
    } catch (URISyntaxException e) {
        LOG.log(Level.SEVERE, "Invalid URI", e);
        throw e;
    }
    /* We're going to fail hard and fast if optional meta items are incorrectly configured */
    Optional<OAuthGrant> oAuthGrant = agent.getOAuthGrant();
    Optional<UsernamePassword> usernameAndPassword = agent.getUsernamePassword();
    boolean followRedirects = agent.getFollowRedirects().orElse(false);
    Optional<ValueType.MultivaluedStringMap> headers = agent.getRequestHeaders();
    Optional<ValueType.MultivaluedStringMap> queryParams = agent.getRequestQueryParameters();
    Integer readTimeout = agent.getRequestTimeoutMillis().orElse(null);
    WebTargetBuilder webTargetBuilder;
    if (readTimeout != null) {
        webTargetBuilder = new WebTargetBuilder(WebTargetBuilder.createClient(executorService, WebTargetBuilder.CONNECTION_POOL_SIZE, readTimeout.longValue(), null), uri);
    } else {
        webTargetBuilder = new WebTargetBuilder(client, uri);
    }
    if (oAuthGrant.isPresent()) {
        LOG.info("Adding OAuth");
        webTargetBuilder.setOAuthAuthentication(oAuthGrant.get());
    } else {
        usernameAndPassword.ifPresent(userPass -> {
            LOG.info("Adding Basic Authentication");
            webTargetBuilder.setBasicAuthentication(userPass.getUsername(), userPass.getPassword());
        });
    }
    headers.ifPresent(webTargetBuilder::setInjectHeaders);
    queryParams.ifPresent(webTargetBuilder::setInjectQueryParameters);
    webTargetBuilder.followRedirects(followRedirects);
    LOG.fine("Creating web target client '" + baseUri + "'");
    webTarget = webTargetBuilder.build();
    setConnectionStatus(ConnectionStatus.CONNECTED);
}
Also used : URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePassword(org.openremote.model.auth.UsernamePassword) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) OAuthGrant(org.openremote.model.auth.OAuthGrant)

Example 3 with OAuthGrant

use of org.openremote.model.auth.OAuthGrant in project openremote by openremote.

the class ManagerKeycloakIdentityProvider method loadCredentials.

/**
 * Load keycloak proxy credentials from file system
 */
public OAuthGrant loadCredentials() {
    // Try and load keycloak proxy credentials from file
    String grantFile = getString(container.getConfig(), KEYCLOAK_GRANT_FILE, KEYCLOAK_GRANT_FILE_DEFAULT);
    Path grantPath = TextUtil.isNullOrEmpty(grantFile) ? null : Paths.get(grantFile);
    OAuthGrant grant = null;
    if (grantPath != null && Files.isReadable(grantPath)) {
        LOG.info("Loading KEYCLOAK_GRANT_FILE: " + grantFile);
        try (InputStream is = Files.newInputStream(grantPath)) {
            String grantJson = IOUtils.toString(is, StandardCharsets.UTF_8);
            grant = ValueUtil.parse(grantJson, OAuthGrant.class).orElseGet(() -> {
                LOG.info("Failed to load KEYCLOAK_GRANT_FILE: " + grantFile);
                return null;
            });
        } catch (Exception ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    return grant;
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) OAuthGrant(org.openremote.model.auth.OAuthGrant) MapAccess.getString(org.openremote.container.util.MapAccess.getString) NotAllowedException(javax.ws.rs.NotAllowedException) BadRequestException(javax.ws.rs.BadRequestException) NotFoundException(javax.ws.rs.NotFoundException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 4 with OAuthGrant

use of org.openremote.model.auth.OAuthGrant in project openremote by openremote.

the class ManagerKeycloakIdentityProvider method init.

@Override
public void init(Container container) {
    super.init(container);
    this.container = container;
    OAuthGrant grant = loadCredentials();
    // Update the keycloak proxy credentials to use stored credentials
    if (grant != null) {
        setActiveCredentials(grant);
    }
    this.keycloakAdminPassword = container.getConfig().getOrDefault(SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT);
    this.timerService = container.getService(TimerService.class);
    this.persistenceService = container.getService(PersistenceService.class);
    this.messageBrokerService = container.getService(MessageBrokerService.class);
    this.clientEventService = container.getService(ClientEventService.class);
    this.consoleAppService = container.getService(ConsoleAppService.class);
}
Also used : PersistenceService(org.openremote.container.persistence.PersistenceService) ConsoleAppService(org.openremote.manager.apps.ConsoleAppService) OAuthGrant(org.openremote.model.auth.OAuthGrant) ClientEventService(org.openremote.manager.event.ClientEventService) TimerService(org.openremote.container.timer.TimerService) MessageBrokerService(org.openremote.container.message.MessageBrokerService)

Example 5 with OAuthGrant

use of org.openremote.model.auth.OAuthGrant in project openremote by openremote.

the class MqttConnection method setCredentials.

public void setCredentials(String realm, String username, String password) {
    this.realm = realm;
    this.username = username;
    this.password = password;
    credentials = !TextUtil.isNullOrEmpty(realm) && !TextUtil.isNullOrEmpty(username) && !TextUtil.isNullOrEmpty(password);
    if (credentials) {
        String tokenEndpointUri = identityProvider.getTokenUri(realm).toString();
        OAuthGrant grant = new OAuthClientCredentialsGrant(tokenEndpointUri, username, password, null);
        tokenSupplier = identityProvider.getAccessTokenSupplier(grant);
    } else {
        LOG.fine("MQTT connection with no credentials so will have limited capabilities: " + this);
    }
}
Also used : OAuthGrant(org.openremote.model.auth.OAuthGrant) OAuthClientCredentialsGrant(org.openremote.model.auth.OAuthClientCredentialsGrant)

Aggregations

OAuthGrant (org.openremote.model.auth.OAuthGrant)5 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 WebTargetBuilder (org.openremote.container.web.WebTargetBuilder)2 UsernamePassword (org.openremote.model.auth.UsernamePassword)2 ChannelHandler (io.netty.channel.ChannelHandler)1 InputStream (java.io.InputStream)1 Path (java.nio.file.Path)1 java.util (java.util)1 TimeUnit (java.util.concurrent.TimeUnit)1 Consumer (java.util.function.Consumer)1 Supplier (java.util.function.Supplier)1 Logger (java.util.logging.Logger)1 BadRequestException (javax.ws.rs.BadRequestException)1 NotAllowedException (javax.ws.rs.NotAllowedException)1 NotFoundException (javax.ws.rs.NotFoundException)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 Entity (javax.ws.rs.client.Entity)1 Invocation (javax.ws.rs.client.Invocation)1 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)1