一。思路

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数据库几种常用的索引类型使用介绍

    一.简介 MySQL目前主要有以下几种索引类型: 1.普通索引 2.唯一索引 3.主键索引 4.组合索引 5.全文索引 二.语句 1 2 CREATE TABLE table_name[col_nam ...

  2. SpringBoot从入门到放弃之配置Spring-Data-JPA自动建表

    pom文件配置引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...

  3. 从Spring Initializr开始

    出识springcloud我们这里需要建立两个项目 来感受下微服务 一.配置服务 1. Spring Initializr. 用idea自带的 Spring Initializr. 建立第一个项目 2 ...

  4. 虹软人脸识别——官方 Qt Demo 移植到 Linux

    一.前言 最近需要在 Linux 平台下开发一个人脸识别相关的应用,用到了虹软的人脸识别 SDK.之前在 Windows 平台用过,感觉不错,SDK 里面还带了 Demo 可以快速看到效果.打开 Li ...

  5. 傻瓜式教学--win10 + frp + rdpwrap + 阿里云服务器 --实现win10 多用户同时远程登录内网机

    概述: 使用win10 专业版 + frp + RDPwrap + 阿里云服务器 的组合实现win10 多用户同时远程登录内网机.使用frp 做内网穿透,将内网机的指定端口暴露在外网,通过ip+por ...

  6. java常用的格式化

    日常工作中,总会遇到一些格式化显示的需求,下面做一些简单的整理 JDK中java.text下提供了格式化常用的工具类,具体结构见下图 时间日期格式化 DateFormat 采用DateFormat.g ...

  7. centos下面基本的linux命令操作

    参考视频: 1.如何打开命令窗口 鼠标点击右键,选择open Terminal就可以打开命令行窗口了. 现在我们可以调整这个窗口的大小,增大窗口大小使用ctrl+shif+加号,缩小窗口ctrl+减号 ...

  8. Spring:一、基本模块思维导图

  9. TCP实战二(半连接队列、全连接队列)

    TCP实验一我们利用了tcpdump以及Wireshark对TCP三次握手.四次挥手.流量控制做了深入的分析,今天就让我们一同深入理解TCP三次握手中两个重要的结构:半连接队列.全连接队列. 参考文献 ...

  10. IDEA 使用jebel热部署插件启动失败

    在使用Jebel热部署插件开发springmvc时,启动会出现内存溢出错误.可在配置Tomcat时增加JVM参数解决. -Xms768m -Xmx768m -XX:PermSize=64M -XX:M ...