Search in sources :

Example 6 with IdentityManager

use of io.undertow.security.idm.IdentityManager in project undertow by undertow-io.

the class BasicAuthenticationMechanism method authenticate.

/**
     * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
     */
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {
                String base64Challenge = current.substring(PREFIX_LENGTH);
                String plainChallenge = null;
                try {
                    ByteBuffer decode = FlexBase64.decode(base64Challenge);
                    Charset charset = this.charset;
                    if (!userAgentCharsets.isEmpty()) {
                        String ua = exchange.getRequestHeaders().getFirst(Headers.USER_AGENT);
                        if (ua != null) {
                            for (Map.Entry<Pattern, Charset> entry : userAgentCharsets.entrySet()) {
                                if (entry.getKey().matcher(ua).find()) {
                                    charset = entry.getValue();
                                    break;
                                }
                            }
                        }
                    }
                    plainChallenge = new String(decode.array(), decode.arrayOffset(), decode.limit(), charset);
                    UndertowLogger.SECURITY_LOGGER.debugf("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, exchange);
                } catch (IOException e) {
                    UndertowLogger.SECURITY_LOGGER.debugf(e, "Failed to decode basic auth header %s in %s", base64Challenge, exchange);
                }
                int colonPos;
                if (plainChallenge != null && (colonPos = plainChallenge.indexOf(COLON)) > -1) {
                    String userName = plainChallenge.substring(0, colonPos);
                    char[] password = plainChallenge.substring(colonPos + 1).toCharArray();
                    IdentityManager idm = getIdentityManager(securityContext);
                    PasswordCredential credential = new PasswordCredential(password);
                    try {
                        final AuthenticationMechanismOutcome result;
                        Account account = idm.verify(userName, credential);
                        if (account != null) {
                            securityContext.authenticationComplete(account, name, false);
                            result = AuthenticationMechanismOutcome.AUTHENTICATED;
                        } else {
                            securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
                            result = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
                        }
                        return result;
                    } finally {
                        clear(password);
                    }
                }
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }
    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
Also used : Pattern(java.util.regex.Pattern) Account(io.undertow.security.idm.Account) IdentityManager(io.undertow.security.idm.IdentityManager) PasswordCredential(io.undertow.security.idm.PasswordCredential) Charset(java.nio.charset.Charset) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 7 with IdentityManager

use of io.undertow.security.idm.IdentityManager in project undertow by undertow-io.

the class ClientCertAuthenticationMechanism method authenticate.

public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
    SSLSessionInfo sslSession = exchange.getConnection().getSslSessionInfo();
    if (sslSession != null) {
        try {
            Certificate[] clientCerts = getPeerCertificates(exchange, sslSession, securityContext);
            if (clientCerts[0] instanceof X509Certificate) {
                Credential credential = new X509CertificateCredential((X509Certificate) clientCerts[0]);
                IdentityManager idm = getIdentityManager(securityContext);
                Account account = idm.verify(credential);
                if (account != null) {
                    securityContext.authenticationComplete(account, name, false);
                    return AuthenticationMechanismOutcome.AUTHENTICATED;
                }
            }
        } catch (SSLPeerUnverifiedException e) {
        // No action - this mechanism can not attempt authentication without peer certificates so allow it to drop out
        // to NOT_ATTEMPTED.
        }
    }
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
Also used : Account(io.undertow.security.idm.Account) Credential(io.undertow.security.idm.Credential) X509CertificateCredential(io.undertow.security.idm.X509CertificateCredential) IdentityManager(io.undertow.security.idm.IdentityManager) SSLSessionInfo(io.undertow.server.SSLSessionInfo) X509CertificateCredential(io.undertow.security.idm.X509CertificateCredential) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 8 with IdentityManager

use of io.undertow.security.idm.IdentityManager in project undertow by undertow-io.

the class DeploymentManagerImpl method setupSecurityHandlers.

/**
     * sets up the outer security handlers.
     * <p/>
     * the handler that actually performs the access check happens later in the chain, it is not setup here
     *
     * @param initialHandler The handler to wrap with security handlers
     */
private HttpHandler setupSecurityHandlers(HttpHandler initialHandler) {
    final DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();
    final LoginConfig loginConfig = deploymentInfo.getLoginConfig();
    HttpHandler current = initialHandler;
    current = new SSLInformationAssociationHandler(current);
    final SecurityPathMatches securityPathMatches = buildSecurityConstraints();
    securityPathMatches.logWarningsAboutUncoveredMethods();
    current = new ServletAuthenticationCallHandler(current);
    for (HandlerWrapper wrapper : deploymentInfo.getSecurityWrappers()) {
        current = wrapper.wrap(current);
    }
    if (deploymentInfo.isDisableCachingForSecuredPages()) {
        current = Handlers.predicate(Predicates.authRequired(), Handlers.disableCache(current), current);
    }
    if (!securityPathMatches.isEmpty()) {
        current = new ServletAuthenticationConstraintHandler(current);
    }
    current = new ServletConfidentialityConstraintHandler(deploymentInfo.getConfidentialPortManager(), current);
    if (!securityPathMatches.isEmpty()) {
        current = new ServletSecurityConstraintHandler(securityPathMatches, current);
    }
    HandlerWrapper initialSecurityWrapper = deploymentInfo.getInitialSecurityWrapper();
    String mechName = null;
    if (initialSecurityWrapper == null) {
        final Map<String, AuthenticationMechanismFactory> factoryMap = new HashMap<>(deploymentInfo.getAuthenticationMechanisms());
        final IdentityManager identityManager = deploymentInfo.getIdentityManager();
        if (!factoryMap.containsKey(BASIC_AUTH)) {
            factoryMap.put(BASIC_AUTH, new BasicAuthenticationMechanism.Factory(identityManager));
        }
        if (!factoryMap.containsKey(FORM_AUTH)) {
            factoryMap.put(FORM_AUTH, new ServletFormAuthenticationMechanism.Factory(identityManager));
        }
        if (!factoryMap.containsKey(DIGEST_AUTH)) {
            factoryMap.put(DIGEST_AUTH, new DigestAuthenticationMechanism.Factory(identityManager));
        }
        if (!factoryMap.containsKey(CLIENT_CERT_AUTH)) {
            factoryMap.put(CLIENT_CERT_AUTH, new ClientCertAuthenticationMechanism.Factory(identityManager));
        }
        if (!factoryMap.containsKey(ExternalAuthenticationMechanism.NAME)) {
            factoryMap.put(ExternalAuthenticationMechanism.NAME, new ExternalAuthenticationMechanism.Factory(identityManager));
        }
        if (!factoryMap.containsKey(GenericHeaderAuthenticationMechanism.NAME)) {
            factoryMap.put(GenericHeaderAuthenticationMechanism.NAME, new GenericHeaderAuthenticationMechanism.Factory(identityManager));
        }
        List<AuthenticationMechanism> authenticationMechanisms = new LinkedList<>();
        if (deploymentInfo.isUseCachedAuthenticationMechanism()) {
            authenticationMechanisms.add(new CachedAuthenticatedSessionMechanism(identityManager));
        }
        if (loginConfig != null || deploymentInfo.getJaspiAuthenticationMechanism() != null) {
            //we don't allow multipart requests, and use the default encoding when it's set
            FormEncodedDataDefinition formEncodedDataDefinition = new FormEncodedDataDefinition();
            if (deploymentInfo.getDefaultEncoding() != null) {
                formEncodedDataDefinition.setDefaultEncoding(deploymentInfo.getDefaultEncoding());
            }
            FormParserFactory parser = FormParserFactory.builder(false).addParser(formEncodedDataDefinition).build();
            List<AuthMethodConfig> authMethods = Collections.<AuthMethodConfig>emptyList();
            if (loginConfig != null) {
                authMethods = loginConfig.getAuthMethods();
            }
            for (AuthMethodConfig method : authMethods) {
                AuthenticationMechanismFactory factory = factoryMap.get(method.getName());
                if (factory == null) {
                    throw UndertowServletMessages.MESSAGES.unknownAuthenticationMechanism(method.getName());
                }
                if (mechName == null) {
                    mechName = method.getName();
                }
                final Map<String, String> properties = new HashMap<>();
                properties.put(AuthenticationMechanismFactory.CONTEXT_PATH, deploymentInfo.getContextPath());
                properties.put(AuthenticationMechanismFactory.REALM, loginConfig.getRealmName());
                properties.put(AuthenticationMechanismFactory.ERROR_PAGE, loginConfig.getErrorPage());
                properties.put(AuthenticationMechanismFactory.LOGIN_PAGE, loginConfig.getLoginPage());
                properties.putAll(method.getProperties());
                String name = method.getName().toUpperCase(Locale.US);
                // The mechanism name is passed in from the HttpServletRequest interface as the name reported needs to be
                // comparable using '=='
                name = name.equals(FORM_AUTH) ? FORM_AUTH : name;
                name = name.equals(BASIC_AUTH) ? BASIC_AUTH : name;
                name = name.equals(DIGEST_AUTH) ? DIGEST_AUTH : name;
                name = name.equals(CLIENT_CERT_AUTH) ? CLIENT_CERT_AUTH : name;
                authenticationMechanisms.add(factory.create(name, parser, properties));
            }
        }
        deployment.setAuthenticationMechanisms(authenticationMechanisms);
        //if the JASPI auth mechanism is set then it takes over
        if (deploymentInfo.getJaspiAuthenticationMechanism() == null) {
            current = new AuthenticationMechanismsHandler(current, authenticationMechanisms);
        } else {
            current = new AuthenticationMechanismsHandler(current, Collections.<AuthenticationMechanism>singletonList(deploymentInfo.getJaspiAuthenticationMechanism()));
        }
        current = new CachedAuthenticatedSessionHandler(current, this.deployment.getServletContext());
    }
    List<NotificationReceiver> notificationReceivers = deploymentInfo.getNotificationReceivers();
    if (!notificationReceivers.isEmpty()) {
        current = new NotificationReceiverHandler(current, notificationReceivers);
    }
    if (initialSecurityWrapper == null) {
        // TODO - A switch to constraint driven could be configurable, however before we can support that with servlets we would
        // need additional tracking within sessions if a servlet has specifically requested that authentication occurs.
        SecurityContextFactory contextFactory = deploymentInfo.getSecurityContextFactory();
        if (contextFactory == null) {
            contextFactory = SecurityContextFactoryImpl.INSTANCE;
        }
        current = new SecurityInitialHandler(deploymentInfo.getAuthenticationMode(), deploymentInfo.getIdentityManager(), mechName, contextFactory, current);
    } else {
        current = initialSecurityWrapper.wrap(current);
    }
    return current;
}
Also used : IdentityManager(io.undertow.security.idm.IdentityManager) DigestAuthenticationMechanism(io.undertow.security.impl.DigestAuthenticationMechanism) ExternalAuthenticationMechanism(io.undertow.security.impl.ExternalAuthenticationMechanism) HashMap(java.util.HashMap) SecurityPathMatches(io.undertow.servlet.handlers.security.SecurityPathMatches) ServletSecurityConstraintHandler(io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler) HandlerWrapper(io.undertow.server.HandlerWrapper) CachedAuthenticatedSessionHandler(io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler) ServletAuthenticationConstraintHandler(io.undertow.servlet.handlers.security.ServletAuthenticationConstraintHandler) SecurityInitialHandler(io.undertow.security.handlers.SecurityInitialHandler) ServletAuthenticationCallHandler(io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler) AuthMethodConfig(io.undertow.servlet.api.AuthMethodConfig) LoginConfig(io.undertow.servlet.api.LoginConfig) ServletFormAuthenticationMechanism(io.undertow.servlet.handlers.security.ServletFormAuthenticationMechanism) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) GenericHeaderAuthenticationMechanism(io.undertow.security.impl.GenericHeaderAuthenticationMechanism) HttpHandler(io.undertow.server.HttpHandler) CachedAuthenticatedSessionMechanism(io.undertow.security.impl.CachedAuthenticatedSessionMechanism) ClientCertAuthenticationMechanism(io.undertow.security.impl.ClientCertAuthenticationMechanism) ExternalAuthenticationMechanism(io.undertow.security.impl.ExternalAuthenticationMechanism) ServletFormAuthenticationMechanism(io.undertow.servlet.handlers.security.ServletFormAuthenticationMechanism) BasicAuthenticationMechanism(io.undertow.security.impl.BasicAuthenticationMechanism) DigestAuthenticationMechanism(io.undertow.security.impl.DigestAuthenticationMechanism) AuthenticationMechanism(io.undertow.security.api.AuthenticationMechanism) GenericHeaderAuthenticationMechanism(io.undertow.security.impl.GenericHeaderAuthenticationMechanism) LinkedList(java.util.LinkedList) FormParserFactory(io.undertow.server.handlers.form.FormParserFactory) NotificationReceiverHandler(io.undertow.security.handlers.NotificationReceiverHandler) AuthenticationMechanismsHandler(io.undertow.security.handlers.AuthenticationMechanismsHandler) NotificationReceiver(io.undertow.security.api.NotificationReceiver) ServletConfidentialityConstraintHandler(io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler) ClientCertAuthenticationMechanism(io.undertow.security.impl.ClientCertAuthenticationMechanism) FormEncodedDataDefinition(io.undertow.server.handlers.form.FormEncodedDataDefinition) AuthenticationMechanismFactory(io.undertow.security.api.AuthenticationMechanismFactory) BasicAuthenticationMechanism(io.undertow.security.impl.BasicAuthenticationMechanism) SSLInformationAssociationHandler(io.undertow.servlet.handlers.security.SSLInformationAssociationHandler) SecurityContextFactory(io.undertow.security.api.SecurityContextFactory)

