Java Code Examples for io.undertow.server.HttpServerExchange#getSecurityContext()

The following examples show how to use io.undertow.server.HttpServerExchange#getSecurityContext() . 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: ServletSecurityRoleHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletRequest request = servletRequestContext.getServletRequest();
    if (request.getDispatcherType() == DispatcherType.REQUEST) {
        List<SingleConstraintMatch> constraints = servletRequestContext.getRequiredConstrains();
        SecurityContext sc = exchange.getSecurityContext();
        if (!authorizationManager.canAccessResource(constraints, sc.getAuthenticatedAccount(), servletRequestContext.getCurrentServlet().getManagedServlet().getServletInfo(), servletRequestContext.getOriginalRequest(), servletRequestContext.getDeployment())) {

            HttpServletResponse response = (HttpServletResponse) servletRequestContext.getServletResponse();
            response.sendError(StatusCodes.FORBIDDEN);
            return;
        }
    }
    next.handleRequest(exchange);
}
 
Example 2
Source File: ServletSecurityRoleHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletRequest request = servletRequestContext.getServletRequest();
    if (request.getDispatcherType() == DispatcherType.REQUEST) {
        List<SingleConstraintMatch> constraints = servletRequestContext.getRequiredConstrains();
        SecurityContext sc = exchange.getSecurityContext();
        if (!authorizationManager.canAccessResource(constraints, sc.getAuthenticatedAccount(), servletRequestContext.getCurrentServlet().getManagedServlet().getServletInfo(), servletRequestContext.getOriginalRequest(), servletRequestContext.getDeployment())) {

            HttpServletResponse response = (HttpServletResponse) servletRequestContext.getServletResponse();
            response.sendError(StatusCodes.FORBIDDEN);
            return;
        }
    }
    next.handleRequest(exchange);
}
 
Example 3
Source File: CachedAuthenticatedSessionHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    SecurityContext securityContext = exchange.getSecurityContext();
    securityContext.registerNotificationReceiver(NOTIFICATION_RECEIVER);
    SessionManager sessionManager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    if (sessionManager == null || sessionConfig == null) {
        next.handleRequest(exchange);
        return;
    }
    Session session = sessionManager.getSession(exchange, sessionConfig);
    // If there was no existing HttpSession then there could not be a cached AuthenticatedSession so don't bother setting
    // the AuthenticatedSessionManager.
    if (session != null) {
        exchange.putAttachment(AuthenticatedSessionManager.ATTACHMENT_KEY, SESSION_MANAGER);
    }

    next.handleRequest(exchange);
}
 
Example 4
Source File: AuthenticationCallHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Only allow the request through if successfully authenticated or if authentication is not required.
 *
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if(exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }
    SecurityContext context = exchange.getSecurityContext();
    if (context.authenticate()) {
        if(!exchange.isComplete()) {
           next.handleRequest(exchange);
        }
    } else {
        exchange.endExchange();
    }
}
 
Example 5
Source File: SingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
    SecurityContext sc = exchange.getSecurityContext();
    Account account = sc.getAuthenticatedAccount();
    if (account != null) {
        try (SingleSignOn sso = singleSignOnManager.createSingleSignOn(account, sc.getMechanismName())) {
            Session session = getSession(exchange);
            registerSessionIfRequired(sso, session);
            exchange.getResponseCookies().put(cookieName, new CookieImpl(cookieName, sso.getId()).setHttpOnly(httpOnly).setSecure(secure).setDomain(domain).setPath(path));
        }
    }
    return factory.create();
}
 
Example 6
Source File: NotificationReceiverHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    SecurityContext sc = exchange.getSecurityContext();
    for (int i = 0; i < receivers.length; ++i) {
        sc.registerNotificationReceiver(receivers[i]);
    }

    next.handleRequest(exchange);
}
 
Example 7
Source File: AuthenticationMechanismsHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final SecurityContext sc = exchange.getSecurityContext();
    if(sc != null && sc instanceof AuthenticationMechanismContext) {
        AuthenticationMechanismContext amc = (AuthenticationMechanismContext) sc;
        for(int i = 0; i < authenticationMechanisms.length; ++i) {
            amc.addAuthenticationMechanism(authenticationMechanisms[i]);
        }
    }
    next.handleRequest(exchange);
}
 
