SpringBoot学习:整合shiro(rememberMe记住我功能)
项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821
首先在shiro配置类中注入rememberMe管理器
/**
* cookie对象;
* rememberMeCookie()方法是设置Cookie的生成模版,比如cookie的name,cookie的有效时间等等。
* @return
*/
@Bean
public SimpleCookie rememberMeCookie(){
//System.out.println("ShiroConfiguration.rememberMeCookie()");
//这个参数是cookie的名称,对应前端的checkbox的name = rememberMe
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
//<!-- 记住我cookie生效时间30天 ,单位秒;-->
simpleCookie.setMaxAge(259200);
return simpleCookie;
} /**
* cookie管理对象;
* rememberMeManager()方法是生成rememberMe管理器,而且要将这个rememberMe管理器设置到securityManager中
* @return
*/
@Bean
public CookieRememberMeManager rememberMeManager(){
//System.out.println("ShiroConfiguration.rememberMeManager()");
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
//rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)
cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
return cookieRememberMeManager;
} @Bean(name = "securityManager")
public DefaultWebSecurityManager defaultWebSecurityManager(MyShiroRealm realm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//设置realm
securityManager.setRealm(realm);
//用户授权/认证信息Cache, 采用EhCache缓存
securityManager.setCacheManager(getEhCacheManager());
//注入记住我管理器
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}
并且配置记住我或认证通过可以访问的地址
/**
* 加载ShiroFilter权限控制规则
*/
private void loadShiroFilterChain(ShiroFilterFactoryBean factoryBean) {
/**下面这些规则配置最好配置到配置文件中*/
Map<String, String> filterChainMap = new LinkedHashMap<String, String>();
//配置记住我或认证通过可以访问的地址
filterChainMap.put("/", "user");
/** authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器
* org.apache.shiro.web.filter.authc.FormAuthenticationFilter */
// anon:它对应的过滤器里面是空的,什么都没做,可以理解为不拦截
//authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问
filterChainMap.put("/permission/userInsert", "anon");
filterChainMap.put("/error", "anon");
filterChainMap.put("/tUser/insert","anon");
filterChainMap.put("/**", "authc"); factoryBean.setFilterChainDefinitionMap(filterChainMap);
}
login.jsp加上了记住我的input标签:
<body style="margin-left: 500px">
<h1 style="margin-left: 30px">登录页面----</h1>
<form action="<%=basePath%>/login" method="post">
用户名 : <input type="text" name="email" id="email"/><br>
密码: <input type="password" name="pswd" id="pswd"/><br>
验证码:<input type="text" name="gifCode" id="gifCode"/>
<img alt="验证码" src="<%=basePath%>gif/getGifCode"><br>
<input type="checkbox" name="rememberMe" />记住我<br>
<input style="margin-left: 100px" type="submit" value="登录"/><input style="left: 50px" onclick="register()" type="button" value="注册"/>
</form>
<h1 style="color: red">${message }</h1>
</body>
后台的登录处理方法参数用boolean类型接收,并且在得到身份验证Token时传入rememberMe参数
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(@Valid User user, BindingResult bindingResult,boolean rememberMe,
RedirectAttributes redirectAttributes){
if(bindingResult.hasErrors()){
return "redirect:login";
}
String email = user.getEmail();
if(StringUtils.isBlank(user.getEmail()) || StringUtils.isBlank(user.getPswd())){
logger.info("用户名或密码为空! ");
redirectAttributes.addFlashAttribute("message", "用户名或密码为空!");
return "redirect:login";
}
//对密码进行加密后验证
UsernamePasswordToken token = new UsernamePasswordToken(user.getEmail(),
CommonUtils.encrypt(user.getPswd()),rememberMe);
//获取当前的Subject
Subject currentUser = SecurityUtils.getSubject();
try {
//在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
//每个Realm都能在必要时对提交的AuthenticationTokens作出反应
//所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
logger.info("对用户[" + email + "]进行登录验证..验证开始");
currentUser.login(token);
logger.info("对用户[" + email + "]进行登录验证..验证通过");
}catch(UnknownAccountException uae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,未知账户");
redirectAttributes.addFlashAttribute("message", "未知账户");
}catch(IncorrectCredentialsException ice){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,错误的凭证");
redirectAttributes.addFlashAttribute("message", "密码不正确");
}catch(LockedAccountException lae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,账户已锁定");
redirectAttributes.addFlashAttribute("message", "账户已锁定");
}catch(ExcessiveAttemptsException eae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,错误次数大于5次,账户已锁定");
redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数大于5次,账户已锁定");
}catch (DisabledAccountException sae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,帐号已经禁止登录");
redirectAttributes.addFlashAttribute("message", "帐号已经禁止登录");
}catch(AuthenticationException ae){
//通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
logger.info("对用户[" + email + "]进行登录验证..验证未通过,堆栈轨迹如下");
ae.printStackTrace();
redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
}
//验证是否登录成功
if(currentUser.isAuthenticated()){
logger.info("用户[" + email + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
//把当前用户放入session
Session session = currentUser.getSession();
User tUser = permissionService.findByUserEmail(email);
session.setAttribute("currentUser",tUser);
return "/welcome";
}else{
token.clear();
return "redirect:login";
}
}
启动项目后,第一次输入http://localhost:8080/boot/后跳转到login登录页面,当登录成功后,关闭浏览器重新打开再输入地址后,不需要重新登录,直接跳转。
SpringBoot学习:整合shiro(rememberMe记住我功能)的更多相关文章
- SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)
首先在shiro配置类中注入rememberMe管理器 /** * cookie对象; * rememberMeCookie()方法是设置Cookie的生成模版,比如cookie的name,cooki ...
- SpringBoot:整合Shiro
目录 1.Shiro简介 1.1.什么是Shiro? 1.2.有哪些功能 1.3.Shiro架构(外部) 1.4.Shiro架构(内部) 2.HelloWorld 3.Shiro整合Spring Bo ...
- shiro中记住我功能
Shiro提供了记住我(RememberMe)的功能,比如访问如淘宝等一些网站时,关闭了浏览器下次再打开时还是能记住你是谁,下次访问时无需再登录即可访问,基本流程如下: 1.首先在登录页面选中Reme ...
- Spring 整合Shiro:记住我
1.登录方法 /** * 执行登录操作 * * @param username * @param password * @param rememberMe * @param model * @retu ...
- 在web项目中使用shiro(记住我功能)
第一步,添加“记住我”复选框,rememberMe要设置参数 第二步,配置shiro的主配置文件 注意 rememberMeCookie对应的bean中要声明 <constructor-arg ...
- SpringBoot学习- 8、整合Shiro
SpringBoot学习足迹 Shiro是什么,引自百度百科:Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码和会话管理.使用Shiro的易于理解的API,您可以快 ...
- SpringBoot 优雅的整合 Shiro
Apache Shiro是一个功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理.借助Shiro易于理解的API,您可以快速轻松地保护任何应用程序 - 从最小的移动应用程序到最 ...
- SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理(上)----筑基中期
写在前面 通过前几篇文章的学习,我们从大体上了解了shiro关于认证和授权方面的应用.在接下来的文章当中,我将通过一个demo,带领大家搭建一个SpringBoot整合Shiro的一个项目开发脚手架, ...
- SpringBoot学习:整合shiro(rememberMe记住我后自动登录session失效解决办法)
项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 定义一个拦截器,判断用户是通过记住我登录时,查询数据库后台自动登录,同时把用户放入ses ...
随机推荐
- HDU 1275 两车追及或相遇问题(相遇和追及公式)
传送门: http://acm.hdu.edu.cn/showproblem.php?pid=1275 两车追及或相遇问题 Time Limit: 2000/1000 MS (Java/Others) ...
- HTML5学习总结——相关练习与项目
一.小米商城项目 第一天示例代码: <!DOCTYPE html> <html lang="en"> <head> <meta chars ...
- MySql第几行到第几行语句
1.查询第一行记录: select * from table limit 1 2.查询第n行到第m行记录 select * from table1 limit n-1,m-n; SELECT * FR ...
- 【2017002】C#FTP上传文件
//上传文件 public static Boolean FtpUpload(string ftpPath, string localFile, FtpServer svr) { //检查目录是否存在 ...
- oracle表空间的创建+权限分配
/*分为四步 */ /*第1步:创建临时表空间 */ create temporary tablespace user_temp tempfile 'D:\oracle\oradata\Oracle9 ...
- phpStudy环境安装SSL证书教程(apache)
https://cloud.tencent.com/product/ssl 此链接是检测域名 证书的可以检测一下 下面是证书配置 小白呢亲测 作为PHP程序员,我们一定要学会使用phpStudy环境集 ...
- python人工智能爬虫系列:怎么查看python版本_电脑计算机编程入门教程自学
首发于:python人工智能爬虫系列:怎么查看python版本_电脑计算机编程入门教程自学 http://jianma123.com/viewthread.aardio?threadid=431 本文 ...
- WebGL学习笔记(1)
基本的WebGL图形操作(详细参考教程:https://www.yiibai.com/webgl,需要1周左右熟悉webgl的对象方法以及着色器代码):绘制三角形 drawElements gl.TR ...
- 『C++』Temp_2018_12_06
#include <iostream> #include <string> using namespace std; class Type{ public: string Na ...
- CentOS7 更换阿里云源
搭建opensack时原生的源不好使就换了个阿里云的源试试 百度搜到的方法:https://blog.csdn.net/chavo0/article/details/51939362 1.备份 # m ...