Shiro -- Starting from a simple example, The shiro example

Source: Internet
Author: User

Shiro -- Starting from a simple example, The shiro example

1. Shiro is used for permissions.

Ii. Permissions

1. Basic concepts:

(1) security entity: Data to be protected.

(2) Permission: whether to operate (view, modify, and delete) the data protected.

2. Two features of Permissions

(1) Permission inheritance: A contains B and B without permissions, but A has permissions. In this case, B is A permission. If there is a public toilet in the building and access control is required for access to the building, the permission of the public toilet is the access control permission of the building.

(2) Recent road force matching: if there is a toilet on a certain floor of the building, you need to have the elevator permission on this floor. At this time, the permission on the toilet is the permission on the elevator on this floor, instead of building access permissions.

3. Several keywords

(1) authentication: Verify the user's identity, that is, verify that the user name and password for Logon are correct and that the user is locked.

(2) Authorization: Determine whether you have the permission to access protected resources.

(3) encryption: protects or hides protected resources.

(4) session management

(5) Single Sign-On (SSO)

Iii. Shiro

1. Core Components

(1) Subject: the current user.

(2) Shiro SecurityManager: Shiro Butler.

(3) Realm: used to access the database.

2. Shiro SecurityManager

Shiro's Big Manager manages Shiro's authentication, authorization, session management, Cache Management, and Realm access to the database. encryption is always used throughout.

3.Users, roles, and permissions

(1) concept:

  • User: in general, it refers to the user name and password to be logged on.
  • Role: a set of permissions.
  • Permission: whether it is capable of doing something.

(2) relationship

  • A role is a set of permissions.
  • The role acts on the user and what role the user is.

(3) Maintain relationships

  • User-role: User Role intermediate table.
  • Role -- permission: Role permission intermediate table.

(4) All of the above are managed by the Shiro Butler.

4. A simple official example

1. The jar package to be imported.

2. Official 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);    }}

NOTE: If SecurityManager is obtained, authentication, or authentication fails, whether a role or a role has a certain permission after successful logon.

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

Note: The Shiro. ini file is used to maintain the relationship between user-role-permissions.

3. ini file description

[Users]: username = password, role 1, role 2

[Roles]: Role = permission 1, permission 2

Permission:

(1) Use a simple string to represent a permission. For example, user

(2) multi-level management: for example, user: query, user: edit, user: query, and edit. The first part is the operation field, and the second part is the execution operation. Wildcard characters: user: *, *: query

(3) instance-level permission: domain: Operation: instance

For example, user: edit: manager can only edit the manager in the user.

Wildcard: user: edit: *, user: *, user: *: manager

Equivalent: user: edit = user: edit: *, user = user: * can only be omitted from the end of a string.

(4) Compare the official examples.

V. Summary:

This section describes the basics of permissions and the HelloWorld of Shiro. You need to understand the important parts, such as authentication and authorization, and how Shiro does these two tasks. Introduce the ini configuration method of the official demo, just for a deeper understanding

Shiro's manager, authentication, authorization, roles, permissions, and so on.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.