一、shiro认证
1、认证流程
2、实现方法
a、引入shiro需要的jar包shiro-code
b、构建securityManager
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(realm);//注入realm
c、主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);//初始化SecurityUtils
Subject subject=SecurityUtils.getSubject();//获取主体
UsernamePasswordToken token=new UsernamePasswordToken("admin","123");//创建token
subject.login(token);//登陆
subject.isAuthenticated();//是否认证
subject.logout();//登出
//初始化的时候添加用户进realm
SimpleAccountRealm realm=new SimpleAccountRealm();
realm.addAccount("admin", "123");
二、shiro授权
1、授权流程
2、实现方法
//在初始化添加用户进realm的时候把权限加进去
SimpleAccountRealm realm=new SimpleAccountRealm();
realm.addAccount("admin", "123","admin","user","test");//加入了"admin","user","test"三个权限,多个可追加
使用checkRole验证权限,没有匹配到权限的时候抛出异常
subject.checkRole("user")
//使用checkRoles一次性校验多个权限,有一个没有匹配上的时候抛出异常
subject.checkRoles("user","test","admin");
三、IniRealm
shiro内置了IniRealm和jdbcRealm
IniRealm的使用方式是创建一个.ini文件,通过读取.ini文件中的参数来进行权限管理
IniRealm realm=new IniRealm("classpath:user.ini");//通过读取文件来创建realm
xxx.ini文件配置:
[users]//标签是用户
admin=123,manager,test;//格式为用户等于密码,权限分组用逗号隔开,可设置多个权限
[roles]//权限管理
admin=user:query,user:update;//权限组对应的权限,多个权限之间逗号隔开
//通过checkPermission校验对应权限信息,没有该权限信息抛出异常
subject.checkPermission("user:query");``
四、jdbcRealm
1、通过com.alibaba.druid创建链接
JdbcRealm jdbcRealm=new JdbcRealm();//创建jdbcRealm
{
DruidDataSource dataSource=new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/test");//数据库链接
dataSource.setUsername("root");
dataSource.setPassword("root");
jdbcRealm.setDataSource(dataSource);
jdbcRealm.setPermissionsLookupEnabled(true);//设置激活权限查询,默认为false
}
2、查询授权和认证信息
jdbcRealm默认查询users表的username和password来授权
默认查询user_roles来获取权限信息
通过setAuthenticationQuery自定义查询授权信息
String sql="select password users where username=? ";
jdbcRealm.setAuthenticationQuery(sql);
通过setUserRolesQuery自定义查询权限信息
String roleSql="select roleName form user_role where username=? ";
jdbcRealm.setUserRolesQuery(roleSql);
五、自定义Realm
创建自定义realm继承AuthorizingRealm,实现doGetAuthorizationInfo(授权)和doGetAuthenticationInfo(认证)方法
认证(doGetAuthenticationInfo):
1、认证方法通过token.getPrincipal()获取用户名,通过用户名查询用户的凭据
2、返回SimpleAuthenticationInfo对象,包含其中的用户名、凭据和自定义realm名称
使用自定义realm对象和内置realm对象在使用方式上一致
授权(doGetAuthorizationInfo):
1、授权方法通过principals.getPrimaryPrincipal()获取用户名,通过用户名查询角色和权限信息
2、查询角色和权限信息放到对应Set集合
3、创建SimpleAuthorizationInfo对象设置角色和权限属性值并返回对象
六、shiro加密
使用HashedCredentialsMatcher 对象进行操作
HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
matcher.setHashAlgorithmName("md5");//加密名称
matcher.setHashIterations(1);//设置加密次数
realm.setCredentialsMatcher(matcher);//设置加密进自定义realm
加盐(sala)
在认证的时候对加密后的密文进行一次散列计算,减少密码被破译的可能
authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("sale"));//sale为盐的字符