spring-boot中登录过滤功能如何实现

  介绍

这篇文章主要介绍了spring-boot中登录过滤功能如何实现,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

先简单说一下我们工程的架构:前端工程是采用反应,后端工程采用spring-cloud,里面分为zuul工程和其他功能模块.zuul工程除了提供后端的路由转发,还可以做全局的过滤器,所以我选择在这个工程里面写登陆校验功能。

会话配置

这里使用复述,存储会话信息。
下载依赖,在砰的一声。xml里面加入

& lt; dependency>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter-data-redis   & lt;/dependency>   & lt; dependency>   & lt; groupId> org.springframework.session   & lt; artifactId> spring-session-data-redis   & lt;/dependency>

配置会话存储,在应用程序中。yml里面加入

会话:   存储类型:复述,   超时:30   复述:   数据库:0   主持人:   密码:   端口:6379   超时:300000

会话超时,在应用程序中。yml里面配置超时貌似没有效果,我们在启动类里面加入超时配置注解

@EnableRedisHttpSession (maxInactiveIntervalInSeconds=7200, redisFlushMode=RedisFlushMode.IMMEDIATE)

添加复述类配置,新建一个redisConfig类,然后写入

包com.config;   进口org.springframework.context.annotation.Configuration;   @ configuration   公开课RedisConfig {   公共RedisConfig () {      }   }

过滤器

这里使用zuulFilter,实现了每个http请求都经过这个过滤器,然后通过会话中是否存在用户名,判断会话是否超时。如果超时就返回错误提示,前端再根据超时的http请求码进行跳转。

包com.config;   进口com.netflix.zuul.ZuulFilter;   进口com.netflix.zuul.context.RequestContext;   进口com.ztesoft.cloud.Service.StaffService;   进口com.ztesoft.cloud.model.User;   进口org.springframework.beans.factory.annotation.Autowired;   进口javax.servlet.http.HttpServletRequest;   公开课WebSecurityFilter延伸ZuulFilter {   @Override   公共字符串filterType () {   返回“pre"//前置过滤器   }   @Override   公共int filterOrder () {   返回0;//优先级为0,数字越大,优先级越低   }   @Override   公共布尔shouldFilter () {   返回true;//是否执行该过滤器,此处为真,说明需要过滤   }   @ autowired   私人StaffService StaffService;   @Override   公共对象的run () {   RequestContext ctx=RequestContext.getCurrentContext ();   HttpServletRequest请求=ctx.getRequest ();   字符串变量=request.getQueryString ();   对象的用户名=request.getSession () .getAttribute (“username");   对象=request.getSession密码().getAttribute (“password");   用户用户=新用户();   如果(用户名!=null) {   user.setUsername (username.toString ());   }   如果(密码!=null) {   user.setPassword (password.toString ());   }   布尔verifyResult=this.staffService.verifyLoginUser(用户);   如果(字串!=零,,queryString.indexOf(“标签=process")比;1)| | verifyResult) {   ctx.setSendZuulResponse(真正);//对该请求进行路由   ctx.setResponseStatusCode (200);   ctx.set (“isSuccess",真);//设值,可以在多个过滤器时使用   返回null;   其他}{   ctx.setSendZuulResponse(假);//过滤该请求,不对其进行路由   ctx.setResponseStatusCode(401);//返回错误码,应该是401   ctx.setResponseBody(“会话的time");//返回错误内容   ctx.set (“isSuccess",假);   返回null;   }   }   }

这里还需要在启动类中注入这个类

@ bean   公共WebSecurityFilter accessFilter () {   返回新WebSecurityFilter ();   }

登陆的代码

主要就是把前端传来的用户名密码放到会话中,并进行校验。如果校验成功,返回登陆成功,否则,返回登陆失败。前端再根据登陆情况做路由跳转。

包com.controller;      @RestController   @RequestMapping (value=https://www.yisu.com/zixun//系统)   公共类SystemController JdkSerializationRedisSerializer延伸实现Serializable {      @ autowired   私人StaffService StaffService;      @PostMapping(“登录”)   公共ResponseEntity

spring-boot中登录过滤功能如何实现