Example 9 with IdentityManager

use of io.undertow.security.idm.IdentityManager in project undertow by undertow-io.

the class BasicAuthServer method main.

public static void main(final String[] args) {
    System.out.println("You can login with the following credentials:");
    System.out.println("User: userOne Password: passwordOne");
    System.out.println("User: userTwo Password: passwordTwo");
    final Map<String, char[]> users = new HashMap<>(2);
    users.put("userOne", "passwordOne".toCharArray());
    users.put("userTwo", "passwordTwo".toCharArray());
    final IdentityManager identityManager = new MapIdentityManager(users);
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity(new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final SecurityContext context = exchange.getSecurityContext();
            exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
        }
    }, identityManager)).build();
    server.start();
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) IdentityManager(io.undertow.security.idm.IdentityManager) HashMap(java.util.HashMap) SecurityContext(io.undertow.security.api.SecurityContext) Undertow(io.undertow.Undertow)

Aggregations

IdentityManager (io.undertow.security.idm.IdentityManager)9 Account (io.undertow.security.idm.Account)6 HttpHandler (io.undertow.server.HttpHandler)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 DigestAlgorithm (io.undertow.security.idm.DigestAlgorithm)2 PasswordCredential (io.undertow.security.idm.PasswordCredential)2 ByteBuffer (java.nio.ByteBuffer)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 Undertow (io.undertow.Undertow)1 AuthenticationMechanism (io.undertow.security.api.AuthenticationMechanism)1 AuthenticationMechanismFactory (io.undertow.security.api.AuthenticationMechanismFactory)1 NotificationReceiver (io.undertow.security.api.NotificationReceiver)1 SecurityContext (io.undertow.security.api.SecurityContext)1 SecurityContextFactory (io.undertow.security.api.SecurityContextFactory)1 AuthenticationMechanismsHandler (io.undertow.security.handlers.AuthenticationMechanismsHandler)1 NotificationReceiverHandler (io.undertow.security.handlers.NotificationReceiverHandler)1 SecurityInitialHandler (io.undertow.security.handlers.SecurityInitialHandler)1 Credential (io.undertow.security.idm.Credential)1 DigestCredential (io.undertow.security.idm.DigestCredential)1