org.keycloak.adapters.AdapterDeploymentContext Java Examples

The following examples show how to use org.keycloak.adapters.AdapterDeploymentContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeycloakAuthenticationProcessingFilterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    request = spy(new MockHttpServletRequest());
    request.setRequestURI("http://host");
    filter = new KeycloakAuthenticationProcessingFilter(authenticationManager);
    keycloakFailureHandler = new KeycloakAuthenticationFailureHandler();

    filter.setApplicationContext(applicationContext);
    filter.setAuthenticationSuccessHandler(successHandler);
    filter.setAuthenticationFailureHandler(failureHandler);

    when(applicationContext.getBean(eq(AdapterDeploymentContext.class))).thenReturn(adapterDeploymentContext);
    when(adapterDeploymentContext.resolveDeployment(any(HttpFacade.class))).thenReturn(keycloakDeployment);
    when(keycloakAccount.getPrincipal()).thenReturn(
            new KeycloakPrincipal<KeycloakSecurityContext>(UUID.randomUUID().toString(), keycloakSecurityContext));


    filter.afterPropertiesSet();
}
 
Example #2
Source File: ElytronHttpFacade.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ElytronHttpFacade(HttpServerRequest request, AdapterDeploymentContext deploymentContext, CallbackHandler handler) {
    this.request = request;
    this.deploymentContext = deploymentContext;
    this.callbackHandler = handler;
    this.tokenStore = createTokenStore();
    this.responseConsumer = response -> {};
}
 
Example #3
Source File: ServletPreAuthActionsHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected ServletPreAuthActionsHandler(AdapterDeploymentContext deploymentContext,
                                       UndertowUserSessionManagement userSessionManagement,
                                       HttpHandler next) {
    this.next = next;
    this.deploymentContext = deploymentContext;
    this.userSessionManagement = userSessionManagement;
}
 
Example #4
Source File: UndertowPreAuthActionsHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public UndertowPreAuthActionsHandler(AdapterDeploymentContext deploymentContext,
                                        UndertowUserSessionManagement userSessionManagement,
                                        SessionManager sessionManager,
                                        HttpHandler next) {
    this.next = next;
    this.deploymentContext = deploymentContext;
    this.sessionManager = sessionManager;
    this.userSessionManagement = userSessionManagement;
}
 
Example #5
Source File: WildflyKeycloakServletExtension.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, AdapterDeploymentContext deploymentContext,
                                                                UndertowUserSessionManagement userSessionManagement, NodesRegistrationManagement nodesRegistrationManagement) {
    log.debug("creating WildflyAuthenticationMechanism");
    return new WildflyAuthenticationMechanism(deploymentContext, userSessionManagement, nodesRegistrationManagement, deploymentInfo.getConfidentialPortManager(), getErrorPage(deploymentInfo));

}
 
Example #6
Source File: KeycloakWebSecurityConfigurerAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Bean
protected AdapterDeploymentContext adapterDeploymentContext() throws Exception {
    AdapterDeploymentContextFactoryBean factoryBean;
    if (keycloakConfigResolver != null) {
         factoryBean = new AdapterDeploymentContextFactoryBean(new KeycloakSpringConfigResolverWrapper(keycloakConfigResolver));
    }
    else {
        factoryBean = new AdapterDeploymentContextFactoryBean(keycloakConfigFileResource);
    }
    factoryBean.afterPropertiesSet();
    return factoryBean.getObject();
}
 
Example #7
Source File: ServletKeycloakAuthMech.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ServletKeycloakAuthMech(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement,
                               NodesRegistrationManagement nodesRegistrationManagement, ConfidentialPortManager portManager,
                               String errorPage) {
    super(deploymentContext, userSessionManagement, errorPage);
    this.nodesRegistrationManagement = nodesRegistrationManagement;
    this.portManager = portManager;
}
 
