1 /*
2  * JBoss, Home of Professional Open Source.
3  * Copyright 2014 Red Hat, Inc., and individual contributors
4  * as indicated by the @author tags.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  */

18
19 package io.undertow.security.handlers;
20
21 import io.undertow.Handlers;
22 import io.undertow.security.api.AuthenticationMechanism;
23 import io.undertow.security.api.AuthenticationMechanismContext;
24 import io.undertow.security.api.SecurityContext;
25 import io.undertow.server.HttpHandler;
26 import io.undertow.server.HttpServerExchange;
27 import io.undertow.server.handlers.ResponseCodeHandler;
28
29 import java.util.List;
30
31 /**
32  * Authentication handler that adds one or more authentication
33  * mechanisms to the security context
34  *
35  * @author Stuart Douglas
36  */

37 public class AuthenticationMechanismsHandler implements HttpHandler {
38
39     private volatile HttpHandler next = ResponseCodeHandler.HANDLE_404;
40     private final AuthenticationMechanism[] authenticationMechanisms;
41
42     public AuthenticationMechanismsHandler(final HttpHandler next, final List<AuthenticationMechanism> authenticationMechanisms) {
43         this.next = next;
44         this.authenticationMechanisms = authenticationMechanisms.toArray(new AuthenticationMechanism[authenticationMechanisms.size()]);
45     }
46
47     public AuthenticationMechanismsHandler(final List<AuthenticationMechanism> authenticationHandlers) {
48         this.authenticationMechanisms = authenticationHandlers.toArray(new AuthenticationMechanism[authenticationHandlers.size()]);
49     }
50
51     @Override
52     public void handleRequest(final HttpServerExchange exchange) throws Exception {
53         final SecurityContext sc = exchange.getSecurityContext();
54         if(sc != null && sc instanceof AuthenticationMechanismContext) {
55             AuthenticationMechanismContext amc = (AuthenticationMechanismContext) sc;
56             for(int i = 0; i < authenticationMechanisms.length; ++i) {
57                 amc.addAuthenticationMechanism(authenticationMechanisms[i]);
58             }
59         }
60         next.handleRequest(exchange);
61     }
62
63     public HttpHandler getNext() {
64         return next;
65     }
66
67     public AuthenticationMechanismsHandler setNext(final HttpHandler next) {
68         Handlers.handlerNotNull(next);
69         this.next = next;
70         return this;
71     }
72
73 }
74