软件编程
位置:首页>> 软件编程>> java编程>> Springboot中登录后关于cookie和session拦截问题的案例分析

Springboot中登录后关于cookie和session拦截问题的案例分析

作者:幸子在神奈川  发布时间:2022-09-25 19:26:44 

标签:Springboot,登录,cookie,session,拦截

一、前言

1、简单的登录验证可以通过Session或者Cookie实现。
2、每次登录的时候都要进数据库校验下账户名和密码,只是加了cookie 或session验证后;比如登录页面A,登录成功后进入页面B,若此时cookie过期,在页面B中新的请求url到页面c,系统会让它回到初始的登录页面。(类似单点登录sso(single sign on))。
3、另外,无论基于Session还是Cookie的登录验证,都需要对HandlerInteceptor进行配置,增加对URL的拦截过滤机制。

二、利用Cookie进行登录验证

1、配置 * 代码如下:


public class CookiendSessionInterceptor implements HandlerInterceptor {  

@Override  
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
 log.debug("进入 * ");  
 Cookie[] cookies = request.getCookies();  
 if(cookies!=null && cookies.length>0){    
  for(Cookie cookie:cookies) {    
    log.debug("cookie===for遍历"+cookie.getName());    
    if (StringUtils.equalsIgnoreCase(cookie.getName(), "isLogin")) {      
     log.debug("有cookie ---isLogin,并且cookie还没过期...");      
     //遍历cookie如果找到登录状态则返回true继续执行原来请求url到controller中的方法      
     return true;    
       }    
     }  
    }  
  log.debug("没有cookie-----cookie时间可能到期,重定向到登录页面后请重新登录。。。");  
  response.sendRedirect("index.html");  
  //返回false,不执行原来controller的方法  
  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 {
 }

}

2、在Springboot中拦截的请求不管是配置 * (定义一个类实现一个接口HttpSessionListener )、过滤器、 * ,都要配置如下此类实现一个接口中的两个方法。
代码如下:


@Configuration
public class WebConfig implements WebMvcConfigurer {  
// 这个方法是用来配置静态资源的,比如html,js,css,等等  
@Override  
public void addResourceHandlers(ResourceHandlerRegistry registry) {
}

// 这个方法用来注册 * ,我们自己写好的 * 需要通过这里添加注册才能生效
@Override  
public void addInterceptors(InterceptorRegistry registry) {  
//addPathPatterns("/**") 表示拦截所有的请求  
//excludePathPatterns("/firstLogin","/zhuce");设置白名单,就是 * 不拦截。首次输入账号密码登录和注册不用拦截!  
//登录页面在 * 配置中配置的是排除路径,可以看到即使放行了,还是会进入prehandle,但是不会执行任何操作。  
registry.addInterceptor(new CookiendSessionInterceptor()).addPathPatterns("/**").excludePathPatterns("/",          
                         "/**/login",          
                         "/**/*.html",          
                         "/**/*.js",          
                         "/**/*.css",          
                         "/**/*.jpg");
}

}

3.前台登录页面index.html(我把这个html放在静态资源了,也让 * 放行了此路由url)
前端测试就是一个简单的form表单提交


<!--测试cookie和sessionid-->
<form action="/login" method="post">  
账号:<input type="text" name="name1" placeholder="请输入账号"><br>  
密码:<input type="password" name="pass1" placeholder="请输入密码"><br>  
<input type="submit" value="登录">
</form>

4、后台控制层Controller业务逻辑:登录页面index.html,登录成功后 loginSuccess.html。
在loginSuccess.html中可提交表单进入次页demo.html,也可点击“退出登录”后台清除没有超时的cookie,并且回到初始登录页面。


