授权,也叫访问控制,即在应用中控制谁访问哪些资源(如访问页面/编辑数据/页面操作
等)。在授权中需了解的几个关键对象:主体(Subject)、资源(Resource)、权限
(Permission)、角色(Role)。
Shiro对于权限控制使用可以分为两种:1、对于url访问的权限配置控制 2、编程的显示调用控制。
1、对于url访问的权限控制
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> ...... <property name="filterChainDefinitions"> <value> /**/login = anon /toLogin = anon # everything else requires authentication: /admin =roles[admin] /** = authc </value> </property> </bean>
对于url权限控制访问是通过filter实现的。
2、编程的显示调用控制
1)编程式:通过写if/else 授权代码块完成
Subject currentUser = SecurityUtils.getSubject();
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:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); }
2)注解式:通过在执行的Java方法上放置相应的注解完成,没有权限将抛出相应的异常。@
@RequiresRoles("schwartz") public void hello(){ //有权限 }
3)JSP/GSP 标签:在JSP/GSP 页面通过相应的标签完成
<shiro:hasRole name="user"> <br><br> <a href="${pageContext.request.contextPath}/user">User Page</a> </shiro:hasRole>
简单案例演示权限控制
实现功能:完成登录验证后,进入主页面,拥有user的role用户可以访问user页面,拥有admin的role用户可以访问admin页面。
工程目录:
主页面list.jsp
<%@ 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> <h4>List Page</h4> Welcome: <shiro:principal></shiro:principal> <shiro:hasRole name="admin"> <br><br> <a href="${pageContext.request.contextPath}/admin">Admin Page</a> </shiro:hasRole> <shiro:hasRole name="user"> <br><br> <a href="${pageContext.request.contextPath}/user">User Page</a> </shiro:hasRole> <br><br> <a href="${pageContext.request.contextPath}/logout">logout</a> </body> </html>
LoginController
package org.tarena.shiro.controller; import javax.websocket.server.PathParam; 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.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping(value="/") public class LoginController { private static final transient Logger log = LoggerFactory.getLogger(LoginController.class); @RequestMapping("login") public String login(){ return "login"; } @RequestMapping("toLogin") public String toLogin(@PathParam(value="username") String username,@PathParam(value="password") String password){ // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // let's login the current user so we can check against roles and permissions: if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(username, password); //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? } } return "redirect:/list"; } @RequestMapping("list") public String List(){ return "list"; } @RequestMapping("unauthorized") public String unauthorized(){ return "unauthorized"; } @RequestMapping("user") public String user(){ return "user"; } @RequestMapping("admin") public String admin(){ return "admin"; } @RequestMapping("logout") public String loginOut(){ Subject currentUser = SecurityUtils.getSubject(); currentUser.logout(); return "redirect:/login"; } }
继承AuthorizingRealm,重写doGetAuthorizationInfo方法
package org.tarena.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.LockedAccountException; 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.crypto.hash.SimpleHash; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; public class MyRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(//获取权限信息 PrincipalCollection principals) { //1. 从 PrincipalCollection 中来获取登录用户的信息 Object principal =principals.getPrimaryPrincipal(); //2. 利用登录的用户的信息来用户当前用户的角色或权限(可能需要查询数据库) Set<String> roles = new HashSet<>(); roles.add("user"); if("admin".equals(principal)) roles.add("admin"); //Set<String> permissions = null; SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles); return info; } @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException {//获取用户信息 // 1. 把 AuthenticationToken 转换为 UsernamePasswordToken UsernamePasswordToken userToken = (UsernamePasswordToken) token; // 2. 从 UsernamePasswordToken 中来获取 username String username = userToken.getUsername(); // 3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录 System.out.println("从数据库中获取 username: " + username + " 所对应的用户信息."); // 4. 若用户不存在, 则可以抛出 UnknownAccountException 异常 if ("unknown".equals(username)) { throw new UnknownAccountException("用户不存在!"); } // 5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常. if ("monster".equals(username)) { throw new LockedAccountException("用户被锁定"); } // 6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: // SimpleAuthenticationInfo // 以下信息是从数据库中获取的. // 1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象. Object principal = username; // 2). credentials: 密码. Object credentials = null; if ("admin".equals(username)) { credentials = "c41d7c66e1b8404545aa3a0ece2006ac"; // } else if ("user".equals(username)) { credentials = "3e042e1e3801c502c05e13c3ebb495c9"; } String realmName = getName(); ByteSource credentialsSalt = ByteSource.Util.bytes(username); SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials,credentialsSalt, realmName); return info; } }
配置MyRealm
<bean id="myRealm" class="org.tarena.shiro.realm.MyRealm"> <property name="credentialsMatcher" > <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="MD5"></property> <property name="hashIterations" value="1024"></property> </bean> </property> </bean>