需要星星支持 谢谢 ~
gitee地址:https://gitee.com/langhai666/langhai-blog
github地址:https://github.com/Allenkuzma/langhaiblogs
以下完整代码请查看开源项目 浪海博客,主要关注下面几个类。
cc.langhai.config.annotation.RequestAuthority(自定义权限注解)
cc.langhai.interceptor.authority.SecurityInterceptor(权限拦截器)
NO.01 开发自定义注解
package cc.langhai.config.annotation;
import java.lang.annotation.*;
/**
* 自定义权限注解
*
* @author langhai
* @date 2023-01-11 21:10
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RequestAuthority {
String[] value();
}
@Target注解指定我们的权限注解使用在方法上面,@Retention注解表示生存周期在运行时候。
NO.02 开发拦截器
package cc.langhai.interceptor.authority;
import cc.langhai.config.annotation.RequestAuthority;
import cc.langhai.domain.Role;
import cc.langhai.exception.AuthException;
import cc.langhai.response.SystemReturnCode;
import cc.langhai.service.RoleService;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* 自定义权限注解 拦截器
*
* @author langhai
* @date 2023-01-11 21:15
*/
public class SecurityInterceptor implements HandlerInterceptor {
@Autowired
private RoleService roleService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!isAuthority(handler)) {
throw new AuthException(SystemReturnCode.SYSTEM_AUTH_FAIL_00001);
}
return true;
}
/**
* 判断此次请求是否有权限
*
* @param handler
* @return 有权限返回true
*/
private boolean isAuthority(Object handler) {
boolean flag = false;
if (handler instanceof HandlerMethod) {
// 获得请求的方法
Method method = ((HandlerMethod) handler).getMethod();
// 获得该方法上面的注解,如果没有注解,直接返回true,通过
RequestAuthority annotation = method.getAnnotation(RequestAuthority.class);
if (annotation != null) {
// 得到当前登录人的权限,判断请求的权限是否包含在内
Role role = roleService.getRole();
if(ObjectUtil.isNull(role)){
throw new AuthException(SystemReturnCode.SYSTEM_AUTH_FAIL_00001);
}
// 获得注解的值(权限)
String[] values = annotation.value();
for (int i = 0; i < values.length; i++) {
String value = values[i];
if(value.equals(role.getName())){
flag = true;
}
}
}
}
return flag;
}
}
这里的逻辑思路是判断拦截下来的方法是否有我们自定义的权限注解,然后获取自定义注解里面的值,与登录用户的权限做对比,如果两者相等则放行请求。
NO.03 使用注解和配置拦截路径
/**
* 跳转到文章列表管理页面(admin权限)
*
* @return 返回文章列表管理页面
*/
@RequestAuthority(value = {"admin"})
@GetMapping("/systemArticleListPage")
public String systemArticleListPage(){
return "blogs/article/systemArticleList";
}
在需要校验权限的方法上使用自定义注解,这里填的值是admin管理员权限注解。
怎么配置拦截路径,直接看下面这个类即可。
cc.langhai.interceptor.authority.AuthorityConfig
主要是实现org.springframework.web.servlet.config.annotation.WebMvcConfigurer接口,然后重写方法。
最后的测试效果:
可以看到当用户的权限为admin的时候,则拦截器放行。