Apache 的安全框架
Apache Shiro是一个Java的安全管理框架,可以用在JavaEE环境下,也可以用在JavaSE环境下。
此前我们学习了很多有关阿帕奇的东西:maven,tomcat,等等
他能做什么? shiro架构官方号称十分钟就可以入门:Apache Shiro | Simple. Java. Security.
gti地址: GitHub - apache/shiro: Apache Shiro
二:快速开始(传送门中内容)1,引入依赖
org.apache.shiro shiro-core1.6.0 org.slf4j jcl-over-slf4j1.7.21 org.slf4j slf4j-log4j121.7.21 log4j log4j1.2.17 com.github.theborakompanioni thymeleaf-extras-shiro2.0.0
2,QuickStart.java
import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.config.IniSecurityManagerFactory; //import org.apache.shiro.ini.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; //import org.apache.shiro.lang.util.Factory; import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class QuickStart { private static final transient Logger log = LoggerFactory.getLogger(QuickStart.class); public static void main(String[] args) { //固定代码 Factoryfactory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance();//三大核心对象之二 SecurityUtils.setSecurityManager(securityManager); // get the currently executing user: //获取当前的用户对象 三大核心对象之一 Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) //通过当前用户拿到session Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); } // 判断当前用户是否被认证 if (!currentUser.isAuthenticated()) { //UsernamePasswordToken令牌 通过当前用户的账号密码生成的令牌 UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true);//设置记住我 try { currentUser.login(token);//执行登录 *** 作 } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... catch more exceptions here (maybe custom ones specific to your application? catch (AuthenticationException ae) { //unexpected condition? error? } } //say who they are: //print their identifying principal (in this case, a username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) 粗粒度 if (currentUser.isPermitted("lightsaber:wield")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: 细粒度 if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! 注销 currentUser.logout(); System.exit(0); } }
shiro.ini
[users] # user 'root' with password 'secret' and the 'admin' role root = secret, admin # user 'guest' with the password 'guest' and the 'guest' role guest = guest, guest # user 'presidentskroob' with password '12345' ("That's the same combination on # my luggage!!!" ;)), and role 'president' presidentskroob = 12345, president # user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz' darkhelmet = ludicrousspeed, darklord, schwartz # user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz' lonestarr = vespa, goodguy, schwartz # ----------------------------------------------------------------------------- # Roles with assigned permissions # # Each line conforms to the format defined in the # org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc # ----------------------------------------------------------------------------- [roles] # 'admin' role has all permissions, indicated by the wildcard '*' admin = * # The 'schwartz' role can do anything (*) with any lightsaber: schwartz = lightsaber:* # The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with # license plate 'eagle5' (instance specific id) goodguy = winnebago:drive:eagle5
shiro的配置文件
log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n # General Apache libraries log4j.logger.org.apache=WARN # Spring log4j.logger.org.springframework=WARN # Default Shiro logging log4j.logger.org.apache.shiro=INFO # Disable verbose logging log4j.logger.org.apache.shiro.util.ThreadContext=WARN log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN三:简单demo
1,ShiroConfig
package com.kuang.config; import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.linkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { //ShiroFilterFactoryBean 第三步 @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManage")DefaultWebSecurityManager defaultWebSecurityManager ){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); //添加shiro的内置过滤器 //登录拦截 MapfilterChainDefinitionMap = new linkedHashMap<>(); filterChainDefinitionMap.put("/user/add","authc"); filterChainDefinitionMap.put("/user/edit","authc");//给这两个页面添加了认证,不认证就看不见 filterChainDefinitionMap.put("/user/del","anon");//没有认证,也能看见 filterChainDefinitionMap.put("/user/add","perms[user:add]");//add请求,登录人必须有user:add权限才能访问,没有授权会跳转到未授权页面 filterChainDefinitionMap.put("/user/edit","perms[user:update]");//edit,登录人必须有user:update权限才能访问 filterChainDefinitionMap.put("/user/del","perms[user:add,user:update]");//del 登录人必须有user:add,user:update权限才能访问 shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); //设置登录的请求 shiroFilterFactoryBean.setLoginUrl("/toLogin"); //访问未授权的请求,就会自动跳转到这个请求/noAuthorization,给他展示未授权页面 shiroFilterFactoryBean.setUnauthorizedUrl("/noAuthorization"); //设置安全管理器 shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager); return shiroFilterFactoryBean; } //DefaultWebSecurityManager 第二步 userRealm已经被spring管理了,所以可以作为参数传进方法中 @Bean(name = "defaultWebSecurityManage") public DefaultWebSecurityManager getDefaultWebSecurityManage(@Qualifier("userRealm") UserRealm userRealm){ DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); //关联userRealm defaultWebSecurityManager.setRealm(userRealm); return defaultWebSecurityManager; } //创建realm 需要自定义类 第一步 @Bean(name = "userRealm") public UserRealm userRealm(){ return new UserRealm(); } //前端用的 //整和shiroDialect 用来整和shiro thymeleaf 包括前面的springsecurity thymeleaf 这可以理解为是thymeleaf的不通方言 @Bean public ShiroDialect getShiroDialect(){ return new ShiroDialect(); } }
2,RealmUser
package com.kuang.config; import com.kuang.pojo.User; import com.kuang.service.UserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; 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.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行了授权author"); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //info.addStringPermission("user:add");//给登录的用户进行了user:add授权,这样的话,就给了所有登录用户都授权,没有达到权限过滤,代码不够灵活,写死了 //为了避免给所有人都进行权限分配,所以需要改变设计思路将,权限存在数据库中,来查询 //获取权限,此刻又出现了新问题,用户信息都是在认证中,我现在是在授权中,该怎么获取这个用户呢?,通过Subject //拿到当前登录的subject对象 Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal();//认证的时候塞进来的 String perms = user.getPerms(); //多个权限 String[] split = perms.split(","); for (String s : split) { info.addStringPermission(s); } return info; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("执行了认证authentic"); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; //连接数据库 手动验证用户名 User user = userService.queryByName(token.getUsername()); if(user == null){ return null; } //shiro可以加密 MD5加密 MD5盐值加密 //密码认证shiro会帮我们做~,不用编码来判断 // return new SimpleAuthenticationInfo("",user.getPwd(),""); return new SimpleAuthenticationInfo(user,user.getPwd(),"");//第一个参数是为了将user存放在principal中,这样在授权中就可以取出来 } }
//添加shiro的内置过滤器
a,认证查看,首页有些功能,需要登录认证了才会展示出来 anon/authc
b,登录人员认证,用户登录时账号密码验证
subject.login(token);//执行了登录方法,验证了账号密码,封装起来的,走了很多层
c,登录人员进行授权,UserRealm中进行的授权 perms
3,后端的代码省略,无非是处理前段的请求,进行页面跳转,查询数据库验证数据。
4,前端权限控制的核心部分
添加 修改 删除 登录 注销
shiro:hasPermission="user:add" 有user:add才能看见
shiro:notAuthenticated 未登录才能看见
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)