Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.keycloak.adapters.tomcat7;
  
 
Web deployment whose security is managed by a remote OAuth Skeleton Key authentication server

Redirects browser to remote authentication server if not logged in. Also allows OAuth Bearer Token requests that contain a Skeleton Key bearer tokens.

Author(s):
Davide Ungari
Version:
$Revision: 1 $
 
 public class KeycloakAuthenticatorValve extends FormAuthenticator implements LifecycleListener {
 	private final static Logger log = Logger.getLogger(""+KeycloakAuthenticatorValve.class);
 
     @Override
     public void lifecycleEvent(LifecycleEvent event) {
         if (event.getType() == .) {
             try {
                 startDeployment();
             } catch (LifecycleException e) {
                 e.printStackTrace();
             }
         }
     }
 
     public void startDeployment() throws LifecycleException {
         super.start();
         StandardContext standardContext = (StandardContext;
         standardContext.addLifecycleListener(this);
          = false;
     }
 
     public void initInternal() {
         InputStream configInputStream = getConfigInputStream();
         KeycloakDeployment kd = null;
         if (configInputStream == null) {
             .warning("No adapter configuration.  Keycloak is unconfigured and will deny all requests.");
             kd = new KeycloakDeployment();
         } else {
             kd = KeycloakDeploymentBuilder.build(configInputStream);
         }
          = new AdapterDeploymentContext(kd);
         setNext(actions);
     }
 
     private static InputStream getJSONFromServletContext(ServletContext servletContext) {
         String json = servletContext.getInitParameter(.);
         if (json == null) {
             return null;
         }
         .info("**** using " + .);
         .info(json);
         return new ByteArrayInputStream(json.getBytes());
     }
 
     private static InputStream getConfigInputStream(Context context) {
         InputStream is = getJSONFromServletContext(context.getServletContext());
         if (is == null) {
             String path = context.getServletContext().getInitParameter("keycloak.config.file");
             if (path == null) {
                 .info("**** using /WEB-INF/keycloak.json");
                 is = context.getServletContext().getResourceAsStream("/WEB-INF/keycloak.json");
             } else {
                try {
                    is = new FileInputStream(path);
                } catch (FileNotFoundException e) {
                	.severe("NOT FOUND /WEB-INF/keycloak.json");
                    throw new RuntimeException(e);
                }
            }
        }
        return is;
    }
    @Override
    public void invoke(Request requestResponse responsethrows IOExceptionServletException {
        try {
            CatalinaHttpFacade facade = new CatalinaHttpFacade(requestresponse);
            PreAuthActionsHandler handler = new PreAuthActionsHandler(facade);
            if (handler.handleRequest()) {
                return;
            }
            checkKeycloakSession(requestfacade);
            super.invoke(requestresponse);
        } finally {
        }
    }
    @Override
    public boolean authenticate(Request requestHttpServletResponse responseLoginConfig configthrows IOException {
        CatalinaHttpFacade facade = new CatalinaHttpFacade(requestresponse);
        KeycloakDeployment deployment = .resolveDeployment(facade);
        if (deployment == null || !deployment.isConfigured()) {
            return false;
        }
        CatalinaRequestAuthenticator authenticator = new CatalinaRequestAuthenticator(deploymentthisfacaderequest);
        AuthOutcome outcome = authenticator.authenticate();
        if (outcome == .) {
            if (facade.isEnded()) {
                return false;
            }
            return true;
        }
        AuthChallenge challenge = authenticator.getChallenge();
        if (challenge != null) {
            challenge.challenge(facade);
        }
        return false;
    }

    
Checks that access token is still valid. Will attempt refresh of token if it is not.

Parameters:
request
    protected void checkKeycloakSession(Request requestHttpFacade facade) {
        if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == nullreturn;
        if (session == nullreturn;
        // just in case session got serialized
        if (session.getDeployment() == nullsession.setDeployment(.resolveDeployment(facade));
        if (session.isActive()) return;
        // FYI: A refresh requires same scope, so same roles will be set.  Otherwise, refresh will fail and token will
        // not be updated
        session.refreshExpiredToken();
        if (session.isActive()) return;
        request.setUserPrincipal(null);
        request.setAuthType(null);
        request.getSessionInternal().setPrincipal(null);
        request.getSessionInternal().setAuthType(null);
    }
    public void keycloakSaveRequest(Request requestthrows IOException {
        saveRequest(requestrequest.getSessionInternal(true));
    }
    public boolean keycloakRestoreRequest(Request request) {
        try {
            return restoreRequest(requestrequest.getSessionInternal());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
New to GrepCode? Check out our FAQ X