shiro与spring集成基础Hello案例详解
这篇文章主要介绍了shiro与spring集成基础Hello案例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
shiro的四大基石
- 身份验证(登录)Authentication:身份认证/登录,验证用户是不是拥有相应的身份;
 - 授权(权限)Authorization:验证某个已登录的用户是否拥有某个权限
 - 密码学(密码加密)Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
 - 会话管理SessionManagement:用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;
 
导包
org.apache.shiro shiro-core 1.4.0 commons-logging commons-logging 1.2 junit junit 4.9 
ini文件(再创建shiro.ini文件)文件中有咱们的用户角色权限
#ini文件里面放的就是咱们的用户,角色,权限,资源 #----------------------------------------------------------------------------- #users:用户 #root:用户名123456:密码admin:角色 #----------------------------------------------------------------------------- [users] root=123456,admin guest=guest,it #----------------------------------------------------------------------------- #roles:角色 #admin=*:admin这个用户拥有所有权限 #it=employee:*:it这个角色拥有员工的所有权限 #hr=employee:save:hr这个角色拥有员工添加权限 #----------------------------------------------------------------------------- [roles] admin=* it=employee:* hr=employee:save
功能测试(一定要有测试包org.junit.Test才能测试)
主要测试登录,权限认证
@Test
publicvoidtestHello()throwsException{
//①.拿到权限管理对象
/**
*读取了shiro.ini的文件(隐藏了realm)->隐藏了iniRealm
*SecurityManager:权限管理器,shiro的所有功能都放在里面
*/
Factoryfactory=newIniSecurityManagerFactory("classpath:shiro.ini");
SecurityManagersecurityManager=factory.getInstance();
//②.相当于把SecurityManager放到了当前上下文
/**
*可以让我们在当前系统的任何位置都可以拿到SecurityManager对象
*/
SecurityUtils.setSecurityManager(securityManager);
//③.拿到当前用户(没有登录就是游客)
SubjectcurrentUser=SecurityUtils.getSubject();
System.out.println("用户是否登录:"+currentUser.isAuthenticated());
//④.如果没有登录,让他进行登录
if(!currentUser.isAuthenticated()){
//ctrl+alt+t:包含代码
try{
//4.1准备令牌(对象)用户名密码令牌
UsernamePasswordTokentoken=newUsernamePasswordToken("guest","guest");
//4.2进行登录功能
currentUser.login(token);
}catch(UnknownAccountExceptione){
//Unknown(未知)Account(账号)Exception:用户名不存在
e.printStackTrace();
System.out.println("哥,你是傻子嘛?");
}catch(IncorrectCredentialsExceptione){
//Incorrect(不正确)Credentials(凭证)Exception:密码错误
e.printStackTrace();
System.out.println("哥,密码错误了?");
}catch(AuthenticationExceptione){
//AuthenticationException:登录中最大的那个异常
e.printStackTrace();
System.out.println("发生了一个神秘的错误!!!");
}
}
System.out.println("用户是否登录:"+currentUser.isAuthenticated());
System.out.println("是否是管理员角色:"+currentUser.hasRole("admin"));
System.out.println("是否是IT角色:"+currentUser.hasRole("it"));
System.out.println("是否可以操作employee:save权限:"+currentUser.isPermitted("employee:save"));
System.out.println("是否可以操作employee:index权限:"+currentUser.isPermitted("employee:index"));
System.out.println("是否可以操作department:index权限:"+currentUser.isPermitted("department:index"));
//⑤.还可以登出(注销)
currentUser.logout();
System.out.println("用户是否登录:"+currentUser.isAuthenticated());
} 
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。