SpringBoot rights management and integration of combat Shiro

SpringBoot rights management and integration of combat Shiro

Author: Stanley Luo Hao

[ Please indicate the source and the signature, thank you! ]

* Watch this article need to have some SpringBoot integration experience *

Shiro framework Introduction

Apache Shiro is 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 network applications and enterprise applications.

Shiro analysis of the core API

In fact, Shiro has three core classes, namely:

1.Subject: some of the ways this class, let's call it the main body of the current user, the user's body contains a login, logout and so on, there are some methods to determine authorization;

2.SecurityManager: The name translates, security manager means;

3.Realm: The Realm of it is actually a bridge to link the database Shiro us, because our program needs to operate the database to get some user information, these operations require Realm to complete;

The three API does, there are some relationships, such .SecurityManager need to associate our Realm, Subject to the need to operate our SecurityManager, conclude that, Subject is the need to manage our SecurityManager, and to associate SecurityManager our Realm;

These are some of the analysis of the core API Shiro carried out;

After completion of the analysis, we are going to integrate directly with SpringBoot with Shiro, we look at it a key step in the integration of

SpringBoot integrity Shiro

The first step then this integration need to import Shiro dependence;

[Because I use Gradle, so only show Gradle usage]

1. Modify .gradle file, add the following dependency

// Thymeleaf template engine, because I used the template engine so I added this dependence 
        the compile Group: 'org.thymeleaf', name: 'Thymeleaf', Version: '3.0.11.RELEASE' // Shiro 
        the compile Group: 'ORG. apache.shiro ', name:' Shiro-Web ', Version:' 1.4.0 ' 
        the compile Group: ' org.apache.shiro ', name:' Shiro-Core ', Version:' 1.4.0 '
         // HTTPS: //mvnrepository.com/artifact/org.apache.shiro/shiro-spring 
        the compile Group: 'org.apache.shiro', name: 'Shiro-Spring', Version: '1.4.0'
         

2. Write Shiro configuration class

Configuration class need three API, are:

 / ** 
     * Create ShiroFilterFactoryBean 
     * shiro filter bean 
     * / 

/ ** 
     * Create DefaultWebSecurityManager 
     * / 

    / ** 
     * Create Realm 
     * /

Figure:

3. custom class Realm

Because we need to create the configuration classes in the Realm object, so we need to build a class called Realm:

Once created, you need to inherit a method that is provided by Shiro:

/**
 * 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {
    //执行授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }

    //执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
      
        return null;

    }

4. In the new class configuration Realm

 

Shiro Configuration class

Package com.lh.shiroStudy.shiro; 


Import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
 Import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
 Import org.springframework.beans.factory.annotation.Qualifier;
 Import ORG .springframework.context.annotation.Bean;
 Import org.springframework.context.annotation.Configuration; 

Import java.util.LinkedHashMap;
 Import a java.util.Map; 


/ ** 
 * Shiro configuration class 
 * / 
// @Configuration, this statement configuration class is a class 
@Configuration
 public  class ShiroConfig { 

    / **  
     * Create ShiroFilterFactoryBean
     * Shiro filtering the bean 
     * /
    @Bean 
    public ShiroFilterFactoryBean getShiroFilterFactoryBean (@Qualifier ( "securityManager" ) DefaultWebSecurityManager securityManager) { 
        ShiroFilterFactoryBean shiroFilterFactoryBean = new new ShiroFilterFactoryBean ();
         // set the security manager 
        shiroFilterFactoryBean.setSecurityManager (securityManager);
         // add Shiro filter 
        / ** 
         * Built Shiro filters can be achieved rights associated interceptor 
         * commonly used filters: 
         * anon: without authentication (login) can access 
         * authc: must be certified before they can access the 
         * user: If you use rememberMe functions can be accessed directly  
         * perms: the resources must be access privileges to resources
         * role: the resource must get role permissions can access 
         * / 

        the MapsetUnauthorizedUrl ( "/ aaaaaa"); //

        

         the easy way so there is no aaaa this page, if necessary, add Contoller in 

        shiroFilterFactoryBean.setFilterChainDefinitionMap (filterMap); 
        return shiroFilterFactoryBean; 
    } 


    / ** 
     * Create a DefaultWebSecurityManager 
     * / 
    @Bean (name = "securityManager" )
     public DefaultWebSecurityManager getDefaultWebSecurityManager (@Qualifier ( "UserRealm to" ) UserRealm to UserRealm) { 
        DefaultWebSecurityManager securityManager = new new DefaultWebSecurityManager (); 
        securityManager.setRealm (UserRealm); 
        return securityManager; 
    }



     / ** 
     * Create Realm 
     * /
    @Bean(name = "UserRealm")
    public UserRealm getRealm(){
        return new UserRealm();
    }

}

Realm category

package com.lh.shiroStudy.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


/**
 * 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {
    //执行授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //给资源进行授权
        Info = SimpleAuthorizationInfo new new SimpleAuthorizationInfo (); 

        // add resources authorization string
         // info.addStringPermission ( "the User: the Add"); 

        // to query the database currently logged in user's authorization string 
        / ** 
         ! * <- Demo state ! -> 
         * get the current user 
         * Subject Subject = SecurityUtils.getSubject (); 
         * = the user the user (the user) subject.getPrincipal (); 
         * the user dbUser = userService.findById (the above mentioned id) 
         * info.addStringPermission (dbUser.getPerms () ); 
         * <! / - demonstration state -!> 
         * / 
        System.out.println ( "authorization logic execution" );
         return  null ; 
    } 

    //Performing authentication logic 
    @Override
     protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken the arg0) throws of AuthenticationException { 
        System.out.println ( "logic performs authentication" );
         // assume that the database username and password are as follows 
        String username = "ADMIN" ; 
        String password = "123456" ;
         / * 
         * write Shiro determination logic, user name and password match 
         * / 
        // 1. Analyzing username 
        UsernamePasswordToken token = (UsernamePasswordToken) the arg0; 

        // the user user = userService.findByName (token.getUsername ()); 

        IF ( == User null ) {
            // username does not exist 
            return  null ; // if it returns null, Shiro bottom throw UnknowAccountException 
        }
         // 2. Analyzing password 
        / ** 
         * There are three parameters 
         * 1. The need to return to the Login 
         * 2. is the password database, the database password return, automatically determines Shiro 
         * is 3. Shiro name 
         * / 
        return  new new SimpleAuthenticationInfo (User, password, "" ); 

    } 
}

 

Guess you like

Origin www.cnblogs.com/StanleyBlogs/p/11407350.html