分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
1.什么是授权
授权,就是访问控制,控制某个用户在应用程序中是否有权限做某件事
2.授权三要素
权限
请看Shiro学习笔记(1)——shiro入门中权限部分内容
角色
通常代表一组行为或职责.这些行为演化为你在一个软件应用中能或者不能做的事情。角色通常是分配给用户帐户的,因此,通过分配,用户能够“做”的事情可以归属于各种角色
- 隐式角色:一个角色代表着一系列的操作,当需要对某一操作进行授权验证时,只需判断是否是该角色即可。这种角色权限相对简单、模糊,不利于扩展
- 显式角色:一个角色拥有一个权限的集合。授权验证时,需要判断当前角色是否拥有该权限。这种角色权限可以对该角色进行详细的权限描述,适合更复杂的权限设计。 Shiro官方推荐使用这种方式。
用户
通常我们将一系列的权限分配给角色,一个用户可以拥有多个角色。这样我们就能控制用户拥有哪些权限
3.Shiro的三种授权方式
可以参考官方文档 Apache shiro
3.1 编码方式授权
这种方式授权在前面的博客有出现过,只不过没有进行详细说明,可以参考
1. Shiro学习笔记(1)——shiro入门
2. Shiro学习笔记(2)——身份验证之Realm
现在再写一次
- 创建java工程,添加需要的jar包
- 自定义Realm,给用户分配一个权限和角色
package com.shiro.realm;import java.util.HashSet;import java.util.Set;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.realm.Realm;import org.apache.shiro.subject.PrincipalCollection;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class MyRealm1 extends AuthorizingRealm{ private static final transient Logger log = LoggerFactory.getLogger(Main.class); /** * 获取身份信息,我们可以在这个方法中,从数据库获取该用户的权限和角色信息 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { log.info("----------doGetAuthorizationInfo方法被调用----------"); String username = (String) getAvailablePrincipal(principals); //通过用户名从数据库获取权限字符串 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //权限 Set<String> s = new HashSet<String>(); s.add("printer:print"); s.add("printer:query"); info.setStringPermissions(s); //角色 Set<String> r = new HashSet<String>(); r.add("role1"); info.setRoles(r); return info; } /** * 在这个方法中,进行身份验证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { //用户名 String username = (String) token.getPrincipal(); log.info("username:"+username); //密码 String password = new String((char[])token.getCredentials()); log.info("password:"+password); //从数据库获取用户名密码进行匹配,这里为了方面,省略数据库操作 if(!"admin".equals(username)){ throw new UnknownAccountException(); } if(!"123".equals(password)){ throw new IncorrectCredentialsException(); } //身份验证通过,返回一个身份信息 AuthenticationInfo aInfo = new SimpleAuthenticationInfo(username,password,getName()); return aInfo; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 配置文件(shiro-realm.ini)
#声明一个realm MyRealm1=com.shiro.realm.MyRealm1 #指定securityManager的realms实现 securityManager.realms=$MyRealm1
- 1
- 2
- 3
- 4
- 验证权限和角色
package com.shiro.realm;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.LockedAccountException;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.config.IniSecurityManagerFactory;import org.apache.shiro.mgt.SecurityManager;import org.apache.shiro.subject.Subject;import org.apache.shiro.util.Factory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class Main { private static final transient Logger log = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { //获取SecurityManager的实例 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject currenUser = SecurityUtils.getSubject(); //如果还未认证 if(!currenUser.isAuthenticated()){ UsernamePasswordToken token = new UsernamePasswordToken("admin","123"); token.setRememberMe(true); try { currenUser.login(token); } catch (UnknownAccountException uae) { log.info("没有该用户: " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info( token.getPrincipal() + " 的密码不正确!"); } catch (LockedAccountException lae) { log.info( token.getPrincipal() + " 被锁定 ,请联系管理员"); }catch (AuthenticationException ae) { //其他未知的异常 } } if(currenUser.isAuthenticated()) log.info("用户 "+currenUser.getPrincipal() +" 登录成功"); //=====================使用编码方式进行权限和角色的验证================== //是否有role1这个角色 if(currenUser.hasRole("role1")){ log.info("有角色role1"); }else{ log.info("没有角色role1"); } //是否有对打印机进行打印操作的权限 if(currenUser.isPermitted("printer:print")){ log.info("可以对打印机进行打印操作"); }else { log.info("不可以对打印机进行打印操作"); } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 除了上面用到的
hasRole
和isPermitted
,还有其他api可以验证授权
—————————————————-角色————————————————–
方法 | 返回 |
---|---|
hasRole(String roleName) | 返回true 如果Subject 被分配了指定的角色 |
hasRoles(List<String> roleNames) | 返回一个与方法参数中目录一致的hasRole结果的数组 |
hasAllRoles(Collection<String> roleNames) | 返回true 如果Subject 被分配了所有的角色 |
checkRole(String roleName) | 成功,不返回任何值,程序继续执行;失败时,将抛出异常信息 |
checkRoles(Collection<String> roleNames) | 成功,不返回任何值,程序继续执行;失败时,将抛出异常信息 |
checkRole(String… roleNames) | 成功,不返回任何值,程序继续执行;失败时,将抛出异常信息 |
—————————————————-权限————————————————–
方法 |
---|
isPermitted(String perm) |
isPermitted(String… perms) |
checkPermission(Permission p) |
checkPermissions(Collection<Permission> perms) |
权限和角色的方法都差不多,就不再详细说明了
3.2 基于注解的授权
基于注解的授权,需要有AOP的支持,我们这里使用spring,你也可以使用AspectJ或者 Guice
创建一个java工程(注意,不是web工程,两者的配置有一些差别)
自定义Realm(这一步和上面的MyRealm1一模一样,复制一份即可)
- 在src下创建spring配置文件(applicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.shiro.anno"></context:component-scan> <!-- 配置Realm --> <bean id="MyRealm1" class="com.shiro.anno.MyRealm1"></bean> <!-- 配置securityManager --> <bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager"> <property name="realm" ref="MyRealm1" /> </bean> <!-- 生命周期 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <!-- 启用shiro注解 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> <!-- 让securityManager这个bean成为静态单例的bean 注意:在web应用中,不要配置这个 --> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" /> <property name="arguments" ref="securityManager" /> </bean></beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 写一个类用于注解授权
package com.shiro.anno;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.authz.annotation.RequiresPermissions;import org.apache.shiro.subject.Subject;import org.springframework.stereotype.Service;@Servicepublic class HelloAnno { public void login(){ Subject currenUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("admin","123"); token.setRememberMe(true); currenUser.login(token); } /** * 有printer:print权限才能调用该方法 * 否则抛异常 */ @RequiresPermissions({"printer:print"}) public void testAnnotation(){ System.out.println("使用注解方式。。。"); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 测试
package com.shiro.anno;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloAnno helloAnno = (HelloAnno)ctx.getBean("helloAnno"); helloAnno.login(); //有权限时,该方法才正常调用,否则抛异常 helloAnno.testAnnotation(); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
当有权限时,正常调用,没有权限时,结果如下
还有其他的注解
注解 | 说明 |
---|---|
@RequiresAuthentication | 要求当前Subject 已经在当前的session 中被验证通过才能被注解的类/实例/方法访问或调用 |
@RequiresGues | 要求当前的Subject 是一个“guest”,也就是他们必须是在之前的session中没有被验证或记住才能被注解的类/实例/方法访问或调用 |
@RequiresPermissions | 要求当前的Subject 被允许一个或多个权限,以便执行注解的方法,比如:@RequiresPermissions(“account:create”) |
@RequiresRoles | 要求当前的Subject 拥有所有指定的角色。如果他们没有,则该方法将不会被执行,而且AuthorizationException 异常将会被抛出。比如:@RequiresRoles(“administrator”) |
@RequiresUser | 需要当前的Subject 是一个应用程序用户才能被注解的类/实例/方法访问或调用。要么是通过验证被确认,或者在之前session 中的’RememberMe’服务被记住 |
3.3 JSP标签授权
1.上面使用的是普通的java工程结合spring进行注解方式的授权,jsp标签授权就必须使用web项目了。
2.我们这次使用springmvc+spring+shiro
springmvc和spring相关配置,我直接贴出来,就不进行说明了
- 创建web项目
- 创建HelloAnno.java和MyRealm1.java(和上面一模一样,复制即可)
- 在src下创建springmvc.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.shiro.controller"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <mvc:default-servlet-handler/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 在src下创建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.shiro.annotation"></context:component-scan> <!-- shiro过滤器bean,id要和web.xml中filter-name一致 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="filterChainDefinitions"> <value> #这里相当于ini配置文件中的[urls] #url=拦截器[参数],拦截器 # some example chain definitions: /admin/** = authc, roles[admin] /docs/** = authc, perms[document:read] # 当访问login时,不用进行认证(anon表示匿名) /login = anon /** = authc # more URL-to-FilterChain definitions here </value> </property> </bean> <!-- 配置securityManager --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm" /> <!-- <property name="sessionMode" value="native"/> --> </bean> <!-- 生命周期 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <!-- 配置Realm: --> <bean id="myRealm" class="com.shiro.annotation.MyRealm1"></bean> <!-- 启用shiro注解 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> <!-- ============一般情况还要配置 数据源,事务 等等=============== --></beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
其实在spring配置文件中,只使用到了spring的IOC容器,其他的配置都是在配置shiro
- web.xml中配置,让spring,springmvc,shiro过滤器起作用
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>shiro2</display-name> <!-- name要和 applicationContext.xml中的对应的bean的id一致 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置启动 Spring IOC 容器的 Listener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmvc.xml --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 在web目录下创建login.jsp登录界面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <h1>login</h1> <form action="login"> <label>username:</label> <input type="text" name="username"/> <label>password:</label> <input type="text" name="password"/> <input type="submit" value="submit"/> </form></body></html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 对应的处理登录请求的controller
package com.shiro.controller;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.subject.Subject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.shiro.annotation.HelloAnno;@Controllerpublic class TestController { @Autowired private HelloAnno helloAnno; @RequestMapping("/login") public String test(String username,String password){ System.out.println("username:"+username); System.out.println("password"+password); //登录 UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject currentUser = SecurityUtils.getSubject(); //如果登录失败,会抛异常,应该要捕捉异常 currentUser.login(token); if(currentUser.isAuthenticated()){ System.out.println("认证成功"); //有权限才能调用该方法,没权限将抛异常 helloAnno.testAnnotation(); } return "success"; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 在这里,我们使用到了上面讲过的基于注解的授权
- 最后返回success.jsp页面,在该页面中,我们使用jsp标签授权
- 在WEB-INF/views下创建success.jsp(要导入标签库)
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
- 1
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <h1>successful</h1> <!-- 如果当前用户有printer:print权限,标签内的内容才显示 --> <shiro:hasPermission name="printer:print"> 我有打印机的打印权限 </shiro:hasPermission> <shiro:hasPermission name="printer:query"> 我有打印机的查询权限 </shiro:hasPermission> <shiro:hasPermission name="printer:delete"> 我有打印机的删除权限 </shiro:hasPermission></body></html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
在我们自定义的Realm中,我们给了该用户两个权限(printer:print和printer:query),因此success.jsp页面应该打印出有查询和打印两个权限,我们来看看结果是否与我们预期
在登录界面输入用户名密码
提交后,跳转到成功页面
达到预期效果
- jsp标签除了有shiro:hasPermission之外,还有很多
<shiro:guest/>
,<shiro:hasRole/>
等 - 详情请查看官方文档
JSP/GSP Tag Library for Apache Shiro