spring boot实现简单的登录拦截
2024-08-26 08:14:34
一。思路
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
最新文章
- java内存模型(待完善)
- Linux 设置定时任务crontab命令
- svn: Can't convert string from 'UTF-8' to native encoding 的解决办法(转)
- java实现文件单词频率统计 topN top K
- git 教程(10)--添加远程库
- 【Python学习笔记】集合
- NetBeans中文乱码解决办法
- js入门——Dom基础
- 动画云创始人胥克谦&;amp;课程格子创始人李天放分享创业经历
- SPOJ - BITDIFF: Bit Difference [神妙の预处理]
- Android 开发笔记___Activity的生命周期
- 【记录】.net 通用log4net日志配置
- C#多线程编程序--聊聊线程
- javascript排序、功能代码总结[长期更新]
- View,ViewGroup的Touch事件的分发机制
- Restful 接口开发 完整版
- java中 &; ^ ~ 的运算
- js入门关于js‘i++’‘++i’和‘i--’‘--i’计算的问题
- 潭州课堂25班:Ph201805201 django 项目 第三十四课 后台文章标签更新功能 ,创建功能实现(课堂笔记)
- 宿主机系统 Deepin 15.4,解决 Virtualbox 5.1 中 XP虚拟机无法使用 USB设备(如:U盘、罗技优联接收器等)的问题