io.undertow.security.idm.IdentityManager Java Examples

The following examples show how to use io.undertow.security.idm.IdentityManager. 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: BasicAuthServer.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
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.writeAsync("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
                    }
                }, identityManager))
                .build();
        server.start();
    }
 
Example #2
Source File: DigestAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public DigestAuthenticationMechanism(final List<DigestAlgorithm> supportedAlgorithms, final List<DigestQop> supportedQops,
        final String realmName, final String domain, final NonceManager nonceManager, final String mechanismName, final IdentityManager identityManager) {
    this.supportedAlgorithms = supportedAlgorithms;
    this.supportedQops = supportedQops;
    this.realmName = realmName;
    this.domain = domain;
    this.nonceManager = nonceManager;
    this.mechanismName = mechanismName;
    this.identityManager = identityManager;

    if (!supportedQops.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        Iterator<DigestQop> it = supportedQops.iterator();
        sb.append(it.next().getToken());
        while (it.hasNext()) {
            sb.append(",").append(it.next().getToken());
        }
        qopString = sb.toString();
    } else {
        qopString = null;
    }
}
 
Example #3
Source File: BasicAuthenticationMechanism.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public AuthenticationMechanism create(String mechanismName,IdentityManager identityManager, FormParserFactory formParserFactory, Map<String, String> properties) {
    String realm = properties.get(REALM);
    String silent = properties.get(SILENT);
    String charsetString = properties.get(CHARSET);
    Charset charset = charsetString == null ? StandardCharsets.UTF_8 : Charset.forName(charsetString);
    Map<Pattern, Charset> userAgentCharsets = new HashMap<>();
    String userAgentString = properties.get(USER_AGENT_CHARSETS);
    if(userAgentString != null) {
        String[] parts = userAgentString.split(",");
        if(parts.length % 2 != 0) {
            throw UndertowMessages.MESSAGES.userAgentCharsetMustHaveEvenNumberOfItems(userAgentString);
        }
        for(int i = 0; i < parts.length; i += 2) {
            Pattern pattern = Pattern.compile(parts[i]);
            Charset c = Charset.forName(parts[i + 1]);
            userAgentCharsets.put(pattern, c);
        }
    }

    return new BasicAuthenticationMechanism(realm, mechanismName, silent != null && silent.equals("true"), identityManager, charset, userAgentCharsets);
}
 
Example #4
Source File: ClientCertAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
    SSLSessionInfo sslSession = exchange.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.
        }
    }

    /*
     * For ClientCert we do not have a concept of a failed authentication, if the client did use a key then it was deemed
     * acceptable for the connection to be established, this mechanism then just 'attempts' to use it for authentication but
     * does not mandate success.
     */

    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #5
Source File: SecurityInitialHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public SecurityInitialHandler(final AuthenticationMode authenticationMode, final IdentityManager identityManager,
        final String programaticMechName, final SecurityContextFactory contextFactory, final HttpHandler next) {
    super(next);
    this.authenticationMode = authenticationMode;
    this.identityManager = identityManager;
    this.programaticMechName = programaticMechName;
    this.contextFactory = contextFactory;
}
 
Example #6
Source File: LightBasicAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
public LightBasicAuthenticationMechanism(final String realmName, final String mechanismName, final boolean silent, final IdentityManager identityManager, Charset charset, Map<Pattern, Charset> userAgentCharsets) {
    this.challenge = BASIC_PREFIX + "realm=\"" + realmName + "\"";
    this.name = mechanismName;
    this.silent = silent;
    this.identityManager = identityManager;
    this.charset = charset;
    this.userAgentCharsets = Collections.unmodifiableMap(new LinkedHashMap<>(userAgentCharsets));
}
 
Example #7
Source File: FormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public FormAuthenticationMechanism(final FormParserFactory formParserFactory, final String name, final String loginPage, final String errorPage, final String postLocation, final IdentityManager identityManager) {
    this.name = name;
    this.loginPage = loginPage;
    this.errorPage = errorPage;
    this.postLocation = postLocation;
    this.formParserFactory = formParserFactory;
    this.identityManager = identityManager;
}
 
Example #8
Source File: ClientCertAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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.
        }
    }

    /*
     * For ClientCert we do not have a concept of a failed authentication, if the client did use a key then it was deemed
     * acceptable for the connection to be established, this mechanism then just 'attempts' to use it for authentication but
     * does not mandate success.
     */

    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #9
