Shiro —— 從一個簡單的例子開始,shiro例子開始

來源:互聯網
上載者:User

Shiro —— 從一個簡單的例子開始,shiro例子開始

一、Shiro是用來做許可權的。

二、許可權

1.基本概念:

(1)安全實體:要保護的資料。

(2)許可權:是否有能力去操作(查看、修改、刪除 )保護的資料。

2、許可權的兩個特性

(1)許可權的繼承性:A 包含 B,B無許可權,但A有許可權,此時B 的許可權即為 A 的許可權。如大廈裡有公用廁所,進出大廈需要門禁,所以公用廁所的許可權就是大廈的門禁許可權。

(2)最近路勁匹配:如大廈某層有衛生間,要想到此衛生間需要有該層電梯許可權,此時該衛生間的許可權為該層電梯的許可權,而不是大廈的門禁許可權。

3.幾個關鍵詞

(1)認證:驗證使用者身份,即驗證登入的使用者名稱密碼是否正確,使用者是否被鎖死。

(2)授權:決定是否有許可權訪問受保護的資源。

(3)加密:保護或隱藏受保護的資源。

(4)會話管理

(5)單點登入(SSO)

三、Shiro

1.核心組件

(1)Subject:目前使用者。

(2)Shiro SecurityManager:Shiro 大管家。

(3)Realm:用於訪問資料庫。

2.Shiro SecurityManager

Shiro 的大管家管理著 Shiro 下的認證、授權、會話管理、緩衝管理、以及 Realm 訪問資料庫,貫穿於始終的是加密。

3.使用者、角色、許可權

(1)概念:

  • 使用者:通俗來講,指的就是要登入的使用者名稱密碼。
  • 角色:許可權的集合。
  • 許可權:是否有能力去做某件事。

(2)關係

  • 許可權作用於角色,角色是許可權的一個集合
  • 角色作用於使用者,使用者是什麼角色。

(3)維繫關係

  • 使用者——角色:使用者角色中間表。
  • 角色——許可權:角色許可權中間表。

(4)以上所有的這些都歸 Shiro 大管家來管理。

四、一個簡單的官方的例子

1.需要匯入的 jar 包。

2.官方demo。

/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. */import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.*;import org.apache.shiro.config.IniSecurityManagerFactory;import org.apache.shiro.mgt.SecurityManager;import org.apache.shiro.session.Session;import org.apache.shiro.subject.Subject;import org.apache.shiro.util.Factory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Simple Quickstart application showing how to use Shiro's API. * * @since 0.9 RC2 */public class Quickstart {    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);    public static void main(String[] args) {        // The easiest way to create a Shiro SecurityManager with configured        // realms, users, roles and permissions is to use the simple INI config.        // We'll do that by using a factory that can ingest a .ini file and        // return a SecurityManager instance:        // Use the shiro.ini file at the root of the classpath        // (file: and url: prefixes load from files and urls respectively):        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");        SecurityManager securityManager = factory.getInstance();        // for this simple example quickstart, make the SecurityManager        // accessible as a JVM singleton.  Most applications wouldn't do this        // and instead rely on their container configuration or web.xml for        // webapps.  That is outside the scope of this simple quickstart, so        // we'll just do the bare minimum so you can continue to get a feel        // for things.        SecurityUtils.setSecurityManager(securityManager);        // Now that a simple Shiro environment is set up, let's see what you can do:        // 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 = currentUser.getSession();        session.setAttribute("someKey", "aValue");        String value = (String) session.getAttribute("someKey");        if (value.equals("aValue")) {            log.info("-->Retrieved the correct value! [" + value + "]");        }        // let's login the current user so we can check against roles and permissions:        if (!currentUser.isAuthenticated()) {            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:weild")) {            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);    }}

說明:擷取 SecurityManager ,認證,認證失敗的幾種情況,成功登陸後是否擁有某個角色,某個角色是否有某個許可權。

[users]root = secret, adminguest = guest, guestpresidentskroob = 12345, presidentdarkhelmet = ludicrousspeed, darklord, schwartzlonestarr = vespa, goodguy, schwartz[roles]admin = *schwartz = lightsaber:*goodguy = winnebago:drive:eagle5

說明:Shiro.ini 檔案,用來維繫使用者——角色——許可權之間的關係。

3.ini 檔案說明

[users]:使用者名稱=密碼,角色1,角色2

[roles]:角色=許可權1,許可權2

許可權:

(1)用簡單的字串來表示一個許可權。如:user

(2)多層次管理:如:user:query,user:edit,user:query,edit。第一部分為操作的領域,第二部分為執行的操作。可以使用萬用字元:user:*,*:query

(3)執行個體級許可權:域:操作:執行個體

如:user:edit:manager 只能對 user 中的 manager 進行 edit。

萬用字元:user:edit:*、user:*:*、user:*:manager

等價:user:edit==user:edit:*、user == user:*:* 只能從字串結尾處省略。

(4)可對比官方例子學習。

五、總結:

介紹了許可權的基礎,介紹了 Shiro 的 HelloWorld,要明白其中重要的部分,如:認證、授權,以及Shiro 是如何來做這兩件事情的。介紹官方demo 的 ini 配置方式,只是想更加深刻的去理解

Shiro 的管理器,認證,授權,角色,許可權等等這些概念。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.