Example #8
Source File: AtlasSecurityConfig.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Bean
protected AdapterDeploymentContext adapterDeploymentContext() throws Exception {
    AdapterDeploymentContextFactoryBean factoryBean;
    String fileName = configuration.getString("atlas.authentication.method.keycloak.file");
    if (fileName != null && !fileName.isEmpty()) {
        keycloakConfigFileResource = new FileSystemResource(fileName);
        factoryBean = new AdapterDeploymentContextFactoryBean(keycloakConfigFileResource);
    } else {
        Configuration conf = configuration.subset("atlas.authentication.method.keycloak");
        AdapterConfig cfg = new AdapterConfig();
        cfg.setRealm(conf.getString("realm", "atlas.com"));
        cfg.setAuthServerUrl(conf.getString("auth-server-url", "https://localhost/auth"));
        cfg.setResource(conf.getString("resource", "none"));

        Map<String,Object> credentials = new HashMap<>();
        credentials.put("secret", conf.getString("credentials-secret", "nosecret"));
        cfg.setCredentials(credentials);
        KeycloakDeployment dep = KeycloakDeploymentBuilder.build(cfg);
        factoryBean = new AdapterDeploymentContextFactoryBean(new KeycloakConfigResolver() {
            @Override
            public KeycloakDeployment resolve(HttpFacade.Request request) {
                return dep;
            }
        });
    }

    factoryBean.afterPropertiesSet();
    return factoryBean.getObject();
}
 
Example #9
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void logoutCurrent(Request request) {
    AdapterDeploymentContext deploymentContext = (AdapterDeploymentContext) request.getAttribute(AdapterDeploymentContext.class.getName());
    KeycloakSecurityContext ksc = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    if (ksc != null) {
        JettyHttpFacade facade = new OIDCJettyHttpFacade(request, null);
        KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
        if (ksc instanceof RefreshableKeycloakSecurityContext) {
            ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
        }

        AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);
        tokenStore.logout();
        request.removeAttribute(KeycloakSecurityContext.class.getName());
    }
}
 
Example #10
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Authentication register(Request request, KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
    request.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);
    Authentication authentication = request.getAuthentication();
    if (!(authentication instanceof KeycloakAuthentication)) {
        UserIdentity userIdentity = createIdentity(principal);
        authentication = createAuthentication(userIdentity, request);
        request.setAuthentication(authentication);
    }
    return authentication;
}
 
Example #11
Source File: CxfKeycloakAuthHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AdapterDeploymentContext buildDeploymentContext() {
    if (configResolver != null) {
        LOG.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolver.getClass());
        return new AdapterDeploymentContext(configResolver);
    } else if (adapterConfig != null) {
        KeycloakDeployment kd = KeycloakDeploymentBuilder.build(adapterConfig);
        return new AdapterDeploymentContext(kd);
    }

    LOG.warning("Adapter is unconfigured, Keycloak will deny every request");
    return new AdapterDeploymentContext();
}
 
Example #12
Source File: UndertowKeycloakEndpoint.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AdapterDeploymentContext getDeploymentContext() {
    if (configResolver != null) {
        LOG.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolver.getClass());
        return new AdapterDeploymentContext(configResolver);
    } else if (adapterConfig != null) {
        KeycloakDeployment kd = KeycloakDeploymentBuilder.build(adapterConfig);
        return new AdapterDeploymentContext(kd);
    }

    LOG.warning("Adapter is unconfigured, Keycloak will deny every request");
    return new AdapterDeploymentContext();
}
 
Example #13
Source File: UndertowKeycloakConsumer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public UndertowKeycloakConsumer(UndertowKeycloakEndpoint endpoint, Processor processor, 
  AdapterDeploymentContext deploymentContext, Pattern skipPattern, List<String> allowedRoles, int confidentialPort) {
    super(endpoint, processor);
    this.sessionManager = new InMemorySessionManager(endpoint.getEndpointUri());
    this.deploymentContext = deploymentContext;
    this.skipPattern = skipPattern;
    this.confidentialPort = confidentialPort;
    this.allowedRoles = allowedRoles == null ? Collections.<String>emptyList() : allowedRoles;
}
 
Example #14
Source File: KeycloakPreAuthActionsFilterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);
    filter = new KeycloakPreAuthActionsFilter(userSessionManagement);
    filter.setNodesRegistrationManagement(nodesRegistrationManagement);
    filter.setApplicationContext(applicationContext);
    filter.setPreAuthActionsHandlerFactory(preAuthActionsHandlerFactory);
    when(applicationContext.getBean(AdapterDeploymentContext.class)).thenReturn(deploymentContext);
    when(deploymentContext.resolveDeployment(any(HttpFacade.class))).thenReturn(deployment);
    when(preAuthActionsHandlerFactory.createPreAuthActionsHandler(any(HttpFacade.class))).thenReturn(preAuthActionsHandler);
    when(deployment.isConfigured()).thenReturn(true);
    filter.initFilterBean();
}
 
