15.权限控制
当用户发出请求时,可以判断用户是否拥有权限访问该接口
一,自定义注解
作用:放在controller层接口上,标识该接口是个受控接口,只有拥有该权限才能访问
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PreAuthorize {
String[] value();
}
二,使用注解
@GetMapping("/queryUserMenu")
@PreAuthorize(value = {"goodInfo11","goodAdd"})
public ResponseData<?> queryUserMenu(){
return menuService.queryUserMenu();
}
三,定义一个根据用户id查询用户权限的mapper
@Repository
public interface AuthMapper {
List<String> queryAuthByUserId(Integer userId);
}
<select id="queryAuthByUserId" resultType="string">
SELECT
ta.authCode
FROM
t_employee te
LEFT JOIN t_employee_auth tea ON te.id = tea.employeeId
LEFT JOIN t_auth ta ON tea.authId = ta.id
WHERE
te.id = #{userId}
</select>
四,定义一个拦截器
package com.woniuxy.intecepter;
@Component
public class AuthrizaIntecepter implements HandlerInterceptor {
@Autowired
private AuthMapper authMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//从request获取当前登录用户id,没有登录模拟获取到用户Id
Integer userId = 1;
//根据用户的id查询当前登录用户的角色
List<String> authcode = authMapper.queryAuthByUserId(userId);
if (handler instanceof HandlerMethod) {//确认访问的是否是controller里面的方法
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();//获取用户正在访问的方法的对象
PreAuthorize preAuthorize = method.getAnnotation(PreAuthorize.class);//获取这个方法上的PreAuthorize注解
if (preAuthorize != null) {//表示这个方法上真的有PreAuthorize这个注解
String[] AuthArr = preAuthorize.value();//获取这个注解上面填写的
//当前登录用户的权限,是否在这个AuthArr数组中,在表示有权限,不在就响应无权限
boolean b = Arrays.stream(AuthArr).anyMatch(s -> authcode.contains(s));
if (!b) {
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(JSON.toJSONString(new ResponseData<>().fail(ResponseEnum.NO_AUTH)));
return false;
}
}
}
return true;
}
}
五,注册拦截器
package com.woniuxy.config;
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private AuthrizaIntecepter authrizaIntecepter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authrizaIntecepter)
.addPathPatterns("/**")
//放行不需要走该拦截的请求。比如登录等
.excludePathPatterns("/user/login");
}
}
本文来自博客园,作者:icui4cu,转载请注明原文链接:https://www.cnblogs.com/icui4cu/p/18921685

浙公网安备 33010602011771号