|
| 1 | +package com.baeldung.undertow.secure; |
| 2 | + |
| 3 | +import java.util.Collections; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +import io.undertow.Undertow; |
| 9 | +import io.undertow.io.IoCallback; |
| 10 | +import io.undertow.security.api.AuthenticationMechanism; |
| 11 | +import io.undertow.security.api.AuthenticationMode; |
| 12 | +import io.undertow.security.api.SecurityContext; |
| 13 | +import io.undertow.security.handlers.AuthenticationCallHandler; |
| 14 | +import io.undertow.security.handlers.AuthenticationConstraintHandler; |
| 15 | +import io.undertow.security.handlers.AuthenticationMechanismsHandler; |
| 16 | +import io.undertow.security.handlers.SecurityInitialHandler; |
| 17 | +import io.undertow.security.idm.IdentityManager; |
| 18 | +import io.undertow.security.impl.BasicAuthenticationMechanism; |
| 19 | +import io.undertow.server.HttpHandler; |
| 20 | +import io.undertow.server.HttpServerExchange; |
| 21 | + |
| 22 | +public class SecureServer { |
| 23 | + |
| 24 | + public static void main(String[] args) { |
| 25 | + final Map<String, char[]> users = new HashMap<>(2); |
| 26 | + users.put("root", "password".toCharArray()); |
| 27 | + users.put("admin", "password".toCharArray()); |
| 28 | + |
| 29 | + final IdentityManager idm = new CustomIdentityManager(users); |
| 30 | + |
| 31 | + Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity((exchange) -> { |
| 32 | + final SecurityContext context = exchange.getSecurityContext(); |
| 33 | + exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), |
| 34 | + IoCallback.END_EXCHANGE); |
| 35 | + }, idm)).build(); |
| 36 | + |
| 37 | + server.start(); |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) { |
| 42 | + HttpHandler handler = toWrap; |
| 43 | + handler = new AuthenticationCallHandler(handler); |
| 44 | + handler = new AuthenticationConstraintHandler(handler); |
| 45 | + final List<AuthenticationMechanism> mechanisms = Collections |
| 46 | + .<AuthenticationMechanism> singletonList(new BasicAuthenticationMechanism("Baeldung_Realm")); |
| 47 | + handler = new AuthenticationMechanismsHandler(handler, mechanisms); |
| 48 | + handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler); |
| 49 | + return handler; |
| 50 | + } |
| 51 | + |
| 52 | +} |
0 commit comments