一。思路

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. 面试必问:分布式锁实现之zk(Zookeeper)

    点赞再看,养成习惯,微信搜索[三太子敖丙]关注这个互联网苟且偷生的工具人. 本文 GitHub https://github.com/JavaFamily 已收录,有一线大厂面试完整考点.资料以及我的 ...

  2. opencv3.1.0 计算机中丢失 opencv_world310d.dll _vs2017解决方法

    ---------------------------opencv1.exe - 系统错误---------------------------无法启动此程序,因为计算机中丢失 opencv_worl ...

  3. Python 网络爬虫实战:爬取 B站《全职高手》20万条评论数据

    本周我们的目标是:B站(哔哩哔哩弹幕网 https://www.bilibili.com )视频评论数据. 我们都知道,B站有很多号称“镇站之宝”的视频,拥有着数量极其恐怖的评论和弹幕.所以这次我们的 ...

  4. 13.DRF-版本

    Django rest framework源码分析(4)----版本 版本 新建一个工程Myproject和一个app名为api (1)api/models.py from django.db imp ...

  5. Perl入门(四)Perl的正则表达式

    正则表达式是Perl语言的特色,基本的语法不是很难,但是编写一个符合需求.高效的正则表达式,还是有一些挑战的. Perl的三种匹配模式 1.查找 语法:m/正则表达式内容/; 作用:查找匹配内容中是否 ...

  6. PHP字符串函数总结

    字符串函数 addcslashes — 为字符串里面的部分字符添加反斜线转义字符 addslashes — 用指定的方式对字符串里面的字符进行转义 bin2hex — 将二进制数据转换成十六进制表示 ...

  7. shell把字符串中的字母去掉,只保留数字

    1 编辑测试文件 [root@hz-kvm cephdisk3]# cat > 1.txt <<EOF> 120Tib> EOF 2 显示文件[root@hz-kvm c ...

  8. 如何判断一个String字符串不为空或这不为空字符串

    如何判断一个String字符串不为空或这不为空字符串 转载兵哥LOVE坤 最后发布于2018-07-27 00:00:05 阅读数 5144  收藏 展开 1.校验不为空:   String str ...

  9. 为什么 group by后面 必须跟selecte 后面的除了聚集函数外的所有字段

    如:SELECT store_name, SUM(Sales) FROM Store_Information GROUP BY store_name 可以而SELECT store_name, add ...

  10. ASP.NET MVC 四种Controller向View传值方法

    控制器: // Get: Data public ActionResult Index() { //ViewData 方式 ViewData["UserName"] = " ...