@Controller
@Slf4j
@RequestMapping(value = "/")
public class TestCookieAndSessionController {  
@Autowired  JdbcTemplate jdbcTemplate;  
/**  * 首次登录,输入账号和密码,数据库验证无误后,响应返回你设置的cookie。再次输入账号密码登录或者首次登录后再请求下一个页面,就会在请求头中携带cookie,  * 前提是cookie没有过期。  * 此url请求方法不管是首次登录还是第n次登录, * 都不会拦截。  * 但是每次(首次或者第N次)登录都要进行,数据库查询验证账号和密码。  * 做这个目的是如果登录页面A,登录成功后进页面B,页面B有链接进页面C,如果cookie超时,重新回到登录页面A。(类似单点登录)  */  

@PostMapping(value = "login")  
public String test(HttpServletRequest request, HttpServletResponse response, @RequestParam("name1")String name,@RequestParam("pass1")String pass) throws Exception{  
try {    
Map<String, Object> result= jdbcTemplate.queryForMap("select * from userinfo where name=? and password=?", new Object[]{name, pass});    
 if(result==null || result.size()==0){    
  log.debug("账号或者密码不正确或者此人账号没有注册");    
  throw new Exception("账号或者密码不正确或者此人账号没有注册!");    
 }else{    
  log.debug("查询满足条数----"+result);    
  Cookie cookie = new Cookie("isLogin", "success");    
  cookie.setMaxAge(30);    
  cookie.setPath("/");    
  response.addCookie(cookie);    
  request.setAttribute("isLogin", name);    
  log.debug("首次登录,查询数据库用户名和密码无误,登录成功,设置cookie成功");    
  return "loginSuccess";    }  
} catch (DataAccessException e) {    
  e.printStackTrace();    
  return "error1";  
 }
}

/**测试登录成功后页面loginSuccess ,进入次页demo.html*/  
@PostMapping(value = "sub")  
public String test() throws Exception{  
return "demo";  
}  
/** 能进到此方法中,cookie一定没有过期。因为 * 在前面已经判断力。过期, * 重定向到登录页面。过期退出登录,清空cookie。*/
@RequestMapping(value = "exit",method = RequestMethod.POST)  
public String exit(HttpServletRequest request,HttpServletResponse response) throws Exception{  
Cookie[] cookies = request.getCookies();  
for(Cookie cookie:cookies){  
if("isLogin".equalsIgnoreCase(cookie.getName())){    
 log.debug("退出登录时,cookie还没过期,清空cookie");    
 cookie.setMaxAge(0);    
 cookie.setValue(null);    
 cookie.setPath("/");    
 response.addCookie(cookie);    
 break;    
 }  
 }  
//重定向到登录页面  
return "redirect:index.html";  
 }

}

5、效果演示:
①在登录“localhost:8082”输入账号登录页面登录:

Springboot中登录后关于cookie和session拦截问题的案例分析

② * 我设置了放行/login,所以请求直接进Controller相应的方法中:
日志信息如下:

Springboot中登录后关于cookie和session拦截问题的案例分析

下图可以看出,浏览器有些自带的不止一个cookie,这里不要管它们。

Springboot中登录后关于cookie和session拦截问题的案例分析

③在loginSuccess.html,进入次页demo.html。cookie没有过期顺利进入demo.html,并且/sub方法经过 * (此请求请求头中携带cookie)。
过期的话直接回到登录页面(这里不展示了)

Springboot中登录后关于cookie和session拦截问题的案例分析

④在loginSuccess.html点击“退出登录”,后台清除我设置的没过期的cookie=isLogin,回到登录页面。

三、利用Session进行登录验证

1、修改 * 配置略微修改下:

Springboot中登录后关于cookie和session拦截问题的案例分析

Interceptor也略微修改下:还是上面的preHandle方法中:

Springboot中登录后关于cookie和session拦截问题的案例分析

2.核心
前端我就不展示了,就是一个form表单action="login1"
后台代码如下:


/**利用session进行登录验证*/
@RequestMapping(value = "login1",method = RequestMethod.POST)  
public String testSession(HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam("name1")String name,      
      @RequestParam("pass1")String pass) throws Exception{  
try {  
Map<String, Object> result= jdbcTemplate.queryForMap("select * from userinfo where name=? and password=?", new Object[]{name, pass});    
 if(result!=null && result.size()>0){    
 String requestURI = request.getRequestURI();    
 log.debug("此次请求的url:{}",requestURI);    
 HttpSession session = request.getSession();    
 log.debug("session="+session+"session.getId()="+session.getId()+"session.getMaxInactiveInterval()="+session.getMaxInactiveInterval());    
 session.setAttribute("isLogin1", "true1");    
 }  
} catch (DataAccessException e) {    
 e.printStackTrace();  
 return "error1";  
}  
return "loginSuccess";
}

//登出,移除登录状态并重定向的登录页  
@RequestMapping(value = "/exit1", method = RequestMethod.POST)  
public String loginOut(HttpServletRequest request) {  
request.getSession().removeAttribute("isLogin1");  
log.debug("进入exit1方法,移除isLogin1");  
return "redirect:index.html";  
}
}

日志如下:可以看见springboot内置的tomcat中sessionid就是请求头中的jsessionid,而且默认时间1800秒(30分钟)。
我也不清楚什么进入 * 2次,因为我login1设置放行了,肯定不会进入 * 。可能是什么静态别的什么资源吧。

Springboot中登录后关于cookie和session拦截问题的案例分析

session.getId()=F88CF6850CD575DFB3560C3AA7BEC89F==下图的JSESSIONID

Springboot中登录后关于cookie和session拦截问题的案例分析

//点击退出登录,请求退出url的请求头还是携带JSESSIONID,除非浏览器关掉才消失。(该session设置的属性isLogin1移除了,session在不关浏览器情况下或者超过默认时间30分钟后,session才会自动清除!)

Springboot中登录后关于cookie和session拦截问题的案例分析

Springboot中登录后关于cookie和session拦截问题的案例分析

四、完结

来源:https://www.cnblogs.com/tenghw/p/13557327.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com