在项目中通过注解+拦截器实现权限控制

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。在项目中通过注解+拦截器实现权限控制,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

在做项目开发过程中,经常需要对请求进行权限拦截处理,前面文章介绍过使用Security进行管理,但是它是在是太强大,对于小的项目可能不需要那么多功能时就没有必要引入,下面介绍一种使用拦截器实现权限拦截,功能比较简单但是相当够用:
通过拦截器+注解实现请求拦截,首先需要定义个注解用于标识哪些请求需要进行拦截:

import java.lang.annotation.*;

/**
 * 登录检查注解注解
 * @author xingo
 * @date 2023/12/12
 *
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface AuthLogin {
	
	/**
	 * 检查是否已经登录
	 * @return
	 */
	boolean check() default false;

}

下面就需要定义拦截器了,拦截器拦截所有请求,判断请求的方法上面是否有注解,对于没有注解的请求表示不需要做权限拦截,直接放行;添加注解的请求需要做权限拦截,验证权限是否符合要求,符合要求的直接放行,否则返回没有权限:

import org.example.pojo.ApiResult;
import org.example.pojo.StatusCode;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 拦截器处理
 * @author xingo
 * @date: 2023/12/12
 */
@Component
public class ManagerAuthInteceptor implements HandlerInterceptor {

	/**
	 * 线程本地变量,注意tomcat是使用线程池,所以线程执行完一定要remove值
	 */
	public static final ThreadLocal<String> LocalUserName = new ThreadLocal<>();

	/**
	 * 在handler方法处理之前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(handler instanceof HandlerMethod) {
			HandlerMethod hm = (HandlerMethod) handler;
			Method method = hm.getMethod();
			Class<?> clazz = hm.getBeanType();

			// 判断添加了注解的方法或类才进行拦截
			boolean annotationType = clazz.isAnnotationPresent(AuthLogin.class);
			boolean annotationMethod = method.isAnnotationPresent(AuthLogin.class);
			if(annotationType || annotationMethod) {
				// 拦截到的请求需要判断用户名是否为空,如果为空表示用户身份验证失败,表示用户无访问权限
				String userName = this.getLoginUserName(request);
				if(userName == null) {
					LocalUserName.remove();
					String sReqType = request.getHeader("X-Requested-With");
					String contentType = request.getHeader("Content-Type");
					if ("XMLHttpRequest".equalsIgnoreCase(sReqType) || (contentType != null && contentType.toLowerCase().contains("application/json"))) {
						response.setContentType("application/json; charset=utf-8");
						response.getWriter().print(JacksonUtils.toJSONString(ApiResult.fail(StatusCode.C_10001)));
					} else {
						response.setContentType("text/html;charset=utf-8");
						response.getWriter().print("用户未登录");
					}
					return false;
				} else {
					LocalUserName.set(userName);
					return true;
				}
			}
		}
		return true;
	}

	/**
	 * 获取登录用户信息
	 * @param request   http请求体
	 * @return
	 */
	private String getLoginUserName(HttpServletRequest request) {
		try {
			String token = "";
			if (request.getCookies() != null) {
				for (Cookie c : request.getCookies()) {
					if (null != c && "TOKEN".equals(c.getName())) {
						token = c.getValue();
						break;
					}
				}
			}
			// 简单通过cookie中的token做权限判断,如果有token且符合要求就返回用户名,否则表示用户身份认证失败
			if(token != null && token.length() > 10) {
				String userName = token.substring(10);
				return userName.equals("admin") ? userName : null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 在handler方法成功处理之后且dispatcher进行视图的渲染之前执行,当方法抛出异常时不会执行
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		LocalUserName.remove();
	}

	/**
	 * 在视图渲染结束后执行,并且无论handler方法中是否抛出异常都一定会执行
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		LocalUserName.remove();
	}
}

上面内容就是简单的权限拦截处理,实际项目中需要根据实际情况进行调整,做权限判断是否可以放行或拒绝。
拦截器定义好后,需要将它注入到系统中:

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置拦截器
 * @author xingo
 * @date: 2023/12/12
 */
@Configuration
@ConditionalOnWebApplication
//@ConditionalOnProperty(prefix = "example.demo", name="webName", havingValue = "MANAGER")    // 根据环境的不同注入不同的拦截器
public class ManagerAuthConfig implements WebMvcConfigurer {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new ManagerAuthInteceptor());
	}
}

在demo的controller中添加方法,方法上面增加身份注解,其他方法保持不变,没有添加注解的方法表示不需要进行拦截,添加注解的方法要验证身份并进行拦截:

import org.example.handler.AuthLogin;
import org.example.handler.BusinessException;
import org.example.handler.ManagerAuthInteceptor;
import org.example.pojo.ApiResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author xingo
 * @Date 2023/12/7
 */
@RestController
public class DemoController {

    @GetMapping("/demo1")
    public Object demo1() {
        int i = 1, j = 0;

        return i / j;
    }

    @GetMapping("/demo2")
    public Object demo2() {
        if(System.currentTimeMillis() > 1) {
            throw BusinessException.fail(88888, "业务数据不合法");
        }

        return System.currentTimeMillis();
    }

    @GetMapping("/demo3")
    public Map<String, Object> demo3() {
        Map<String, Object> map = new HashMap<>();
        map.put("key1", "Hello,world!");
        map.put("key2", new Date());

        return map;
    }

    @GetMapping("/demo4")
    public List<Object> demo4() {
        List<Object> list = new ArrayList<>();
        list.add(new Date());
        list.add("Hello,world!");
        list.add(Long.MAX_VALUE);
        list.add(Integer.MAX_VALUE);

        return list;
    }

    @GetMapping("/demo5")
    public Map<String, Object> demo5() throws InterruptedException {
        Map<String, Object> map = new HashMap<>();
        map.put("method", "demo5");
        map.put("start", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
        TimeUnit.SECONDS.sleep(1);
        map.put("end", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));

        return map;
    }

    @GetMapping("/demo6")
    public ApiResult demo6() throws InterruptedException {
        Map<String, Object> map = new HashMap<>();
        map.put("method", "demo6");
        map.put("start", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
        TimeUnit.SECONDS.sleep(1);
        map.put("end", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));

        return ApiResult.success(map);
    }

    @AuthLogin
    @GetMapping("/demo7")
    public Map<String, Object> demo7() {
        Map<String, Object> map = new HashMap<>();
        map.put("method", "demo7");
        map.put("userName", ManagerAuthInteceptor.LocalUserName.get());
        map.put("time", new Date());

        return map;
    }
}

经过测试,添加注解的方法需要身份验证并且符合要求后才会正确返回信息,否则会拦截请求;而对于没有添加注解的方法会直接放行。
登录成功访问接口

登录失败访问接口
访问不拦截的接口

通过拦截器加注解方式还是很方便的进行权限控制,下一篇文章分享通过使用过滤器同样实现权限拦截控制。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/181817.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!