Source File: SecurityContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SecurityContextImpl(final HttpServerExchange exchange, final AuthenticationMode authenticationMode, final IdentityManager identityManager) {
    super(exchange);
    this.authenticationMode = authenticationMode;
    this.identityManager = identityManager;
    if (System.getSecurityManager() != null) {
        System.getSecurityManager().checkPermission(PERMISSION);
    }
}
 
Example #10
Source File: SecurityContextFactoryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SecurityContext createSecurityContext(final HttpServerExchange exchange, final AuthenticationMode mode,
    final IdentityManager identityManager, final String programmaticMechName) {
    SecurityContextImpl securityContext = SecurityActions.createSecurityContextImpl(exchange, mode, identityManager);
    if (programmaticMechName != null)
        securityContext.setProgramaticMechName(programmaticMechName);
    return securityContext;
}
 
Example #11
Source File: BasicAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public BasicAuthenticationMechanism(final String realmName, final String mechanismName, final boolean silent, final IdentityManager identityManager, Charset charset, Map<Pattern, Charset> userAgentCharsets) {
    this.challenge = BASIC_PREFIX + "realm=\"" + realmName + "\"";
    this.name = mechanismName;
    this.silent = silent;
    this.identityManager = identityManager;
    this.charset = charset;
    this.userAgentCharsets = Collections.unmodifiableMap(new LinkedHashMap<>(userAgentCharsets));
}
 
Example #12
Source File: DatawaveAuthenticationMechanism.java    From datawave with Apache License 2.0 5 votes vote down vote up
public DatawaveAuthenticationMechanism(String mechanismName, boolean forceRenegotiation, IdentityManager identityManager) {
    this.name = mechanismName;
    this.forceRenegotiation = forceRenegotiation;
    this.identityManager = identityManager;
    trustedHeaderAuthentication = Boolean.valueOf(System.getProperty("dw.trusted.header.authentication", "false"));
    jwtHeaderAuthentication = Boolean.valueOf(System.getProperty("dw.jwt.header.authentication", "false"));
    SUBJECT_DN_HEADER = System.getProperty("dw.trusted.header.subjectDn", "X-SSL-ClientCert-Subject".toLowerCase());
    ISSUER_DN_HEADER = System.getProperty("dw.trusted.header.issuerDn", "X-SSL-ClientCert-Issuer".toLowerCase());
}
 
Example #13
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    final IdentityManager basicIdentityManager = new LightIdentityManager();

    HttpHandler handler = Handlers.routing()
        .add(Methods.GET, "/health/"+server.get("serviceId"), new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.GET, "/oauth2/code", addGetSecurity(new Oauth2CodeGetHandler(), basicIdentityManager))
        .add(Methods.POST, "/oauth2/code", addFormSecurity(new Oauth2CodePostHandler(), basicIdentityManager))
    ;
    return handler;
}
 
Example #14
Source File: SecureServer.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    final Map<String, char[]> users = new HashMap<>(2);
    users.put("root", "password".toCharArray());
    users.put("admin", "password".toCharArray());

    final IdentityManager idm = new CustomIdentityManager(users);

    Undertow server = Undertow.builder()
      .addHttpListener(8080, "localhost")
      .setHandler(addSecurity(SecureServer::setExchange, idm)).build();

    server.start();
}
 
Example #15
Source File: SecurityActions.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
static SecurityContextImpl createSecurityContextImpl(final HttpServerExchange exchange, final AuthenticationMode authenticationMode, final IdentityManager identityManager) {
    if (System.getSecurityManager() == null) {
        return new SecurityContextImpl(exchange, authenticationMode, identityManager);
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<SecurityContextImpl>() {
            @Override
            public SecurityContextImpl run() {
                return new SecurityContextImpl(exchange, authenticationMode, identityManager);
            }
        });
    }
}
 
Example #16
Source File: BasicAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public BasicAuthenticationMechanism(final String realmName, final String mechanismName, final boolean silent, final IdentityManager identityManager, Charset charset, Map<Pattern, Charset> userAgentCharsets) {
    this.challenge = BASIC_PREFIX + "realm=\"" + realmName + "\"";
    this.name = mechanismName;
    this.silent = silent;
    this.identityManager = identityManager;
    this.charset = charset;
    this.userAgentCharsets = Collections.unmodifiableMap(new LinkedHashMap<>(userAgentCharsets));
}
 
Example #17
Source File: SecurityContextFactoryImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityContext createSecurityContext(final HttpServerExchange exchange, final AuthenticationMode mode,
    final IdentityManager identityManager, final String programmaticMechName) {
    SecurityContextImpl securityContext = SecurityActions.createSecurityContextImpl(exchange, mode, identityManager);
    if (programmaticMechName != null)
        securityContext.setProgramaticMechName(programmaticMechName);
    return securityContext;
}
 
