当前位置: 首页 > news >正文

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;}
}
http://www.lryc.cn/news/405400.html

相关文章:

  • 【linux驱动开发】卸载驱动时报错:Trying to free already-free IRQ 0
  • SpringBoot如何解决yml明文密码问题
  • SDL常用结构体和函数接口
  • 【数据结构】AVL树(图文解析 + 代码实现)
  • HTML(六)——HTML表单和框架
  • 【Qt 】JSON 数据格式详解
  • 路由表与IP数据报转发:基础小白指南
  • python—selenium爬虫
  • Mysql - 索引
  • 从课本上面开始学习的51单片机究竟有什么特点,在现在的市场上还有应用吗?
  • uniapp中出现Uncaught runtime errors
  • 数字信号处理基础知识(二)
  • 人生低谷来撸C#--015 C# 属性(Property)
  • 面试题003:面向对象的特征——封装性
  • 森林防火,森林防火智能储水罐_鼎跃安全
  • 虚幻引擎,体积雾、体积光、镜头泛光
  • Python 机器学习求解 PDE 学习项目——PINN 求解二维 Poisson 方程
  • 微信小程序删除滑块 SwiperCell 自动收起 Van weapp van-swipe-cell 滑块自动收起 点击页面也自动收起滑块
  • 【vluhub】log4j注入漏洞 CVE-2021-44228
  • Redis核心技术与实战学习笔记
  • 力扣经典题目之->设计循环队列 的超详细讲解与实现
  • 【数据结构】排序算法——Lesson2
  • Ubuntu编译ffmpeg并添加cmake工程
  • Vue.js[组件(Component)]
  • 基于微信小程序+SpringBoot+Vue的校园自助打印系统(带1w+文档)
  • qt设置过滤器
  • 线上环境服务器CPU飙升排查
  • unity文字||图片模糊
  • 香薰学习笔记
  • iOS ------ weak的基本原理