Apache Shiro security framework

Keywords: Shiro Apache Session

1, What is Shiro security framework

shrio is a powerful and flexible open source security framework, which mainly deals with authentication, authorization, session management and encryption.

  • Authentication: sometimes referred to as "login", i.e. authentication of the user.

  • Authorization: the process of access control, that is, determining who has access to what.

  • Session management: user specific sessions can be managed even in non Web or EJB applications.

  • Encryption: use encryption algorithms to keep data secure while still being easy to use.

Supporting features:

  • Web support: Shiro's web support API helps developers easily protect web applications.
  • Caching: caching is the first layer of the Apache Shiro API to ensure that secure operations remain fast and efficient.
  • Concurrency: Apache Shiro's concurrency feature supports multithreaded applications.
  • Testing: test support helps you write unit and integration tests and ensures that your code is protected as expected.
  • Run As: allows users to take on the identity of other users, if allowed, which is sometimes useful in management scenarios.
  • Remember me: remember the user's identity throughout the session, so they log in only if necessary.

2, Write shiro basic code

1. Introduce relevant environment

The jar s related to shiro core and slf4j API are introduced. shiro uses slf4j to record logs.

        <dependency>
		    <groupId>org.slf4j</groupId>
		    <artifactId>slf4j-api</artifactId>
		    <version>1.7.25</version>
		</dependency>
        <dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-core</artifactId>
			<version>1.2.2</version>
		</dependency>

2. Create ini file

src/main/resources/shiro.ini

# ini file configuration
# -----------------------------------------------------------------------------
# User information format
# username [user name] = password [password], role1 [role 1], role2 [role 2],..., role [role n]
# -----------------------------------------------------------------------------
[users]
root = 123456, admin
guest = 123456, rolea
user1 = 12345, roleb

# -----------------------------------------------------------------------------
# Define role related permissions
# roleName [role name] = perm1 [permission range], perm2,..., permn
# *Similar to wildcards, representing any operation in the current scope
# -----------------------------------------------------------------------------
[roles]
admin = *
rolea = book:bug
roleb = book:add,book:delete

3. Reference procedure

package demo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
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;
/**
 * [Users, roles, and permissions are strings]
 * 
 * 
 * */
public class Test {
    //Create a log object for the current class
	private static final transient Logger log=LoggerFactory.getLogger(Test.class);

	public static void main(String[] args) {
        //Create a factory, point to the ini file, and classpath represents the Src / main / resource directory
		Factory<SecurityManager> fac=new  IniSecurityManagerFactory("classpath:shiro.ini");
		SecurityManager manager=fac.getInstance();
		SecurityUtils.setSecurityManager(manager);
		
		log.info("Environment initialization complete");
		
		Subject currentUser=SecurityUtils.getSubject();
		//System.out.println(currentUser);
		
		Session session=currentUser.getSession();
		session.setAttribute("message", "this is shiro");
		System.out.println(session.getAttribute("message"));
		//Whether the current user has verified
		System.out.println(currentUser.isAuthenticated());
		
		if(currentUser.isAuthenticated()) {
			System.out.println("Already logged in");
		}
		else {
			UsernamePasswordToken token =new UsernamePasswordToken("user1", "12345");
			//token.setRememberMe(true);
			try {
				currentUser.login(token);
				System.out.println("Login successfully");
			} catch (UnknownAccountException e) {
				System.out.println("user does not exist");
			}catch (IncorrectCredentialsException e) {
				System.out.println("Password error");
			}
			
		}
		if(currentUser.hasRole("admin")) {
			System.out.println("Welcome administrator");
		}
		if(currentUser.isPermitted("book:bug")) {
			System.out.println("Allow to buy books");
		}
		if(currentUser.isPermitted("book:add")) {
			System.out.println("Allow to add books");
		}
		if(currentUser.isPermitted("book:delete")) {
			System.out.println("Allow books to be deleted");
		}
		currentUser.logout();
	}

}

 

Published 5 original articles, praised 0, visited 2003
Private letter follow

Posted by Kev on Mon, 24 Feb 2020 20:55:28 -0800