Example #15
Source File: AdapterActionsFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest servletReq = (HttpServletRequest) request;
    HttpServletResponse servletResp = (HttpServletResponse) response;

    //Accept timeOffset as argument to enforce timeouts
    String timeOffsetParam = request.getParameter(TIME_OFFSET_PARAM);
    String resetDeploymentParam = request.getParameter(RESET_DEPLOYMENT_PARAM);

    if (timeOffsetParam != null && !timeOffsetParam.isEmpty()) {
        int timeOffset = Integer.parseInt(timeOffsetParam);
        log.infof("Time offset updated to %d for application %s", timeOffset, servletReq.getRequestURI());
        Time.setOffset(timeOffset);
        writeResponse(servletResp, "Offset set successfully");
    } else if (resetDeploymentParam != null && !resetDeploymentParam.isEmpty()) {
        AdapterDeploymentContext deploymentContext = (AdapterDeploymentContext) request.getServletContext().getAttribute(AdapterDeploymentContext.class.getName());

        Field field = Reflections.findDeclaredField(AdapterDeploymentContext.class, "deployment");
        Reflections.setAccessible(field);
        KeycloakDeployment deployment = (KeycloakDeployment) Reflections.getFieldValue(field, deploymentContext);

        Time.setOffset(0);
        deployment.setNotBefore(0);
        if (deployment.getPublicKeyLocator() instanceof JWKPublicKeyLocator) {
            deployment.setPublicKeyLocator(new JWKPublicKeyLocator());
        }

        log.infof("Restarted PublicKeyLocator, notBefore and timeOffset for application %s", servletReq.getRequestURI());
        writeResponse(servletResp, "Restarted PublicKeyLocator, notBefore and timeOffset successfully");
    } else {
        // Continue request
        chain.doFilter(request, response);
    }

}
 
Example #16
Source File: OfflineAccessPortalServlet.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakDeployment getDeployment(HttpServletRequest servletRequest) throws ServletException {
    // The facade object is needed just if you have relative "auth-server-url" in keycloak.json. Otherwise you can call deploymentContext.resolveDeployment(null)
    HttpFacade facade = getFacade(servletRequest);

    AdapterDeploymentContext deploymentContext = (AdapterDeploymentContext) getServletContext().getAttribute(AdapterDeploymentContext.class.getName());
    if (deploymentContext == null) {
        throw new ServletException("AdapterDeploymentContext not set");
    }
    return deploymentContext.resolveDeployment(facade);
}
 
Example #17
Source File: KeycloakAuthenticationEntryPointTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    authenticationEntryPoint = new KeycloakAuthenticationEntryPoint(adapterDeploymentContext);
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    when(applicationContext.getBean(eq(AdapterDeploymentContext.class))).thenReturn(adapterDeploymentContext);
    when(adapterDeploymentContext.resolveDeployment(any(HttpFacade.class))).thenReturn(keycloakDeployment);
    when(keycloakDeployment.isBearerOnly()).thenReturn(Boolean.FALSE);
}
 
Example #18
Source File: KeycloakHttpServerAuthenticationMechanism.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AdapterDeploymentContext getDeploymentContext(HttpServerRequest request) {
    if (this.deploymentContext == null) {
        return (AdapterDeploymentContext) request.getScope(Scope.APPLICATION).getAttachment(KeycloakConfigurationServletListener.ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE_ELYTRON);
    }

    return this.deploymentContext;
}
 
Example #19
Source File: KeycloakAuthFilter.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
public void validateRequest(final ContainerRequestContext requestContext) {
    if (requestContext.getSecurityContext().getUserPrincipal() != null) {
        // the user is already authenticated, further processing is not necessary
        return;
    }
    Request request = Request.getBaseRequest((ServletRequest)
            requestContext.getProperty(HttpServletRequest.class.getName()));
    JaxrsHttpFacade facade = new JaxrsHttpFacade(requestContext, requestContext.getSecurityContext());
    request.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);

    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        return;
    }

    AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);

    tokenStore.checkCurrentToken();
    JettyRequestAuthenticator authenticator = createRequestAuthenticator(request, facade, deployment, tokenStore);
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        return;
    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        challenge.challenge(facade);
        if (!adapterConfig.isBearerOnly()) {
            // create session and set cookie for client
            facade.getResponse().setCookie("JSESSIONID", request.getSession().getId(), "/", null, -1, false, false);
        }
        facade.getResponse().end();
    }
}
 
Example #20
Source File: KeycloakServletExtension.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public KeycloakServletExtension(AdapterDeploymentContext deploymentContext) {
    this.deploymentContext = deploymentContext;
}
 
