一。思路

1.在pom.xml导入相关包

2.先写个简单的认证适配器(WebSecurityConfig extends WebSecurityConfigurerAdapter),登录拦截后就会跳转到我们想要的页面,不然就会跳转到spring的登录页面

3.写个登录拦截器(LoginInterceptor implements HandlerInterceptor),在请求前(preHandle)根据登录时保存在session attribute里的值进行判断用户是否登录

4.写个拦截器配置(WebConfigurer implements WebMvcConfigurer),注入拦截器(LoginInterceptor ),在addInterceptors方法里进行配置拦截和不用拦截的方法

二。相关代码

1.认证适配器
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${app.basePath:}")
private String appBasePath; @Override
protected void configure(HttpSecurity http) throws Exception {
String basePath = StringUtils.trimToEmpty(appBasePath); http.authorizeRequests()
.anyRequest()
.permitAll(); http.formLogin()
.loginPage(basePath + "/console/login.html")
.defaultSuccessUrl(basePath + "/console/index.html", true)
.failureForwardUrl("/console/login.html?error=true")
.permitAll(); http.logout()
.logoutSuccessUrl(basePath + "/console/login.html")
.permitAll(); http.csrf()
.disable(); http.headers()
.frameOptions()
.disable();
}
} 2.登录拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
String currentAdminId = (String) session.getAttribute("CURRENT_ADMIN_ID");
if (StringUtils.isNotBlank(currentAdminId)) {
return true;
} else {
        //这里返回要加上全路径,不然会出现 重定向次数过多 的错
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/console/";
        response.sendRedirect(basePath+"login.html");
        return false;
        }
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }
} 3.拦截器配置
@Configuration
public class WebConfigurer implements WebMvcConfigurer { @Autowired
private LoginInterceptor loginInterceptor; /**
* 自定义资源拦截路径可以和springBoot默认的资源拦截一起使用,但是我们如果自己定义的路径与默认的拦截重复,那么我们该方法定义的就会覆盖默认配置
*
* @param registry
* @Return: void
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
} /**
* 添加拦截器
*
* @param registry
* @Return: void
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns("/**") 表示拦截所有的请求,
// excludePathPatterns("/login", "/register") 表示不拦截里面的方法
     //注意:这里如果不放开对image、js、css等静态文件的拦截的话,就会报 重定向次数过多 的错
registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/login", "/register", "/console/login.html","/console/conLogin.json","/console/login/captcha.png", "/static/**");
}
} 4.session操作
@UtilityClass
public class SessionTool { private static final String ADMIN_ID = "CURRENT_ADMIN_ID";
  /**
  * 获取当前请求
  *
  * @return 请求信息
  */
  public static HttpServletRequest getCurrentServletRequest() {
  RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
  ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
  return servletRequestAttributes.getRequest();
  }
    /**
* 获取当前用户id
*
* @param
* @Return: java.lang.String
*/
public static String getCurrentAdminId() {
HttpServletRequest servletRequest = getCurrentServletRequest();
        if (servletRequest != null) {
HttpSession session = servletRequest.getSession();
String code = (String) session.getAttribute(ADMIN_ID);
return code;
}
return null;
} /**
* 设置当前用户id
*
* @param code
* @Return: void
*/
public static void setCurrentAdminId(String code) {
HttpServletRequest servletRequest = getCurrentServletRequest();
if (servletRequest != null) {
HttpSession session = servletRequest.getSession();
session.setAttribute(ADMIN_ID, StringUtils.trimToNull(code));
}
} /**
* 移除当前用户id
*
* @param
* @Return: void
*/
public static void delCurrentAdminId() {
HttpServletRequest servletRequest = getCurrentServletRequest();
if (servletRequest != null) {
HttpSession session = servletRequest.getSession();
session.removeAttribute(ADMIN_ID);
}
} /**
* 判断当前用户id是否为空
*
* @param
* @Return: boolean
*/
public static boolean isSign() {
return StringUtils.isNotBlank(getCurrentAdminId());
}
} 参考文件
https://blog.csdn.net/u011972171/article/details/79924133
https://blog.csdn.net/weixin_42740540/article/details/88594441https://blog.csdn.net/weixin_42849689/article/details/89957823

