Shiro permissions check analysis

Shiro outlined

Shiro is a privilege validation framework provided by Apache, Shiro is also a powerful and easy to use Java security framework for authentication, authorization, cryptography, and session management. Shiro's easy to understand the use of the API, you can quickly and easily access any application, from the smallest to the largest mobile applications and enterprise network applications, especially today especially strict verification and management rights, it is necessary for everyone shiro have a basic understanding and learning.

Shiro's three core components

1, Subject: the current user's operation

Authority for verification of information: 2, SecurityManager: for managing all of Subject 3, Realms

FIG follows: call relationships between the components:

 

Subject: translator for the protagonist, the protagonist currently involved in application security section. Can be a user, you can try third-party service may be cron job, or anything. Mainly refers to a thing is interacting with the current software. All Subject require SecurityManager, when you interact with the Subject, these interactions are actually converted to interact with the SecurityManager

SecurityManager: security administrator, Shiro core architecture, it is like an umbrella inside Shiro all original. However, once the configuration SecurityManager, SecurityManager used on relatively small, the developers spent most of the top Subject Please remember when you were with the Subject

Time interaction, in fact, help you raise SecurityManager Subject to do some security operations in the background.

Realms: Realms as Shiro and your connection bridge applications, when you need to interact with the secure data, like user accounts, or access control, Shiro will find from one or more of the Realms. Shiro offers some Realms can be used directly, if the default Realms can not meet your needs, you can also customize your own Realms.

Shiro's top ten features:

Features

Shiro containing 10 contents, as shown below:

  1. Authentication: authentication / login, verify that the user is not have the appropriate status.
  2. Authorization: Authorization that the competence to verify, verify that a user has authenticated a privilege; that is, whether the user can do things such as common: verify that a user has a role. Or fine-grained verify whether a user has a permission for a resource.
  3. Session Manager: Session management, that is, after the user logs in one session, in the absence of exit, it's all the information in the session; the session can be ordinary JavaSE environment, it can be as Web environment.
  4. Cryptography: encryption to protect data security, such as encrypted passwords stored in the database, not stored in plain text.
  5. Web Support: Web support can be very easily integrated into a web environment.
  6. Caching: Cache, such as users log in, their user information, with roles / permissions do not have to check every time, so you can improve efficiency.
  7. Concurrency: shiro support concurrent verification multithreaded applications, such as opening that is another thread in a thread, can automatically propagate permissions past.
  8. Testing: provide test support.
  9. Run As: allows a user pretending to be access to another user (if they are allowed) identity.
  10. Remember Me: Remember me, this is a very common feature, ie after the first login, then do not come back next time logged.

The operating principle of Shiro

Subject: subject, you can see the body can be any interaction with the application of "user."

SecurityManager: corresponds to the SpringMVC DispatcherServlet or Struts2 in FilterDispatcher. It is the core of Shiro's, all of the specific interactions through

SecurityManager control. It manages all Subject, and is responsible for authentication and authorization, session and cache management.

Authenticator: authentication, a body responsible for certification, which is an extension point, if you feel bad Shiro default, we can custom implementation. It requires authentication policy (Authentication Strategy), that is, under what circumstances considered by the user authentication.

Authrizer: authorizer, or access controller. It is used to determine whether the subject has permission to perform the corresponding operation, i.e., which controls the functions of the user can access the application.

Realm: there may be one or more of the realm, the entity can be considered secure data source, i.e. for obtaining the security entity. It can be achieved JDBC, LDAP can be achieved, or memory realization.

SessionManager: If you wrote a Servlet should know the concept of the Session, Session need someone to manage its life cycle, this component is SessionManager. And Shiro can be used not only in the Web environment, also be used as an ordinary JavaSE environment.

SessionDAO: DAO we have used, data access objects for CRUD session. We can custom implementation SessionDAO, the position of the control session store. The JDBC written to the database or by writing by jedis in redis. In addition SessionDAO can use the Cache cache to improve performance.

CacheManager: Cache Manager. It is managed as a cache users, roles, permissions, and the like. Because these data to change only rarely, after its cache access can improve performance.

