目 录
1.0 前言
最近接触了公司项目的登陆模块,感觉相关技术的运用比我先前用shiro实现的登录更加简洁轻便,实现相关功能之后,做个summary。相关技术包括spring拦截器,自定义注解。
2.0 登录实现
我这里就不贴LoginController.java跟login.html等相关页面了,也不贴用户,角色,权限相关了,比较偏题,自由发挥。我这是用户关联角色,角色关联菜单,把菜单当作权限管理,然后通过角色实现相关url的权限管理
2.1 定义相关注解
允许匿名访问注解
/**
* 是否允许匿名
* <p>
* Copyright (c) 2018 Choice, Inc.
* All Rights Reserved.
* Choice Proprietary and Confidential.
*
* @author duhuo
* @since 2018年03月27日
*/
@Target({ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AllowAnonymous {
}
权限放行注解
/**
* 用于admin拦截器放行其他角色使用权限
* <p>
* Copyright (c) 2018 Choice, Inc.
* All Rights Reserved.
* Choice Proprietary and Confidential.
*
* @author duhuo
* @since 2018年12月24日
*/
@Target({ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RolesAuth {
String roleCodes();
}
2.2 创建LoginInterceptor 实现 HandlerInterceptor
/**
* 权限拦截器
* <p>
* Copyright (c) 2018 Choice, Inc.
* All Rights Reserved.
* Choice Proprietary and Confidential.
*
* @author duhuo
* @since 2018年05月18日
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
// 进入方法前,返回false未通过拦截,返回true通过拦截,在定义false时需要定义一些处理方式,可以设置重定向
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object methodHandler) throws Exception {
AllowAnonymous allowAnonymous = ((HandlerMethod)methodHandler).getMethodAnnotation(AllowAnonymous.class);
if (allowAnonymous != null) {
// 允许匿名访问,放行
logger.info("【匿名访问,】");
return true;
}
HttpSession session = request.getSession();
// 获取session值
Object oper = session.getAttribute("oper");
if (oper == null) {
response.sendRedirect("/login");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
// 结束返回
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2.3 创建WebMvcConfig继承WebMvcConfigurerAdapter
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private LoginInterceptor loginInterceptor;
@Autowired
private AdminInterceptor adminInterceptor;
public void configurePathMatch(PathMatchConfigurer configurer) {
super.configurePathMatch(configurer);
}
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
FastJsonHttpMessageConverter4 fastConverter = new FastJsonHttpMessageConverter4();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.BrowserCompatible
);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
/**
* 配置拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).excludePathPatterns("/user-login", "/login", "/logout", "/fegin/message-sms/**", "/app/**");
// 登录拦截器
// admin拦截器
// registry.addInterceptor(adminInterceptor).excludePathPatterns("/user-login", "/login", "/appadmin/**", "/merchant-admin/**", "/logout", "/fegin/message-sms/**", "/app/**");
super.addInterceptors(registry);
}
// 跨域支持
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("PUT", "DELETE", "GET", "POST", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(false).maxAge(3600);
}
// 映射资源路径
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 第一个方法资源访问路径前缀,第二个方法设置资源路径
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/static/assets/");
}
}
此处注意几点
- registry.addInterceptor(loginInterceptor),这一步是添加先前我们自己定义的拦截器。
- registry.excludePathPatterns("/user-login", “/login”, “/logout”, “/fegin/message-sms/", "/app/”) 这一步是添加放行路径,访问这些url不会被拦截,这里有个坑,springBoot1.X版本的拦截器默认不拦截静态资源(static下面的资源),但是springBoot2.0版本的拦截器默认拦截静态资源,所以你要是使用2.X版本,此处需添加静态资源路径。
- 你访问的页面里,可能访问了别的资源,但是这些资源有没有放行,所以会报错,所以放行资源还是要设置好。
到这里就实现了登陆相关,但是这还是不够的,因为在不同的角色下所能访问到的资源是不同的,我这虽然通过角色管理了菜单,但是还是能够url访问到一些不愿意暴露的接口,所以接下来就是权限管理了。
3.0 权限管理
在这里先理一下拦截器的流程,首先需要明白spring的拦截器略微区别于servlet的过滤器,两者差别不大,一个依赖spring坐拥spring全家桶,能够获取ioc的相关支持,能够获取到容器中的bean;一个依赖servlet,存在依赖于servlet容器,在spring项目中少了很多优势。然后在自定义拦截器的时候,主要分为两步,
- 1,实现 HandlerInterceptor 接口,同步骤2.2;
- 2,前端映射器注册拦截器 ,同步骤2.3;
一般出问题在第二步,资源管理放行这一块,需要做到,功能尚未实现,代码务必谨慎。
3.1 定义管理员拦截器
管理员拦截器
**
* 超级管理员拦截器, 拦截除应用管理员及机构管理员除外
* <p>
* Copyright (c) 2018 Choice, Inc.
* All Rights Reserved.
* Choice Proprietary and Confidential.
*
* @author duhuo
* @since 2018年12/21
*/
@Component
public class AdminInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(AdminInterceptor.class);
// 进入方法前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object methodHandler) throws Exception {
AllowAnonymous allowAnonymous = ((HandlerMethod)methodHandler).getMethodAnnotation(AllowAnonymous.class);
if (allowAnonymous != null) {
// 允许匿名访问,放行
logger.info("【匿名访问,】");
return true;
}
HttpSession session = request.getSession();
// session中获取角色信息,需要在登陆的时候将用户角色信息存进session
Object role = session.getAttribute("roles");
if (role == null) {
response.sendRedirect("/error-page?errorMessage=auth error!!!");
return false;
}
String roles = (String)role;
// 判断该方法是否允许其他角色使用,配合最早定义的相关注解使用,若注解中包含该角色,则可以访问,否则权限错误
RolesAuth rolesAuth = ((HandlerMethod) methodHandler).getMethodAnnotation(RolesAuth.class);
if (rolesAuth != null) {
rolesAuth.roleCodes().split(",");
for (String roleCode : rolesAuth.roleCodes().split(",")) {
if (roles.indexOf(roleCode) != -1) {
return true;
}
}
}
// admin用户可以访问
if (roles.indexOf("admin") == -1) {
// 判断是否是ajax请求 application/x-www-form-urlencoded; charset=UTF-8
String contentType = request.getHeader("Content-Type");
if (StrUtil.isNotEmpty(contentType) && contentType.equals("application/x-www-form-urlencoded; charset=UTF-8")) {
// ajax 返回
response.setContentType("applation/json; charset=UTF-8");
ApiResult<String> stringApiResult = new ApiResult<>("", false, "权限错误!!!");
response.getWriter().write(JSON.toJSONString(stringApiResult));
return false;
} else {
response.sendRedirect("/error-page?errorMessage=auth error!!!");
}
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
// 结束返回
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
此处拦截器主要包括三个功能,一个是匿名访问,一个是被相关注解标记过的接口可被对应角色访问,最后一个是设置管理员可访问。
3.2 前端映射器添加admin拦截器
将之前创建的映射器里的注解打开即可
// admin拦截器
registry.addInterceptor(adminInterceptor).excludePathPatterns("/user-login", "/login", "/appadmin/**",
在配置完拦截器之后,检查放行资源路径。此处需要知道,注册的拦截器自上而下执行,此处定义了两个拦截器,一个登录,一个权限管理,在通过第一个拦截器后会返回true否则false,然后执行第二个拦截器里的内容,这点跟servlet里过滤器里的chain差不多。
3.3 controller 添加相关注解
例:
到这就实现了权限管理,代码不是特别难,思路比较重要,把握好细节基本没问题。
另外申明一点: 本人菜鸟,代码参考自公司大佬,所以比较片面,甚至一些地方会有描述不恰当或是错误,请指正,也欢迎朋友一块讨论。。。。