spring boot实现简单的登录拦截的更多相关文章

  1. Spring Boot项目简单上手+swagger配置+项目发布(可能是史上最详细的)

    Spring Boot项目简单上手+swagger配置 1.项目实践 项目结构图 项目整体分为四部分:1.source code 2.sql-mapper 3.application.properti ...

  2. Spring boot 注解简单备忘

    Spring boot 注解简单备忘 1.定义注解 package com.space.aspect.anno;import java.lang.annotation.*; /** * 定义系统日志注 ...

  3. Spring Boot项目中如何定制拦截器

    本文首发于个人网站:Spring Boot项目中如何定制拦截器 Servlet 过滤器属于Servlet API,和Spring关系不大.除了使用过滤器包装web请求,Spring MVC还提供Han ...

  4. Spring Boot Mybatis简单使用

    Spring Boot Mybatis简单使用 步骤说明 build.gradle:依赖添加 application.properties:配置添加 代码编写 测试 build.gradle:依赖添加 ...

  5. spring boot(十四)shiro登录认证与权限管理

    这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求.在Java领域一般有Spring Security ...

  6. Spring Boot干货:静态资源和拦截器处理

    前言 本章我们来介绍下SpringBoot对静态资源的支持以及很重要的一个类WebMvcConfigurerAdapter. 正文 前面章节我们也有简单介绍过SpringBoot中对静态资源的默认支持 ...

  7. cas 3.5.3服务器搭建+spring boot集成+shiro模拟登录(不修改现有shiro认证架构)

    因为现有系统外部接入需要,需要支持三方单点登录.由于系统本身已经是微服务架构,由多个业务独立的子系统组成,所以有自己的用户认证微服务(不是cas,我们基础设施已经够多了,现在能不增加就不增加).但是因 ...

  8. Spring Boot 第六弹,拦截器如何配置,看这儿~

    持续原创输出,点击上方蓝字关注我吧 目录 前言 Spring Boot 版本 什么是拦截器? 如何自定义一个拦截器? 如何使其在Spring Boot中生效? 举个栗子 思路 根据什么判断这个接口已经 ...

  9. spring boot actuator 简单使用

    spring boot admin + spring boot actuator + erueka 微服务监控 简单的spring boot actuator 使用 POM <dependenc ...

随机推荐

  1. 从mysql数据库中查询最新的一条数据的方法

    第一种方法 SELECT * from a where id = (SELECT max(id) FROM a); 第二种方法: select * FROM 表名 ORDER BY id DESC L ...

  2. Android学习笔记Log类输出日志信息

    Log类提供的方法 代码示例 .. Log.e(TAG,"[错误信息]"); Log.w(TAG,"[警告信息]"); Log.i(TAG,"[普通信 ...

  3. 关于时间格式 GMT,UTC,CST,ISO

    GMT: 格林尼治所在地的标准时间 UTC: 协调世界时,又称世界统一时间.世界标准时间.国际协调时间.由于英文(CUT)和法文(TUC)的缩写不同,作为妥协,简称UTC. 协调世界时是以原子时秒长为 ...

  4. cc38b_demo_C++_异常_(2)txwtech在异常中使用虚函数-多态

    //cc38b_demo,21days_C++_异常_(2)txwtech20200121在异常中使用虚函数-多态 //--异常层次结构//*异常的类-创建自己的异常类//*异常派生-就是继承//*异 ...

  5. webpack简单笔记

    本文简单记录学习webpack3.0的笔记,已备日后查阅.节省查阅文档时间 安装 可以使用npm安装 //全局安装 npm install -g webpack //安装到项目目录 npm insta ...

  6. 吃货联盟订餐系统 源代码 Java初级小项目

    咳咳,今天博主给大家写一个小的项目:吃货联盟订餐系统.博主不是大神(互联网架构师的路上ing),也是小白一个,不过是刚入门的小白^_^.项目功能也很简单:只是模拟日常的订餐流程呦,所以有错误以及功能不 ...

  7. 处理TortoiseGit一直弹出密码框的方法 -输入git@XXXX.com的密码

    问题 :在push和pull的时候,一直都弹出这个框 1.开始处搜索TortoiseGit文件夹,找到其中的“PuTTYgen”文件,如下显示 2.运行之后在弹出的窗口中点击下方的“Generate” ...

  8. 史上最经典的git教程

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://wsyht90.blog.51cto.com/9014030/1832284 文档 ...

  9. vwware虚拟机网卡的三种模式

    这里在虚拟机中必须要保证右上角的两个勾选上 三种模式:简单一个比如宿主机器直接连接路由器上网,那虚拟机和宿主机器是一定的可以上外网,相当于虚拟机直接连接在路由器上面,虚拟机需要配置可以上外网的IP地址 ...

  10. disruptor架构三 使用场景 使用WorkHandler和BatchEventProcessor辅助创建消费者

    在helloWorld的实例中,我们创建Disruptor实例,然后调用getRingBuffer方法去获取RingBuffer,其实在很多时候,我们可以直接使用RingBuffer,以及其他的API ...