中间件学习-shiro实现认证与授权
本文代码已上传到github上
https://github.com/Robert-plus/shiro-demo
本文原文请访问
https://blog.csdn.net/bbxylqf126com/article/details/110501155
认证
最简单理解就是通过用户名与密码进行登录
授权
就是根据角色[role]与权限[permission]对访问的资源与内容进行控制
shiro简介
Apache Shiro™ 是一个功能强大且易于使用的Java安全框架,可执行身份验证、授权、加密和会话管理。借助Shiro易于理解的API,您可以快速轻松地保护任何应用程序—从最小的移动应用程序到最大的web和企业应用程序
三大核心
Subject
SecurityManager
Realm
@Configuration
public class ShiroConfiguration {
//1.创建shiroFilter //负责拦截所有请求
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//给filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//配置系统受限资源
//配置系统公共资源
Map<String,String> map = new HashMap<String,String>();
// anon 设置为公共资源,放行要注意anon和authc的顺序
map.put("/user/register","anon");
map.put("/register.jsp","anon");
map.put("/user/login","anon"); // anon 设置为公共资源,放行要注意anon和authc的顺序
map.put("/index.jsp","authc"); //authc 请求这个资源需要认证和授权
//默认认证界面路径
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
//2.创建安全管理器
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getRealm") Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//给安全管理器设置
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
//3.创建自定义realm
@Bean
public Realm getRealm(){
CustomerRealm customerRealm = new CustomerRealm();
// 设置密码匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
// 设置加密方式
credentialsMatcher.setHashAlgorithmName(ShiroConstant.HASH_ALGORITHM_NAME.MD5);
// 设置散列次数
credentialsMatcher.setHashIterations(ShiroConstant.HASH_ITERATORS);
customerRealm.setCredentialsMatcher(credentialsMatcher);
return customerRealm;
}
}
通过配置类将三大组件注入使用
shiro简单部署
由于代码量整体偏多,上传到了github上
https://github.com/Robert-plus/shiro-demo
mysql版本较新,使用cj新驱动路径;数据库名shiro;将执行sql文件创建表和插入数据
运行程序,访问localhost:8888/index.jsp
shiro代码
访问localhost:8888/index.jsp会自动重定向到访问localhost:8888/login.jsp
这是由于在shiroFilterFactoryBean中配置了index需要authc
输入第一个用户名密码,christy,123456
显示全部内容
输入第二个用户名密码,tom,123456
显示部分内容
这是由于在index.jsp中<shiro:hasPermission >以及 <shiro:hasAnyRole >等标签的配置
转载于
https://blog.csdn.net/bbxylqf126com/article/details/110501155
更多请访问原文