Example 8
Source File: CachedAuthenticatedSessionHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    SecurityContext securityContext = exchange.getSecurityContext();
    securityContext.registerNotificationReceiver(NOTIFICATION_RECEIVER);

    HttpSession session = servletContext.getSession(exchange, false);
    // If there was no existing HttpSession then there could not be a cached AuthenticatedSession so don't bother setting
    // the AuthenticatedSessionManager.
    if (session != null) {
        exchange.putAttachment(AuthenticatedSessionManager.ATTACHMENT_KEY, SESSION_MANAGER);
        SavedRequest.tryRestoreRequest(exchange, session); //not sure if this is where it belongs
    }

    next.handleRequest(exchange);
}
 
Example 9
Source File: AuthenticationTestBase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
protected static String getAuthenticatedUser(final HttpServerExchange exchange) {
    SecurityContext context = exchange.getSecurityContext();
    if (context != null) {
        Account account = context.getAuthenticatedAccount();
        if (account != null) {
            // An account must always return a Principal otherwise it is not an Account.
            return account.getPrincipal().getName();
        }
    }

    return null;
}
 
Example 10
Source File: JDBCLogHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void logMessage(String pattern, HttpServerExchange exchange) {
    JDBCLogAttribute jdbcLogAttribute = new JDBCLogAttribute();

    if (pattern.equals("combined")) {
        jdbcLogAttribute.pattern = pattern;
    }
    jdbcLogAttribute.remoteHost = ((InetSocketAddress) exchange.getSourceAddress()).getAddress().getHostAddress();
    SecurityContext sc = exchange.getSecurityContext();
    if (sc == null || !sc.isAuthenticated()) {
        jdbcLogAttribute.user = null;
    } else {
        jdbcLogAttribute.user = sc.getAuthenticatedAccount().getPrincipal().getName();
    }
    jdbcLogAttribute.query = exchange.getQueryString();

    jdbcLogAttribute.bytes = exchange.getResponseContentLength();
    if (jdbcLogAttribute.bytes < 0) {
        jdbcLogAttribute.bytes = 0;
    }

    jdbcLogAttribute.status = exchange.getStatusCode();

    if (jdbcLogAttribute.pattern.equals("combined")) {
        jdbcLogAttribute.virtualHost = exchange.getRequestHeader(HttpHeaderNames.HOST);
        jdbcLogAttribute.method = exchange.getRequestMethod();
        jdbcLogAttribute.referer = exchange.getRequestHeader(HttpHeaderNames.REFERER);
        jdbcLogAttribute.userAgent = exchange.getRequestHeader(HttpHeaderNames.USER_AGENT);
    }

    this.pendingMessages.add(jdbcLogAttribute);
    int state = stateUpdater.get(this);
    if (state == 0) {
        if (stateUpdater.compareAndSet(this, 0, 1)) {
            this.executor = exchange.getWorker();
            this.executor.execute(this);
        }
    }
}
 
Example 11
Source File: AuthenticationTypeExchangeAttribute.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public String readAttribute(HttpServerExchange exchange) {
    SecurityContext sc = exchange.getSecurityContext();
    if(sc == null) {
        return null;
    }
    return sc.getMechanismName();
}
 
Example 12
Source File: RemoteUserAttribute.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public String readAttribute(final HttpServerExchange exchange) {
    SecurityContext sc = exchange.getSecurityContext();
    if (sc == null || !sc.isAuthenticated()) {
        return null;
    }
    return sc.getAuthenticatedAccount().getPrincipal().getName();
}
 
