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 package io.undertow.servlet.handlers.security;
19
20 import io.undertow.security.api.SecurityContext;
21 import io.undertow.server.HttpHandler;
22 import io.undertow.server.HttpServerExchange;
23 import io.undertow.servlet.handlers.ServletRequestContext;
24 import io.undertow.util.StatusCodes;
25
26 /**
27  * This is the final {@link io.undertow.server.HttpHandler} in the security chain, it's purpose is to act as a barrier at the end of the chain to
28  * ensure authenticate is called after the mechanisms have been associated with the context and the constraint checked.
29  *
30  * This handler uses the Servlet {@link javax.servlet.http.HttpServletResponse#sendError(int)} method to make
31  * sure the correct error page is displayed.
32  *
33  * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
34  */

35 public class ServletAuthenticationCallHandler implements HttpHandler {
36
37     private final HttpHandler next;
38
39     public ServletAuthenticationCallHandler(final HttpHandler next) {
40         this.next = next;
41     }
42
43     /**
44      * Only allow the request through if successfully authenticated or if authentication is not required.
45      *
46      * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
47      */

48     @Override
49     public void handleRequest(final HttpServerExchange exchange) throws Exception {
50         if(exchange.isInIoThread()) {
51             exchange.dispatch(this);
52             return;
53         }
54         SecurityContext context = exchange.getSecurityContext();
55         if (context.authenticate()) {
56             if(!exchange.isComplete()) {
57                next.handleRequest(exchange);
58             }
59         } else {
60             if(exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
61                 ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
62                 src.getOriginalResponse().sendError(exchange.getStatusCode());
63             } else {
64                 exchange.endExchange();
65             }
66         }
67     }
68
69 }
70