001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.shiro.authz.aop; 020 021import org.apache.shiro.authz.AuthorizationException; 022 023import javax.annotation.security.RolesAllowed; 024import java.lang.annotation.Annotation; 025 026/** 027 * Checks to see if a @{@link RolesAllowed} annotation is declared, and if so, performs 028 * a role check to see if the calling <code>Subject</code> is allowed to proceed. 029 * 030 * @since 2.0 031 */ 032public class RolesAllowedAnnotationHandler extends AuthorizingAnnotationHandler { 033 034 /** 035 * Default no-argument constructor that ensures this handler looks for 036 * {@link org.apache.shiro.authz.annotation.RequiresRoles RequiresRoles} annotations. 037 */ 038 public RolesAllowedAnnotationHandler() { 039 super(RolesAllowed.class); 040 } 041 042 /** 043 * Ensures that the calling <code>Subject</code> has one of the Annotation's specified roles, and if not, throws an 044 * <code>AuthorizingException</code> indicating that access is denied. 045 * 046 * @param a the RolesAllowed annotation to use to check for one or more roles 047 * @throws org.apache.shiro.authz.AuthorizationException if the calling <code>Subject</code> does not have the role 048 * necessary to proceed. 049 */ 050 @Override 051 public void assertAuthorized(Annotation a) throws AuthorizationException { 052 if (!(a instanceof RolesAllowed)) { 053 return; 054 } 055 056 RolesAllowed raAnnotation = (RolesAllowed) a; 057 String[] roles = raAnnotation.value(); 058 059 if (roles.length == 1) { 060 getSubject().checkRole(roles[0]); 061 return; 062 } 063 064 // Logical OR 065 066 // Avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasRole first 067 boolean hasAtLeastOneRole = false; 068 for (String role : roles) { 069 if (getSubject().hasRole(role)) { 070 hasAtLeastOneRole = true; 071 } 072 } 073 // Cause the exception if none of the role match, note that the exception message will be a bit misleading 074 if (!hasAtLeastOneRole) { 075 getSubject().checkRole(roles[0]); 076 } 077 } 078}