Search in sources :

Example 1 with KeycloakPrincipal

use of org.keycloak.KeycloakPrincipal in project vboard by voyages-sncf-technologies.

the class AuthenticationController method getUserEmailFromAuth.

private static String getUserEmailFromAuth(Authentication auth) {
    if (auth instanceof JsonWebTokenAuthentication) {
        return ((JsonWebTokenAuthentication) auth).getEmail();
    }
    final KeycloakPrincipal userDetails = (KeycloakPrincipal) auth.getPrincipal();
    final IDToken idToken = userDetails.getKeycloakSecurityContext().getToken();
    return idToken.getEmail();
}
Also used : JsonWebTokenAuthentication(com.vsct.vboard.config.cognito.JsonWebTokenAuthentication) IDToken(org.keycloak.representations.IDToken) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 2 with KeycloakPrincipal

use of org.keycloak.KeycloakPrincipal in project openremote by openremote.

the class DefaultWebsocketComponent method deploy.

@Override
protected void deploy() throws Exception {
    WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
    getConsumers().forEach((key, value) -> {
        String endpointPath = WEBSOCKET_PATH + "/" + key;
        LOG.info("Deploying websocket endpoint: " + endpointPath);
        webSocketDeploymentInfo.addEndpoint(ServerEndpointConfig.Builder.create(WebsocketAdapter.class, endpointPath).configurator(new DefaultContainerConfigurator() {

            @SuppressWarnings("unchecked")
            @Override
            public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
                return (T) new WebsocketAdapter(value);
            }

            @Override
            public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
                String realm = Optional.ofNullable(request.getHeaders().get(Constants.REALM_PARAM_NAME)).map(realms -> realms.isEmpty() ? null : realms.get(0)).orElse(null);
                Principal principal = request.getUserPrincipal();
                AuthContext authContext = null;
                if (principal instanceof KeycloakPrincipal) {
                    KeycloakPrincipal<?> keycloakPrincipal = (KeycloakPrincipal<?>) principal;
                    authContext = new AccessTokenAuthContext(keycloakPrincipal.getKeycloakSecurityContext().getRealm(), keycloakPrincipal.getKeycloakSecurityContext().getToken());
                } else if (principal instanceof BasicAuthContext) {
                    authContext = (BasicAuthContext) principal;
                } else if (principal != null) {
                    LOG.info("Unsupported user principal type: " + principal);
                }
                config.getUserProperties().put(ConnectionConstants.HANDSHAKE_AUTH, authContext);
                config.getUserProperties().put(ConnectionConstants.HANDSHAKE_REALM, realm);
                super.modifyHandshake(config, request, response);
            }
        }).build());
    });
    // We use the I/O thread to handle received websocket frames, as we expect to quickly hand them over to
    // an internal asynchronous message queue for processing, so we don't need a separate worker thread
    // pool for websocket frame processing
    webSocketDeploymentInfo.setDispatchToWorkerThread(false);
    // Make the shit Undertow/Websocket JSR client bootstrap happy - this is the pool that would be used
    // when Undertow acts as a WebSocket client, which we don't do... and I'm not even sure it can do that...
    webSocketDeploymentInfo.setWorker(Xnio.getInstance().createWorker(OptionMap.builder().set(Options.WORKER_TASK_MAX_THREADS, 1).set(Options.WORKER_NAME, "WebsocketInternalClient").set(Options.THREAD_DAEMON, true).getMap()));
    boolean directBuffers = Boolean.getBoolean("io.undertow.websockets.direct-buffers");
    webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(directBuffers, 1024, 100, 12));
    String deploymentName = "WebSocket Deployment";
    deploymentInfo = new DeploymentInfo().setDeploymentName(deploymentName).setContextPath(WEBSOCKET_PATH).addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo).setClassLoader(WebsocketComponent.class.getClassLoader());
    // Require authentication, but authorize specific roles later in Camel
    WebResourceCollection resourceCollection = new WebResourceCollection();
    resourceCollection.addUrlPattern("/*");
    SecurityConstraint constraint = new SecurityConstraint();
    constraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT);
    constraint.addWebResourceCollection(resourceCollection);
    deploymentInfo.addSecurityConstraints(constraint);
    HttpHandler handler = WebService.addServletDeployment(container, deploymentInfo, true);
    websocketHttpHandler = pathStartsWithHandler(deploymentName, WEBSOCKET_PATH, handler);
    // Give web socket handler higher priority than any other handlers already added
    webService.getRequestHandlers().add(0, websocketHttpHandler);
}
Also used : HttpHandler(io.undertow.server.HttpHandler) WebResourceCollection(io.undertow.servlet.api.WebResourceCollection) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) BasicAuthContext(org.openremote.container.security.basic.BasicAuthContext) AccessTokenAuthContext(org.openremote.container.security.keycloak.AccessTokenAuthContext) AuthContext(org.openremote.container.security.AuthContext) BasicAuthContext(org.openremote.container.security.basic.BasicAuthContext) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) HandshakeResponse(javax.websocket.HandshakeResponse) WebsocketAdapter(org.openremote.container.web.socket.WebsocketAdapter) AccessTokenAuthContext(org.openremote.container.security.keycloak.AccessTokenAuthContext) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) DefaultContainerConfigurator(io.undertow.websockets.jsr.DefaultContainerConfigurator) KeycloakPrincipal(org.keycloak.KeycloakPrincipal) Principal(java.security.Principal) HandshakeRequest(javax.websocket.server.HandshakeRequest) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 3 with KeycloakPrincipal

