java30-Shiro
概述
解决认证和授权
基本使用
package com.xpc.simple;import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;public class Demo1 {@Testpublic void authen(){// 认证的发起者 SecurityManager Realm// 1.准备RealmSimpleAccountRealm realm = new SimpleAccountRealm();realm.addAccount("admin","password","超级管理员","商家");// 2.准备SecurityManagerDefaultSecurityManager manager = new DefaultSecurityManager();// 3.SecurityManager和Realm准备建立链接manager.setRealm(realm);// 4.subject和SecurityManager准备建立链接SecurityUtils.setSecurityManager(manager);// 5.声明subjectSubject subject = SecurityUtils.getSubject();// 6.发起认证subject.login(new UsernamePasswordToken("admin","password"));// 7.判断是否认证成功System.out.println(subject.isAuthenticated());// 8.退出登录
// subject.logout();// 9.授权是认证成功后的操作System.out.println(subject.hasRole("超级管理员"));subject.checkRole("管理员");}
}
基于IniRealm
准备一个.ini文件存储信息
[users]
# 用户名=密码
username=password,role1,role2
admin=admin,超级管理员,运营
[roles]
超级管理员=user:add,user:delete,user:update,user:query
package com.xpc.ini;import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;public class Demo1 {@Testpublic void test(){// 1.构建IniRealmIniRealm iniRealm = new IniRealm("classpath:shrio.ini");// 2.构建SecurityManager绑定RealmDefaultSecurityManager manager = new DefaultSecurityManager();manager.setRealm(iniRealm);// 3.基于SecurityUtils绑定SecurityManager并声明subjectSecurityUtils.setSecurityManager(manager);Subject subject = SecurityUtils.getSubject();// 4.认证操作subject.login(new UsernamePasswordToken("admin","admin"));// 5.角色校验System.out.println(subject.hasRole("超级管理员"));subject.checkRole("运营");// 6.权限校验subject.checkPermission("user:select");}
}
CustomRealm(自定义Realm)
package com.xpc.realm;import com.alibaba.druid.util.StringUtils;
import com.xpc.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;import java.util.HashSet;
import java.util.Set;public class CustomRealm extends AuthorizingRealm {{HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();matcher.setHashAlgorithmName("MD5");matcher.setHashIterations(1024);this.setCredentialsMatcher(matcher);}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {// 基于token获取用户名String username = (String) authenticationToken.getPrincipal();// 判断用户名非空if(StringUtils.isEmpty(username)){return null;}// 如果用户名不为null 基于用户名查询数据User user = this.findUserByUsername(username);// 判断用户是否正确if(null == user){return null;}// 声明AuthenticationInfo 并填充信息SimpleAuthenticationInfo customRealmInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "CustomRealm");// 设置盐customRealmInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));// 返回信息return customRealmInfo;}@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {// 获取用户认证信息User user = (User) principalCollection.getPrimaryPrincipal();// 基于用户信息获取当前用户拥有的角色Set<String> set = this.findRolesByUser();// 基于用户信息获取当前角色拥有的权限Set<String> roleSet = this.findPermsByRoleSet();// 传入角色和权限信息SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();info.setRoles(set);info.setStringPermissions(roleSet);// 返回return info;}private User findUserByUsername(String username){if("admin".equals(username)){User user = new User();user.setUsername("admin");user.setId(1);user.setPassword("6f9a73ae2e0fb82d1d171bd11bdccc97");user.setSalt("sdwefdsfasd");return user;}return null;}private Set<String> findRolesByUser(){Set<String> set = new HashSet<>();set.add("超级管理员");set.add("运营");return set;}private Set<String> findPermsByRoleSet(){Set<String> set = new HashSet<>();set.add("user:add");set.add("user:select");return set;}
}
自定义过滤器
package fileter;import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;public class RolesFileter extends AuthenticationFilter {@Overrideprotected boolean isAccessAllowed(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, Object mappedValue) {// 获取字体subjectSubject subject = getSubject(request, response);// 将传入角色转化为数组String [] roles = (String []) mappedValue;// 健壮性校验if(roles == null || roles.length == 0){return true;}// 开始校验for (String role : roles) {if(subject.hasRole(role)){return true;}}return false;}
}