Example 13
Source File: JDBCLogHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void logMessage(String pattern, HttpServerExchange exchange) {
    JDBCLogAttribute jdbcLogAttribute = new JDBCLogAttribute();

    if (pattern.equals("combined")) {
        jdbcLogAttribute.pattern = pattern;
    }
    jdbcLogAttribute.remoteHost = ((InetSocketAddress) exchange.getConnection().getPeerAddress()).getAddress().getHostAddress();
    SecurityContext sc = exchange.getSecurityContext();
    if (sc == null || !sc.isAuthenticated()) {
        jdbcLogAttribute.user = null;
    } else {
        jdbcLogAttribute.user = sc.getAuthenticatedAccount().getPrincipal().getName();
    }
    jdbcLogAttribute.query = exchange.getQueryString();

    jdbcLogAttribute.bytes = exchange.getResponseContentLength();
    if (jdbcLogAttribute.bytes < 0) {
        jdbcLogAttribute.bytes = 0;
    }

    jdbcLogAttribute.status = exchange.getStatusCode();

    if (jdbcLogAttribute.pattern.equals("combined")) {
        jdbcLogAttribute.virtualHost = exchange.getRequestHeaders().getFirst(Headers.HOST);
        jdbcLogAttribute.method = exchange.getRequestMethod().toString();
        jdbcLogAttribute.referer = exchange.getRequestHeaders().getFirst(Headers.REFERER);
        jdbcLogAttribute.userAgent = exchange.getRequestHeaders().getFirst(Headers.USER_AGENT);
    }

    this.pendingMessages.add(jdbcLogAttribute);
    int state = stateUpdater.get(this);
    if (state == 0) {
        if (stateUpdater.compareAndSet(this, 0, 1)) {
            this.executor = exchange.getConnection().getWorker();
            this.executor.execute(this);
        }
    }
}
 
Example 14
Source File: AuthenticationRequiredPredicate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean resolve(HttpServerExchange value) {
    SecurityContext sc = value.getSecurityContext();
    if(sc == null) {
        return false;
    }
    return sc.isAuthenticationRequired();
}
 
Example 15
Source File: NotificationReceiverHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    SecurityContext sc = exchange.getSecurityContext();
    for (int i = 0; i < receivers.length; ++i) {
        sc.registerNotificationReceiver(receivers[i]);
    }

    next.handleRequest(exchange);
}
 
Example 16
Source File: AuthenticationMechanismsHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final SecurityContext sc = exchange.getSecurityContext();
    if(sc != null && sc instanceof AuthenticationMechanismContext) {
        AuthenticationMechanismContext amc = (AuthenticationMechanismContext) sc;
        for(int i = 0; i < authenticationMechanisms.length; ++i) {
            amc.addAuthenticationMechanism(authenticationMechanisms[i]);
        }
    }
    next.handleRequest(exchange);
}
 
Example 17
Source File: AuthenticationConstraintHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (isAuthenticationRequired(exchange)) {
        SecurityContext context = exchange.getSecurityContext();
        UndertowLogger.SECURITY_LOGGER.debugf("Setting authentication required for exchange %s", exchange);
        context.setAuthenticationRequired();
    }

    next.handleRequest(exchange);
}
 
Example 18
Source File: AuthenticationTypeExchangeAttribute.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String readAttribute(HttpServerExchange exchange) {
    SecurityContext sc = exchange.getSecurityContext();
    if(sc == null) {
        return null;
    }
    return sc.getMechanismName();
}
 
