刚开始学习springboot+shiro的安全登录
项目整合参考的http://412887952-qq-com.iteye.com/blog/2299777,是我目前所见写的最详细的一位大佬
把各种问题和经验记录下来,以备后面学习使用。
这些只是小弟初学shiro的一些粗浅的理解,有错误和不完整的地方希望大佬指正
因为项目用到了thymeleaf模板管理前台页面,但是在引用layui的时候一直引用不到,最终解决方法如下
在application.properties中增加标红的配置
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.content-type=text/html
spring.mvc.static-path-pattern=/static/**
重新梳理一下shiro各种配置
1.登录/注册时密码验证:
1.1 解密算法配置:在ShiroConfig中配置,这里的散列算法和散列次数要和注册时对应
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(1024);//散列的次数,比如散列两次,相当于 md5(md5(""));
return hashedCredentialsMatcher;
}
1.2在自己定义的ShiroRealm类,doGetAuthenticationInfo方法返回SimpleAuthenticationInfo对象,
shiro会帮我们用SimpleAuthenticationInfo对象进行登录验证
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userInfo, //用户
userInfo.getPassword(), //密码
//盐值
//如果注册时加盐加密了,这里需要将盐值传入
//shiro根据盐值进行密码解密,然后与页面输入的密码匹配
//getCredentialsSalt获取username+salt,我注册时将username+salt作为真正的盐值
//如果注册时只用salt的话,这里就直接获取userinfo的salt就行
ByteSource.Util.bytes(userInfo.getCredentialsSalt()),
getName() //realm name
);
1.3.shiro注册,这里的密码加密配置和1.1中的配置对应即可
@RequestMapping("/register")
public String register(UserInfo user) {
String username=user.getUsername();
String password1=user.getPassword();
//这里是获取加密时的盐值,我这里将用户名作为盐值,最好使用随机数
ByteSource salt = ByteSource.Util.bytes(username);
//使用username+salt作为真正的盐值,也可以只用salt;1024是加密次数,暂时不知道具体细节,与解密配置对应就行
String password = new SimpleHash("MD5", password1,username+salt,1024).toString();
//这里只将salt放入数据库中,解密时获取username+salt
user.setSalt(salt.toString());
user.setPassword(password);
byte by=1;
user.setState(by);
dao.save(user);
return "login";
}
2.权限管理
2.1在ShiroConfig中注入权限管理的Bean
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
2.2然后在shiroRealm中获取用户权限交给shiro进行控制
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal();
for(SysRole role:userInfo.getRoleList()){
authorizationInfo.addRole(role.getRole());
for(SysPermission p:role.getPermissions()){
authorizationInfo.addStringPermission(p.getPermission());
}
}
return authorizationInfo;
}
具体流程大致是,根据用户与角色对照表获取角色-->根据角色与资源对照表获取资源-->交给shiro判断用户是否有权限访问该资源
表结构如下
用户表
用户与角色对照表
角色表
角色与资源对照表
资源表
接上大佬写的教程,基本就可以正常进行安全登录和权限的控制了
这些只是小弟初学shiro的一些粗浅的理解,有错误和不完整的地方希望大佬指正