授权,也叫访问控制,即在应用中控制谁访问哪些资源(如访问页面/编辑数据/页面操作
等)。在授权中需了解的几个关键对象:主体(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=""></property>
</bean>
</property>
</bean>

Authorization的更多相关文章

  1. [转]教你实践ASP.NET Core Authorization

    本文转自:http://www.cnblogs.com/rohelm/p/Authorization.html 本文目录 Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主, ...

  2. [转]Web APi之认证(Authentication)及授权(Authorization)【一】(十二)

    本文转自:http://www.cnblogs.com/CreateMyself/p/4856133.html 前言 无论是ASP.NET MVC还是Web API框架,在从请求到响应这一过程中对于请 ...

  3. [转]OAuth 2.0 - Authorization Code授权方式详解

    本文转自:http://www.cnblogs.com/highend/archive/2012/07/06/oautn2_authorization_code.html I:OAuth 2.0 开发 ...

  4. 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 – ...

  5. 教你实践ASP.NET Core Authorization

    本文目录 Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主,当然如果说webapi或者其他的分布式解决方案授权,也容易就可以实现单点登录都非常的简单,可以使用现成的Iden ...

  6. ABP理论学习之授权(Authorization)

    返回总目录 本篇目录 介绍 定义权限 检查权限 使用AbpAuthorize特性 使用IPermissionChecker Razor视图 客户端(Javascript) 权限管理者 介绍 几乎所有的 ...

  7. Web APi之认证(Authentication)及授权(Authorization)【一】(十二)

    前言 无论是ASP.NET MVC还是Web API框架,在从请求到响应这一过程中对于请求信息的认证以及认证成功过后对于访问页面的授权是极其重要的,用两节来重点来讲述这二者,这一节首先讲述一下关于这二 ...

  8. authorization与URL授权

    利用Web.config中的authorization标签设置授权属于URL授权. 使用 URL 授权 通过 URL 授权,您可以显式允许或拒绝某个用户名或角色对特定目录的访问权限.为此,请在该目录的 ...

  9. Lind.DDD.Authorization用户授权介绍

    回到目录 Lind.DDD.Authorization是Lind.DDD框架的组成部分,之所以把它封装到框架里,原因就是它的通用性,几乎在任何一个系统中,都少不了用户授权功能,用户授权对于任何一个系统 ...

  10. Security » Authorization » 通过映射限制身份

    Limiting identity by scheme¶ 通过映射限制身份(这部分有好几个概念还不清楚,翻译的有问题) 36 of 39 people found this helpful In so ...

随机推荐

  1. useContext 让父子组件传值更简单(五)

    有了useState和useEffect已经可以实现大部分的业务逻辑了,但是React Hooks中还是有很多好用的Hooks函数的,比如useContext和useReducer. 在用类声明组件时 ...

  2. Java RMI实践

    Java远程方法调用,即Java RMI(Java Remote Method Invocation).一种用于实现远程过程调用的应用程序编程接口.客户机上运行的程序可以调用服务器上的对象. 缺点:只 ...

  3. flutter PopupMenuButton弹出式菜单列表

    import 'package:flutter/material.dart'; class PopupMenuButtonDemo extends StatefulWidget { @override ...

  4. Spring的@ExceptionHandler和@ControllerAdvice统一处理异常

    之前敲代码的时候,避免不了各种try..catch, 如果业务复杂一点, 就会发现全都是try…catch try{ ..........}catch(Exception1 e){ ......... ...

  5. 011-JSON、JSONObject、JSONArray使用、JSON数组形式字符串转换为List<Map<String,String>>的8种方法

    一.JSON数据格式 1.1.常用JSON数据格式 1.对象方式:JSONObject的数据是用 { } 来表示的, 例如: { "id" : "123", & ...

  6. MySQL创建双主键

    如下: CREATE TABLE `loginlog` ( `id` ) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT '主键编号', `IP` ...

  7. ROS学习笔记(一)

    运行ROS例程(turtlesim)1)安装turtlesim包sudo apt-get install ros-kinetic-turtlesim2)运行管理器节点roscore3)运行turtle ...

  8. ES6深入浅出-11 ES6新增的API(上)-2.Array新增API

    Array.form 把不是数组的东西变成数组.最常见的就是把伪数组变成数组 那么什么是伪数组 这就是伪数组,因为它不是继承自Array的原型的对象.它只是一个看起来很像数组的数组 只看下面的代码.a ...

  9. oracle数据库【表复制】insert into select from跟create table as select * from 两种表复制语句区别

    create table  as select * from和insert into select from两种表复制语句区别 create table targer_table as select ...

  10. 【438】Python 处理文件

    1. 读取文件,计算 tweets 数目 python中readline判断文件读取结束的方法 line == '' python:如何检查一行是否为空行 line == '\n' or line = ...