001/* 002 * Copyright 2002-2017 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; 020 021import javax.servlet.ServletException; 022import javax.servlet.http.HttpServletRequest; 023import javax.servlet.http.HttpServletResponse; 024 025import org.springframework.lang.Nullable; 026 027/** 028 * Interceptor that checks the authorization of the current user via the 029 * user's roles, as evaluated by HttpServletRequest's isUserInRole method. 030 * 031 * @author Juergen Hoeller 032 * @since 20.06.2003 033 * @see javax.servlet.http.HttpServletRequest#isUserInRole 034 */ 035public class UserRoleAuthorizationInterceptor extends HandlerInterceptorAdapter { 036 037 @Nullable 038 private String[] authorizedRoles; 039 040 041 /** 042 * Set the roles that this interceptor should treat as authorized. 043 * @param authorizedRoles array of role names 044 */ 045 public final void setAuthorizedRoles(String... authorizedRoles) { 046 this.authorizedRoles = authorizedRoles; 047 } 048 049 050 @Override 051 public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 052 throws ServletException, IOException { 053 054 if (this.authorizedRoles != null) { 055 for (String role : this.authorizedRoles) { 056 if (request.isUserInRole(role)) { 057 return true; 058 } 059 } 060 } 061 handleNotAuthorized(request, response, handler); 062 return false; 063 } 064 065 /** 066 * Handle a request that is not authorized according to this interceptor. 067 * Default implementation sends HTTP status code 403 ("forbidden"). 068 * <p>This method can be overridden to write a custom message, forward or 069 * redirect to some error page or login page, or throw a ServletException. 070 * @param request current HTTP request 071 * @param response current HTTP response 072 * @param handler chosen handler to execute, for type and/or instance evaluation 073 * @throws javax.servlet.ServletException if there is an internal error 074 * @throws java.io.IOException in case of an I/O error when writing the response 075 */ 076 protected void handleNotAuthorized(HttpServletRequest request, HttpServletResponse response, Object handler) 077 throws ServletException, IOException { 078 079 response.sendError(HttpServletResponse.SC_FORBIDDEN); 080 } 081 082}