Authorization
授权,也叫访问控制,即在应用中控制谁访问哪些资源(如访问页面/编辑数据/页面操作
等)。在授权中需了解的几个关键对象:主体(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>
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=""></property>
</bean>
</property>
</bean>
Authorization的更多相关文章
- [转]教你实践ASP.NET Core Authorization
本文转自:http://www.cnblogs.com/rohelm/p/Authorization.html 本文目录 Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主, ...
- [转]Web APi之认证(Authentication)及授权(Authorization)【一】(十二)
本文转自:http://www.cnblogs.com/CreateMyself/p/4856133.html 前言 无论是ASP.NET MVC还是Web API框架,在从请求到响应这一过程中对于请 ...
- [转]OAuth 2.0 - Authorization Code授权方式详解
本文转自:http://www.cnblogs.com/highend/archive/2012/07/06/oautn2_authorization_code.html I:OAuth 2.0 开发 ...
- Authorization in Cloud Applications using AD Groups
If you're a developer of a SaaS application that allows business users to create and share content – ...
- 教你实践ASP.NET Core Authorization
本文目录 Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主,当然如果说webapi或者其他的分布式解决方案授权,也容易就可以实现单点登录都非常的简单,可以使用现成的Iden ...
- ABP理论学习之授权(Authorization)
返回总目录 本篇目录 介绍 定义权限 检查权限 使用AbpAuthorize特性 使用IPermissionChecker Razor视图 客户端(Javascript) 权限管理者 介绍 几乎所有的 ...
- Web APi之认证(Authentication)及授权(Authorization)【一】(十二)
前言 无论是ASP.NET MVC还是Web API框架,在从请求到响应这一过程中对于请求信息的认证以及认证成功过后对于访问页面的授权是极其重要的,用两节来重点来讲述这二者,这一节首先讲述一下关于这二 ...
- authorization与URL授权
利用Web.config中的authorization标签设置授权属于URL授权. 使用 URL 授权 通过 URL 授权,您可以显式允许或拒绝某个用户名或角色对特定目录的访问权限.为此,请在该目录的 ...
- Lind.DDD.Authorization用户授权介绍
回到目录 Lind.DDD.Authorization是Lind.DDD框架的组成部分,之所以把它封装到框架里,原因就是它的通用性,几乎在任何一个系统中,都少不了用户授权功能,用户授权对于任何一个系统 ...
- Security » Authorization » 通过映射限制身份
Limiting identity by scheme¶ 通过映射限制身份(这部分有好几个概念还不清楚,翻译的有问题) 36 of 39 people found this helpful In so ...
随机推荐
- 替换分隔符 ^p, 或者是回车
1 Excel 里面的数据, 粘出来到notepad上,再从notepad 粘到word, 再把world里面的分隔符或者是回车符替换成 其他的 .
- Git 回滚 Master
RenGuoQiang@PC-RENGUOQIANG MINGW64 /d/zgg/zgg-crm (master) $ git reset --hard 194e2cc8eec88743cc8978 ...
- StringBuffer & StringBuilder的区别
StringBuffer是线程安全的,内部有锁.所以比StringBuilder慢一点. 在单线程生成字符串的情况下,优先使用StringBuilder. 这就是为啥有时候IntelliJ Idea会 ...
- leetcode 874. Walking Robot Simulation
874. Walking Robot Simulation https://www.cnblogs.com/grandyang/p/10800993.html 每走一步(不是没走commands里的一 ...
- 十、collection的作用+变量
一.collection作用?容器 组织业务逻辑 导入导出 其他功能,比如监控和mock server 二.为什么要使用变量 假设我们需要测试n个api,这些api的domain都是相同的,比如 ap ...
- Python3基础 for-else break、continue跳出循环示例
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- 0.9.0.RELEASE版本的spring cloud alibaba sentinel限流、降级处理实例
先看服务提供方的,我们在原来的sentinel实例(参见0.9.0.RELEASE版本的spring cloud alibaba sentinel实例)上加上限流.降级处理,三板斧只需在最后那一斧co ...
- Spring cloud微服务安全实战-6-4权限控制改造
授权,权限的控制 令牌里的scope包含fly就有权限访问.根据Oauth的scope来做权限控制, 要让@PreAuthorize生效,就要在启动类里面写一个注解. 里面有一个属性叫做,就是在方法的 ...
- linux添加动态库路劲
修改这个文件/etc/ld.so.conf.d,最后加上so的绝对路径即可
- QML注意color小写
1.用的时候大小写一样的 如: color="#3D3D3D" 和 color="#3d3d3d"都是同一个颜色 2.判断的时候,QML默认是小写 如:if(c ...