Example 19
Source File: UndertowKeycloakConsumer.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange httpExchange) throws Exception {
    if (shouldSkip(httpExchange.getRequestPath())) {
        super.handleRequest(httpExchange);
        return;
    }

    //perform only non-blocking operation on exchange
    if (httpExchange.isInIoThread()) {
        httpExchange.dispatch(this);
        return;
    }

    OIDCUndertowHttpFacade facade = new OIDCUndertowHttpFacade(httpExchange);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);

    if (deployment == null || !deployment.isConfigured()) {
        httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
        LOG.fine("deployment not configured");
        return;
    }

    LOG.fine("executing PreAuthActionsHandler");
    SessionManagementBridge bridge = new SessionManagementBridge(userSessionManagement, sessionManager);
    PreAuthActionsHandler preAuth = new PreAuthActionsHandler(bridge, deploymentContext, facade);
    if (preAuth.handleRequest()) return;

    SecurityContext securityContext = httpExchange.getSecurityContext();
    if (securityContext == null) {
        securityContext = new SecurityContextImpl(httpExchange, IDENTITY_MANAGER);
    }
    AdapterTokenStore tokenStore = getTokenStore(httpExchange, facade, deployment, securityContext);
    tokenStore.checkCurrentToken();

    LOG.fine("executing AuthenticatedActionsHandler");
    RequestAuthenticator authenticator = new UndertowRequestAuthenticator(facade, deployment, confidentialPort, securityContext, httpExchange, tokenStore);
    AuthOutcome outcome = authenticator.authenticate();

    if (outcome == AuthOutcome.AUTHENTICATED) {
        LOG.fine("AUTHENTICATED");
        if (httpExchange.isResponseComplete()) {
            return;
        }
        AuthenticatedActionsHandler actions = new AuthenticatedActionsHandler(deployment, facade);
        if (actions.handledRequest()) {
            return;
        } else {
            final Account authenticatedAccount = securityContext.getAuthenticatedAccount();
            if (authenticatedAccount instanceof KeycloakUndertowAccount) {
                final KeycloakUndertowAccount kua = (KeycloakUndertowAccount) authenticatedAccount;
                httpExchange.putAttachment(KEYCLOAK_PRINCIPAL_KEY, (KeycloakPrincipal) kua.getPrincipal());
            }

            Set<String> roles = Optional
              .ofNullable(authenticatedAccount.getRoles())
              .orElse((Set<String>) Collections.EMPTY_SET);

            LOG.log(Level.FINE, "Allowed roles: {0}, current roles: {1}", new Object[] {allowedRoles, roles});

            if (isRoleAllowed(roles, httpExchange)) {
                super.handleRequest(httpExchange);
            } else {
                httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
            }

            return;
        }
    }

    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        LOG.fine("challenge");
        challenge.challenge(facade);
        return;
    }

    httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
}
 
Example 20
Source File: Oauth2CodePostHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");

    // get the form from the exchange
    final FormData data = exchange.getAttachment(FormDataParser.FORM_DATA);

    final FormData.FormValue jClientId = data.getFirst("client_id");
    final FormData.FormValue jRedirectUri = data.getFirst("redirect_uri");
    final FormData.FormValue jState = data.getFirst("state");
    final FormData.FormValue jRemember = data.getFirst("remember");
    final String clientId = jClientId.getValue();
    final String remember = jRemember == null ? null : jRemember.getValue();  // should be 'Y' or 'N' if not null.
    String redirectUri = jRedirectUri == null ? null : jRedirectUri.getValue();
    final String state = jState == null ? null : jState.getValue();
    if(logger.isDebugEnabled()) {
        logger.debug("client_id = " + clientId + " state = " + state + " redirectUri = " + redirectUri + " remember = " + remember);
    }
    // check if the client_id is valid
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);
    if(client == null) {
        if(logger.isDebugEnabled()) logger.debug("client is not found for clientId = " + clientId);
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
    } else {
        final SecurityContext context = exchange.getSecurityContext();
        String userId = context.getAuthenticatedAccount().getPrincipal().getName();
        if(logger.isDebugEnabled()) logger.debug("userId = " + userId);
        if("error".equals(userId)) {
            exchange.setStatusCode(StatusCodes.BAD_REQUEST);
            exchange.getResponseSender().send(context.getAuthenticatedAccount().getRoles().iterator().next());
            processAudit(exchange);
        } else {
            Set<String> roles = context.getAuthenticatedAccount().getRoles();
            Map<String, String> codeMap = new HashMap<>();
            codeMap.put("userId", userId);
            if(roles != null && !roles.isEmpty()) {
                codeMap.put("roles", String.join(" ", roles));
            }
            // generate auth code
            String code = Util.getUUID();
            if(redirectUri == null) {
                redirectUri = client.getRedirectUri();
            } else {
                codeMap.put("redirectUri", redirectUri);
            }
            if(remember != null) codeMap.put("remember", remember); // pass the remember checkbox value to the token service
            CacheStartupHookProvider.hz.getMap("codes").set(code, codeMap);

            redirectUri = redirectUri + "?code=" + code;
            if(state != null) {
                redirectUri = redirectUri + "&state=" + state;
            }
            if(logger.isDebugEnabled()) logger.debug("redirectUri = " + redirectUri);
            // now redirect here.
            exchange.setStatusCode(StatusCodes.FOUND);
            exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri);
            exchange.endExchange();
            processAudit(exchange);
        }
    }
}