Example #21
Source File: AbstractUndertowKeycloakAuthMech.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AbstractUndertowKeycloakAuthMech(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement sessionManagement, String errorPage) {
    this.deploymentContext = deploymentContext;
    this.sessionManagement = sessionManagement;
    this.errorPage = errorPage;
}
 
Example #22
Source File: ServletPreAuthActionsHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public Wrapper(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement) {
    this.deploymentContext = deploymentContext;
    this.userSessionManagement = userSessionManagement;
}
 
Example #23
Source File: KeycloakPreAuthActionsFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void initFilterBean() throws ServletException {
    deploymentContext = applicationContext.getBean(AdapterDeploymentContext.class);
}
 
Example #24
Source File: UndertowAuthenticationMechanism.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public UndertowAuthenticationMechanism(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement sessionManagement,
                                       NodesRegistrationManagement nodesRegistrationManagement, int confidentialPort, String errorPage) {
    super(deploymentContext, sessionManagement, errorPage);
    this.nodesRegistrationManagement = nodesRegistrationManagement;
    this.confidentialPort = confidentialPort;
}
 
Example #25
Source File: UndertowAuthenticatedActionsHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public Wrapper(AdapterDeploymentContext deploymentContext) {
    this.deploymentContext = deploymentContext;
}
 
Example #26
Source File: UndertowAuthenticatedActionsHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public UndertowAuthenticatedActionsHandler(AdapterDeploymentContext deploymentContext, HttpHandler next) {
    this.deploymentContext = deploymentContext;
    this.next = next;
}
 
Example #27
Source File: AdapterDeploymentContextFactoryBean.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> getObjectType() {
    return AdapterDeploymentContext.class;
}
 
Example #28
Source File: KeycloakServletExtension.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement,
                                                                NodesRegistrationManagement nodesRegistrationManagement) {
    log.debug("creating ServletKeycloakAuthMech");
    String errorPage = getErrorPage(deploymentInfo);
    return new ServletKeycloakAuthMech(deploymentContext, userSessionManagement, nodesRegistrationManagement, deploymentInfo.getConfidentialPortManager(), errorPage);
}
 
Example #29
Source File: KeycloakHttpServerAuthenticationMechanism.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public KeycloakHttpServerAuthenticationMechanism(Map<String, ?> properties, CallbackHandler callbackHandler, AdapterDeploymentContext deploymentContext) {
    this.properties = properties;
    this.callbackHandler = callbackHandler;
    this.deploymentContext = deploymentContext;
}
 
Example #30
Source File: KeycloakHttpServerAuthenticationMechanism.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException {
    LOGGER.debugf("Evaluating request for path [%s]", request.getRequestURI());
    AdapterDeploymentContext deploymentContext = getDeploymentContext(request);

    if (deploymentContext == null) {
        LOGGER.debugf("Ignoring request for path [%s] from mechanism [%s]. No deployment context found.", request.getRequestURI(), getMechanismName());
        request.noAuthenticationInProgress();
        return;
    }

    ElytronHttpFacade httpFacade = new ElytronHttpFacade(request, deploymentContext, callbackHandler);
    KeycloakDeployment deployment = httpFacade.getDeployment();

    if (!deployment.isConfigured()) {
        request.noAuthenticationInProgress();
        return;
    }

    RequestAuthenticator authenticator = createRequestAuthenticator(request, httpFacade, deployment);

    httpFacade.getTokenStore().checkCurrentToken();

    if (preActions(httpFacade, deploymentContext)) {
        LOGGER.debugf("Pre-actions has aborted the evaluation of [%s]", request.getRequestURI());
        httpFacade.authenticationInProgress();
        return;
    }

    AuthOutcome outcome = authenticator.authenticate();

    if (AuthOutcome.AUTHENTICATED.equals(outcome)) {
        if (new AuthenticatedActionsHandler(deployment, httpFacade).handledRequest()) {
            httpFacade.authenticationInProgress();
        } else {
            httpFacade.authenticationComplete();
        }
        return;
    }

    AuthChallenge challenge = authenticator.getChallenge();

    if (challenge != null) {
        httpFacade.noAuthenticationInProgress(challenge);
        return;
    }

    if (AuthOutcome.FAILED.equals(outcome)) {
        httpFacade.getResponse().setStatus(403);
        httpFacade.authenticationFailed();
        return;
    }

    httpFacade.noAuthenticationInProgress();
}