一。思路

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. TensorFlow从0到1之浅谈深度学习(10)

    DNN(深度神经网络算法)现在是AI社区的流行词.最近,DNN 在许多数据科学竞赛/Kaggle 竞赛中获得了多次冠军. 自从 1962 年 Rosenblat 提出感知机(Perceptron)以来 ...

  2. python反向遍历一个可迭代对象

    我们通常情况下都是正向遍历一个列表,下面是一种简单的反向遍历一个列表的方式. ## 正向遍历 >>>A = [9, 8, 7] >>>for index, a in ...

  3. Day7-微信小程序实战-引入iconfont(充分利用iconfont图标库的资源)

    一.引入iconfont 首先在iconfont.com中注册登陆: 点击上方[图标管理]并进入我的项目 注意:如果没有项目的话,就点击右边的来创建项目 在官网中找到想要的图标之后,以SVG的形式下载 ...

  4. MySQL语句的使用

    进入数据库  mysql -u root -pmysql    (u用户名,p密码)#如果不想让其他人看到就直接一个p然后回车再打密码 select version();   查看数据库版本 sele ...

  5. Jmeter系列(30)- 详解 JDBC Request

    如果你想从头学习Jmeter,可以看看这个系列的文章哦 https://www.cnblogs.com/poloyy/category/1746599.html 前言 JDBC Request 主要是 ...

  6. IDEA解决SVN频繁弹出登录框

    将HTTP请求改成SVN就可以了,或者请项目经理开启SVN中的HTTP请求

  7. Git报错信息

    1. 解决办法: 当在最后提交的时候,出现的错误. 解决办法: git remote rm origin 执行下面代码: git remote add origin https://github.co ...

  8. HDU 5969 最大的位或【贪心】

    题目 B君和G君聊天的时候想到了如下的问题. 给定自然数l和r ,选取2个整数x,y满足l <= x <= y <= r ,使得x|y最大. 其中|表示按位或,即C. C++. Ja ...

  9. linux就该这么学 第一天学习笔记

    题外话 在每天的网上冲浪中,一次无意间的点击,发现了linux就该这么学的网站,然后就看了一晚上,当时还是学生的我特别想要参加培训,可是碍于眼前的经济状况,只得将这个想法深深的藏在了心里,并加了一下网 ...

  10. 【FastDFS】如何打造一款高可用的分布式文件系统?这次我明白了!!

    写在前面 前面我们学习了如何基于两台服务器搭建FastDFS环境,而往往在生产环境中,需要FastDFS做到高可用,那如何基于FastDFS打造一款高可用的分布式文件系统呢?别急,今天,我们就一起来基 ...