Springboot实现角色验证拦截器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq3399013670/article/details/87858675

Springboot实现角色验证拦截器简易demo,仅供参考:

UserRole枚举类,用户角色定义:

public enum UserRole
{
    /**
     * 1,管理员
     */
    ADMIN("1","ADMIN","超级用户"),
    
	/**
	 * 2,匿名访问
	 */
    ANONYMOUS("2","ANONYMOUS","匿名访问");
    
	/**
	 * 编号
	 */
	private String id;		
	/**
	 * 代号
	 */
	private String code;	
	/**
	 * 名称
	 */
	private String name;	
    // 私有构造,setter,getter方法省略
.....
.....

Authorization.java,授权注解,作用于controller类及其方法上,方法优先

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorization
{
    UserRole[] value() default{};
}

AuthChecker.java 对访问接口(Controller及其方法)进行实时权限检查,拦截器{@link AuthInterceptor}拦截了每个Controller方法的访问,并都会进入此处进行检查。

public class AuthChecker {
	/**
     * 执行权限检查。根据Controller的权限和实际登录用户的权限进行匹配,从而允许或者拒        绝访问。拒绝访问时,抛出异常。
     * @param presetRoles Controller上预先设置的允许访问权限集,即Authorization注解的内容
     * @param request Web请求对象
     * @throws GenericException 权限不匹配时,可抛出的异常
     */
    public static void check(List<UserRole> presetRoles, HttpServletRequest request) throws GenericException
    {
    	SessionInfo session = (SessionInfo) request.getSession().getAttribute("session");
    	// 若允许匿名访问,不做权限检查。
    	if (presetRoles.contains(UserRole.ANONYMOUS)){
    		return;
    	}else if(presetRoles.contains(UserRole.ADMIN) &&
    			session.getUser().getType().equals(UserRole.ADMIN.getId())) {
    		return;
    	} else {
    		throw new GenericException(ErrorCodes.EC_AUTH_FAILED);
    	}
    }
}

AuthInterceptor .java授权处理拦截器。
在执行controller之前判断用户是否有接口执行权限。具体的权限检查在AuthChecker中实现,可对其进行适当修改。


@Component("authInterceptor")
public class AuthInterceptor extends HandlerInterceptorAdapter
{
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception 
    {     
        if (handler.getClass().isAssignableFrom(HandlerMethod.class))
        {
            // 方法上是否有授权注解
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Authorization authorization = handlerMethod.getMethodAnnotation(Authorization.class);
            if (authorization == null)
            {
                // 方法所属类上是否有授权注解
                authorization = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Authorization.class);
                if (authorization == null)
                {
                    // 无授权注解,禁止访问
                    throw new GenericException("EC_AUTH_FAILED");
                }
            } 
            
            // 获取授权信息
            ArrayList<UserRole> roles = new ArrayList<UserRole>();
            for (int i = 0; i < authorization.value().length; i++)
            {
                roles.add(authorization.value()[i]);
            }
            
            // 权限检查时,若权限不匹配,需抛出异常
            AuthChecker.check(roles, request);
        }
        return true; 
    }
}

DemoConroller .java 权限拦截的使用:

@Controller
@RequestMapping("/test")
public class DemoConroller {
	@RequestMapping("/create")
	@Authorization({UserRole.ADMIN})
	public String forwardtestPage(HttpServletRequest request) {
		return "index.jsp";
	}
}

猜你喜欢

转载自blog.csdn.net/qq3399013670/article/details/87858675