001/* 002 * Copyright 2002-2014 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.servlet.handler; 018 019import java.io.IOException; 020import javax.servlet.ServletException; 021import javax.servlet.http.HttpServletRequest; 022import javax.servlet.http.HttpServletResponse; 023 024/** 025 * Interceptor that checks the authorization of the current user via the 026 * user's roles, as evaluated by HttpServletRequest's isUserInRole method. 027 * 028 * @author Juergen Hoeller 029 * @since 20.06.2003 030 * @see javax.servlet.http.HttpServletRequest#isUserInRole 031 */ 032public class UserRoleAuthorizationInterceptor extends HandlerInterceptorAdapter { 033 034 private String[] authorizedRoles; 035 036 037 /** 038 * Set the roles that this interceptor should treat as authorized. 039 * @param authorizedRoles array of role names 040 */ 041 public final void setAuthorizedRoles(String... authorizedRoles) { 042 this.authorizedRoles = authorizedRoles; 043 } 044 045 046 @Override 047 public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 048 throws ServletException, IOException { 049 050 if (this.authorizedRoles != null) { 051 for (String role : this.authorizedRoles) { 052 if (request.isUserInRole(role)) { 053 return true; 054 } 055 } 056 } 057 handleNotAuthorized(request, response, handler); 058 return false; 059 } 060 061 /** 062 * Handle a request that is not authorized according to this interceptor. 063 * Default implementation sends HTTP status code 403 ("forbidden"). 064 * <p>This method can be overridden to write a custom message, forward or 065 * redirect to some error page or login page, or throw a ServletException. 066 * @param request current HTTP request 067 * @param response current HTTP response 068 * @param handler chosen handler to execute, for type and/or instance evaluation 069 * @throws javax.servlet.ServletException if there is an internal error 070 * @throws java.io.IOException in case of an I/O error when writing the response 071 */ 072 protected void handleNotAuthorized(HttpServletRequest request, HttpServletResponse response, Object handler) 073 throws ServletException, IOException { 074 075 response.sendError(HttpServletResponse.SC_FORBIDDEN); 076 } 077 078}