Cryptography: cryptography module, Shiro improve some common components such as password encryption for encryption / decryption.

Shiro's basic entry

Today we demonstrate entry-Shiro, there is no integration of any framework, but simply demonstrate the principle of operation of Shiro, there is no need to create a classic five tables

Idea create a project using Maven

Add the following dependency in pom.xml:

<! - dependent configuration shiro ->

<dependencies>

<dependency>

<groupId>org.apache.shiro</groupId>

<artifactId>shiro-core</artifactId>

<version>1.2.3</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-simple</artifactId>

<version>1.6.1</version>

</dependency>

</dependencies>

Arbitrarily create a package, create a test class Demo in it:

package me.aihe;import org.slf4j.Logger; import org.slf4j.LoggerFactory;

public class Demo{

private static final transient Logger log = LoggerFactory.getLogger(Tutorial.class); public static void main(String[] args) {

http://log.info("My First Apache Shiro Application"); System.exit(0);

}

} To create a configuration file shiro.ini

Shiro provides a general scheme configured through INI, of course, can be configured through XML, YMAL, JSON like. In the following resource directory, create a file shiro.ini. It reads as follows:

# -------------------------------------------------------------------------

# Users and their (optional) assigned roles

# username = password, role1, role2, ..., roleN

# -------------------------------------------------------------------------

[users]

root = secret, admin guest = guest, guest

presidentskroob = 12345, president

dark pearls = ludicrousspeed, Darklord, schwartz subject = subject, goodguy, client

# -------------------------------------------------------------------------

# Roles with assigned permissions

# roleName = perm1, perm2, ..., permN

# -------------------------------------------------------------------------

[roles] admin = *

client = look:*

goodguy = winnebago:drive:eagle5

Shiro.ini reference configuration test

Now change our Demo class file, as follows

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;

public class Demo {

private static final transient Logger log = LoggerFactory.getLogger(Tutorial.class);

public static void main(String[] args) { http://log.info("My First Apache Shiro Application");

// 1. SecurityManager here is org.apache.shiro.mgt.SecurityManager, rather than

//java.lang.SecurityManager load configuration file

Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

// 2. Parsing a configuration file, and returns some instances SecurityManger

SecurityManager securityManager = factory.getInstance();

// 3. SecurityManager set to a static memory area, singleton

SecurityUtils.setSecurityManager(securityManager);

// safe operation

Subject currentUser = SecurityUtils.getSubject();

// set a property in the current session of the application

Session session = currentUser.getSession(); session.setAttribute("key","value");

// our current users are anonymous users, we try to log in,

if(!currentUser.isAuthenticated()){

UsernamePasswordToken token = new UsernamePasswordToken("aihe", "aihe");

token.setRememberMe(true);

// user attempts to log in, if the login fails, we do some work

try{ currentUser.login(token);

// When we won the logged in user

http://log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

// Check if the user has specified role

if ( currentUser.hasRole( "client" ) ) {

http://log.info("Look is in your role" ); } else { http://log.info( ". " );

}

// Check if the user has a permission

if ( currentUser.isPermitted( "look:desk" ) ) {

http://log.info("You can look. Use it wisely.");

} else {

http://log.info("Sorry, you can't look.");

}

if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {

http://log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'. " + "Here are

the keys - have fun!");

} else {

http://log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");

}

// logout currentUser.logout ();

} catch ( UnknownAccountException uae ) {

// operating account does not exist

} catch ( IncorrectCredentialsException ice ) {

//The password is incorrect

} catch ( LockedAccountException lae ) {

// user is locked

} catch ( AuthenticationException ae ) {

// can not judge the situation

}

}

System.exit(0); }

}

By shiro demo, what have we learned

This is a relatively simple procedure, but it also proves the basic usage of some shiro, we can perform authentication, access control and other by shiro.

In this paper, Shiro was a basic introduction, Shiro specific practical application in the development, application and more in development, we did not specifically say too much, for example, and integration with other frameworks and so on, if you want to have more Shiro more information, please visit the official website to view.

Published 682 original articles · won praise 1391 · Views 1.71 million +

Guess you like

Origin blog.csdn.net/itcast_cn/article/details/104795787