use of org.keycloak.KeycloakPrincipal in project loc-framework by lord-of-code.

the class LocKeycloakLogInterceptor method afterCompletion.

@Override
public void afterCompletion(WebRequest request, @Nullable Exception ex) throws Exception {
    log.info("afterCompletion: request is {}", request);
    KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    locKeycloakLog.save(LocKeycloakLog.LocKeycloakLogDomain.builder().param(request.getParameterMap().toString()).createDateTime(LocalDateTime.now()).url(request.getContextPath()).userName(keycloakPrincipal.getName()).build());
}
Also used : KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 4 with KeycloakPrincipal

use of org.keycloak.KeycloakPrincipal in project vboard by voyages-sncf-technologies.

the class AuthenticationController method createUserFromAuth.

@NotNull
@SuppressFBWarnings("CLI_CONSTANT_LIST_INDEX")
private static User createUserFromAuth(Authentication auth) {
    if (auth instanceof JsonWebTokenAuthentication) {
        JsonWebTokenAuthentication jwtAuth = ((JsonWebTokenAuthentication) auth);
        String username = jwtAuth.getName();
        String[] parts = StringUtils.split(username, "\\");
        if (parts != null) {
            username = parts[1];
        }
        parts = StringUtils.split(username, "_");
        if (parts == null) {
            throw new IllegalArgumentException("The username in the JWT token provided does not contain a '_'");
        }
        String firstName = StringUtils.capitalize(parts[0]);
        String lastName = StringUtils.capitalize(parts[1]);
        LOGGER.info("createUserFromAuth/JWT: email={} firstName={} lastName={}", jwtAuth.getEmail(), firstName, lastName);
        return new User(jwtAuth.getEmail(), firstName, lastName);
    }
    final KeycloakPrincipal userDetails = (KeycloakPrincipal) auth.getPrincipal();
    final IDToken idToken = userDetails.getKeycloakSecurityContext().getToken();
    LOGGER.info("createUserFromAuth/Keycloak: email={} firstName={} lastName={}", idToken.getEmail(), idToken.getGivenName(), idToken.getFamilyName());
    return new User(idToken.getEmail(), idToken.getGivenName(), idToken.getFamilyName());
}
Also used : User(com.vsct.vboard.models.User) JsonWebTokenAuthentication(com.vsct.vboard.config.cognito.JsonWebTokenAuthentication) IDToken(org.keycloak.representations.IDToken) KeycloakPrincipal(org.keycloak.KeycloakPrincipal) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) NotNull(javax.validation.constraints.NotNull)

Aggregations

KeycloakPrincipal (org.keycloak.KeycloakPrincipal)4 JsonWebTokenAuthentication (com.vsct.vboard.config.cognito.JsonWebTokenAuthentication)2 IDToken (org.keycloak.representations.IDToken)2 User (com.vsct.vboard.models.User)1 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 DefaultByteBufferPool (io.undertow.server.DefaultByteBufferPool)1 HttpHandler (io.undertow.server.HttpHandler)1 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)1 SecurityConstraint (io.undertow.servlet.api.SecurityConstraint)1 WebResourceCollection (io.undertow.servlet.api.WebResourceCollection)1 DefaultContainerConfigurator (io.undertow.websockets.jsr.DefaultContainerConfigurator)1 WebSocketDeploymentInfo (io.undertow.websockets.jsr.WebSocketDeploymentInfo)1 Principal (java.security.Principal)1 NotNull (javax.validation.constraints.NotNull)1 HandshakeResponse (javax.websocket.HandshakeResponse)1 HandshakeRequest (javax.websocket.server.HandshakeRequest)1 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)1 AuthContext (org.openremote.container.security.AuthContext)1 BasicAuthContext (org.openremote.container.security.basic.BasicAuthContext)1 AccessTokenAuthContext (org.openremote.container.security.keycloak.AccessTokenAuthContext)1