01: /*
02: * Copyright 2002-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.web.servlet.handler;
18:
19: import java.io.IOException;
20:
21: import javax.servlet.ServletException;
22: import javax.servlet.http.HttpServletRequest;
23: import javax.servlet.http.HttpServletResponse;
24:
25: /**
26: * Interceptor that checks the authorization of the current user via the
27: * user's roles, as evaluated by HttpServletRequest's isUserInRole method.
28: *
29: * @author Juergen Hoeller
30: * @since 20.06.2003
31: * @see javax.servlet.http.HttpServletRequest#isUserInRole
32: */
33: public class UserRoleAuthorizationInterceptor extends
34: HandlerInterceptorAdapter {
35:
36: private String[] authorizedRoles;
37:
38: /**
39: * Set the roles that this interceptor should treat as authorized.
40: * @param authorizedRoles array of role names
41: */
42: public final void setAuthorizedRoles(String[] authorizedRoles) {
43: this .authorizedRoles = authorizedRoles;
44: }
45:
46: public final boolean preHandle(HttpServletRequest request,
47: HttpServletResponse response, Object handler)
48: throws ServletException, IOException {
49:
50: if (this .authorizedRoles != null) {
51: for (int i = 0; i < this .authorizedRoles.length; i++) {
52: if (request.isUserInRole(this .authorizedRoles[i])) {
53: return true;
54: }
55: }
56: }
57: handleNotAuthorized(request, response, handler);
58: return false;
59: }
60:
61: /**
62: * Handle a request that is not authorized according to this interceptor.
63: * Default implementation sends HTTP status code 403 ("forbidden").
64: * <p>This method can be overridden to write a custom message, forward or
65: * redirect to some error page or login page, or throw a ServletException.
66: * @param request current HTTP request
67: * @param response current HTTP response
68: * @param handler chosen handler to execute, for type and/or instance evaluation
69: * @throws javax.servlet.ServletException if there is an internal error
70: * @throws java.io.IOException in case of an I/O error when writing the response
71: */
72: protected void handleNotAuthorized(HttpServletRequest request,
73: HttpServletResponse response, Object handler)
74: throws ServletException, IOException {
75:
76: response.sendError(HttpServletResponse.SC_FORBIDDEN);
77: }
78:
79: }
|