Example #18
Source File: FormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public FormAuthenticationMechanism(final FormParserFactory formParserFactory, final String name, final String loginPage, final String errorPage, final String postLocation, final IdentityManager identityManager) {
    this.name = name;
    this.loginPage = loginPage;
    this.errorPage = errorPage;
    this.postLocation = postLocation;
    this.formParserFactory = formParserFactory;
    this.identityManager = identityManager;
}
 
Example #19
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    final IdentityManager identityManager = new MapIdentityManager(users);

    HttpHandler handler = Handlers.routing()
        .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.GET, "/oauth2/authorize", addBasicSecurity(new Oauth2AuthorizeGetHandler(), identityManager))
        .add(Methods.POST, "/oauth2/authorize", addFormSecurity(new Oauth2AuthorizePostHandler(), identityManager))
    ;
    return handler;
}
 
Example #20
Source File: BasicAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @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);
                    }
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #21
Source File: CachedAuthenticatedSessionMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public CachedAuthenticatedSessionMechanism(final IdentityManager identityManager) {
    this.identityManager = identityManager;
}
 
Example #22
Source File: LightBasicAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private IdentityManager getIdentityManager(SecurityContext securityContext) {
    return identityManager != null ? identityManager : securityContext.getIdentityManager();
}
 
Example #23
Source File: DigestAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private IdentityManager getIdentityManager(SecurityContext securityContext) {
    return identityManager != null ? identityManager : securityContext.getIdentityManager();
}
 
Example #24
Source File: GSSAPIAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public GSSAPIAuthenticationMechanism(final GSSAPIServerSubjectFactory subjectFactory, IdentityManager identityManager, Oid ...supportedMechanisms) {
    this.subjectFactory = subjectFactory;
    this.identityManager = identityManager;
    this.mechanisms = supportedMechanisms;
}
 
Example #25
Source File: LightGSSAPIAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private IdentityManager getIdentityManager(SecurityContext securityContext) {
    return identityManager != null ? identityManager : securityContext.getIdentityManager();
}
 
Example #26
Source File: LightBasicAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
/**
 * @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);
                    if(logger.isDebugEnabled()) logger.debug("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, exchange);
                } catch (IOException e) {
                    logger.error("Failed to decode basic auth header " + base64Challenge + " in " + exchange, e);
                }
                int colonPos;
                if (plainChallenge != null && (colonPos = plainChallenge.indexOf(COLON)) > -1) {
                    String userName = plainChallenge.substring(0, colonPos);
                    char[] password = plainChallenge.substring(colonPos + 1).toCharArray();

                    // get clientAuthClass and userType
                    String clientAuthClass = null;
                    String userType = null;
                    Map<String, Deque<String>> params = exchange.getQueryParameters();
                    Deque<String> clientIdDeque = params.get("client_id");
                    if(clientIdDeque != null) {
                        String clientId = clientIdDeque.getFirst();
                        IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
                        Client client = clients.get(clientId);
                        if(client != null) {
                            clientAuthClass = client.getAuthenticateClass();
                        }
                    }
                    Deque<String> userTypeDeque = params.get("user_type");
                    if(userTypeDeque != null) {
                        userType = userTypeDeque.getFirst();
                    }

                    IdentityManager idm = getIdentityManager(securityContext);
                    LightPasswordCredential credential = new LightPasswordCredential(password, clientAuthClass, userType, exchange);
                    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);
                    }
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #27
Source File: FormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public FormAuthenticationMechanism(final FormParserFactory formParserFactory, final String name, final String loginPage, final String errorPage, final IdentityManager identityManager) {
    this(formParserFactory, name, loginPage, errorPage, DEFAULT_POST_LOCATION, identityManager);
}
 
Example #28
Source File: ImmediateAuthenticationMechanismFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public AuthenticationMechanism create(String mechanismName, IdentityManager identityManager, FormParserFactory formParserFactory, Map<String, String> properties) {
    return authenticationMechanism;
}
 
Example #29
Source File: GSSAPIAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private IdentityManager getIdentityManager(SecurityContext securityContext) {
    return identityManager != null ? identityManager : securityContext.getIdentityManager();
}
 
Example #30
Source File: ServletFormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ServletFormAuthenticationMechanism(FormParserFactory formParserFactory, String name, String loginPage, String errorPage, IdentityManager identityManager, boolean saveOriginalRequest) {
    super(formParserFactory, name, loginPage, errorPage, identityManager);
    this.saveOriginalRequest = saveOriginalRequest;
}