spring boot实现简单的登录拦截

一。思路

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")
// .usernameParameter("loginName")
// .passwordParameter("loginPassword")
// .loginProcessingUrl("/console/conLogin.json")
.defaultSuccessUrl(basePath + "/console/index.html", true)
.failureForwardUrl("/console/login.html?error=true")
.permitAll();

http.logout()
// .logoutUrl("/console/out-login.json")
.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 {
response.sendRedirect("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/88594441
https://blog.csdn.net/weixin_42849689/article/details/89957823

猜你喜欢

转载自www.cnblogs.com/GGDong/p/12980703.html