Shiro and safer framework of SpringSecurity

    Two basic concepts

Security Entity: The system needs to protect specific data objects

Permissions: operating system-related functions, such as basic CRUD

 Shiro  

First Shiro compared with Spring Security, Shiro while maintaining powerful features, simplicity and flexibility also has a huge advantage.

Shiro is a powerful and flexible open source security framework that can deal with a very clear authentication, authorization, session management, and password encryption. Here is what it should have:

  1. Easy to understand Java Security API;
  2. Simple authentication (login), supports a variety of data sources (LDAP, JDBC, Kerberos, ActiveDirectory, etc.);
  3. On the role of a simple sign right (access control), signed right support fine-grained;
  4. Support cache to improve performance of the application;
  5. Built-in POJO-based enterprise session management for Web and non-Web-based environment;
  6. Heterogeneous client session to access;
  7. Very simple encryption API;
  8. Not with any frame or container bundles can be run independently.

Shiro four core functions: Authentication, Authorization, Cryptography, Session Management

Shiro Ka构

Shiro three core components: Subject, SecurityManager and Realms.

Subject: subject, you can see the body can be anything that can interact with the application of "user";

SecurityManager: SpringMVC equivalent of DispatcherServlet or Struts2 in FilterDispatcher; Shiro's heart; all the specific interactions are controlled by SecurityManager; it manages all Subject, and is responsible for authentication and authorization, session and cache management.

Realm: domain, Shiro acquired from safety data (such as users, roles, permissions) from the Realm, that is SecurityManager to authenticate users, it needs to obtain the appropriate user from the Realm are compared to determine the identity of the user is legitimate; need from the Realm to give the user the role / permissions to verify that the user can operate; can Realm as dataSource, i.e. secure data source.

And two configuration classes ShiroConfig UserRealm 
 1 package com.example.shirodemo.config;
 2 
 3 import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
 4 import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
 5 import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
 6 import org.springframework.beans.factory.annotation.Qualifier;
 7 import org.springframework.context.annotation.Bean;
 8 import org.springframework.context.annotation.Configuration;
 9 
10 import java.util.LinkedHashMap;
11 import java.util.Map;
12 
13  / ** 
14  * shiro arranged Deliverable
 15   * / 
16  @Configuration
 17  public  class ShiroConfig {
 18      / ** 
19       *创建ShiroFilterFactoryBean
 20       * / 
21      AttoBean
 22      public ShiroFilterFactoryBean GetShiroFilterFactoryBean (AttoQualifier ( "securityManager" ) DefaultWebSecurityManager securityManager) {
 23          ShiroFilterFactoryBean ShiroFilterFactoryBean = new new ShiroFilterFactoryBean ();
 24          // 设置safety manager 
25          ShiroFilterFactoryBean.SetSecurityManager (securityManager);
26          // add Shiro interceptor 
27          / ** 
28           * Shiro built-in filter, can achieve rights associated interceptor
 29           * anon: without authentication (login) has direct access to
 30           * authc: must be certified to access
 31           * the User: If use rememberMe functions can access
 32           * PERMS: the resources resource permissions can access
 33 is           * role: the resources must be role privilege can access
 34 is           * / 
35          the Map <String, String> filterMap = new new a LinkedHashMap <> () ;
 36      / *     filterMap.put ( "/ the Add", "authc");
 37 [          filterMap.put ( "/ Update", "authc"); * / 
38 is         // filterMap.put("/test","anon");
39         filterMap.put("/login","anon");
40         //添加Shiro授权拦截器
41         filterMap.put("/add","perms[添加]");
42         filterMap.put("/foresee","perms[预言未来]");
43         filterMap.put("/update","perms[修改]");
44         filterMap.put("/delete","perms[删除]");
45         //filterMap.put("/update","perms[]");
46         //filterMap.put("/delete","perms[]");
47         //filterMap.put("/getAll","perms[]");
48         filterMap.put("/*","authc");
49          // jump to the login page 
50          shiroFilterFactoryBean.setLoginUrl ( "/ tologin" );
 51 is          // set unauthorized page 
52 is          shiroFilterFactoryBean.setUnauthorizedUrl ( "/ UNAUTH" );
 53 is          shiroFilterFactoryBean.setFilterChainDefinitionMap (filterMap);
 54 is  
55          return shiroFilterFactoryBean;
 56 is      }
 57 is      / ** 
58       * Create DefaultWebSecurityManager
 59       * / 
60      @Bean ( "securityManager" )
 61 is      public DefaultWebSecurityManager getDefaultWebSecurityManager (@Qualifier ( "UserRealm") UserRealm userRealm){
62         DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
63         //关联Realm
64         securityManager.setRealm(userRealm);
65         return securityManager;
66     }
67     /**
68      * 创建Realm
69      */
70     @Bean("userRealm")
71     public UserRealm getRealm(){
72         UserRealm userRealm=new UserRealm();
73         return userRealm;
74     }
75     /**
76       * configuration shiroDialect, for use with labels shiro thymeleaf and
 77       * / 
78      @Bean
 79      public ShiroDialect getShiroDialect () {
 80          ShiroDialect shiroDialect = new new ShiroDialect ();
 81          return shiroDialect;
 82      }
 83 }
 
package com.example.shirodemo.config;


import com.example.shirodemo.bean.Permission;
import com.example.shirodemo.bean.User;
import com.example.shirodemo.service.IPermissionService;
import com.example.shirodemo.service.IUserService;
import org.apache.shiro.SecurityUtils;
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;
import org.apache.shiro.subject.Subject;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {
    @Resource
    private IUserService userService;
    @Resource
    private IPermissionService permissionService;
    /**
     * 执行授权逻辑
     * @paramprincipalCollection 
     * @return 
     * / 
    @Override 
    protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) { 
        System.out.println ( "authorization logic execution" );
         / ** 
         * authorization to the resource 
         * / 
        SimpleAuthorizationInfo simpleAuthorizationInfo = new new SimpleAuthorizationInfo ();
          // add authorization string
         // simpleAuthorizationInfo.addStringPermission ( "the User: the Add"); 

        // -------------------- certification account 
        Subject Subject = SecurityUtils.getSubject (); 
        the User the User =(User)subject.getPrincipal();
        User user1=userService.findById(user.getId());
        if(user1==null){
            //用户名不存在
            return null;
        }
        //-------------------开始授权
        List<Permission> permissions =permissionService.getPermissionByUserId(user1.getId());
        for (Permission per : permissions) {
            simpleAuthorizationInfo.addStringPermission(per.getName());
            System.out.println("拥有权限:"+per.getName());
        }
        return simpleAuthorizationInfo;
    }

    / ** 
     * Perform authentication logic 
     * @param AuthenticationToken 
     * @return 
     * @throws of AuthenticationException
      * / 
    @Override 
    protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken AuthenticationToken) throws of AuthenticationException { 
        System.out.println ( "logic performs authentication" );
         / ** 
         * Analyzing ShiroRealm UsernamePasswordToken correct logic 
         * / 
        // 1 determines that the user name 
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) AuthenticationToken; 
        the user user =userService.findByname (usernamePasswordToken.getUsername ());
         IF (User == null ) {
             // user name does not exist 
            return  null ; 
        } 
        // determines whether the password is correct 
        return  new new SimpleAuthenticationInfo (User, user.getPassword (), "" ) ; 
    } 
}

Certification process

1   / * 
2       * log logic
 . 3       * / 
. 4      @RequestMapping ( "/ Login" )
 . 5      public String Login (the User User, the Model Model) {
 . 6          / ** 
. 7           * shiro write authentication operation using
 8           * / 
9          // 1: Get Subject 
10          the Subject Subject = SecurityUtils.getSubject ();
 . 11          // 2: user IDs and passwords package 
12 is          usernamePasswordToken usernamePasswordToken = new new usernamePasswordToken (user.getUsername (), user.getPassword ());
 13 is          // . 3: Executive Login method 
14          the try {
15              subject.login (usernamePasswordToken);
 16              model.addAttribute (User);
 . 17              // successful login
 18              // Successful jump to
 . 19              // return "the redirect: / Test"; 
20 is              return "/ Test" ;
 21 is          } the catch (UnknownAccountException E) {
 22 is              // e.printStackTrace ();
 23 is              // login user name does not exist the failure 
24              model.addAttribute ( "MSG", "user name does not exist" );
 25              return "Login" ;
 26 is          } the catch(IncorrectCredentialsException E) {
 27              // login failure error code 
28              model.addAttribute ( "MSG", "password error" );
 29              return "Login" ;
 30          }
 31 is      }
 32 }
 

Subject UserRealm go get the user data authentication logic inside the class, the authorization process is relatively simple and you can see the code above,

     Shiro configured interceptor

 // add Shiro interceptor
27         / **
28          * Shiro built-in filter, can achieve rights associated interceptor
29          * anon: without authentication (login) has direct access to
30          * authc: must be certified to access
31          * the User: If you are using rememberMe functions can access
32          * PERMS: the resources resource permissions can access
33          * role: the resources must be role permissions can access
34          * /

      Spring Security

In addition to not be divorced from Spring, shiro functions it has. And Spring Security for Oauth, OpenID also has support, Shiro will need to manually achieve. Spring Security more fine-grained permissions, after all, Spring Security is Spring family.

 

Note:

OAuth between the "client" and "service providers", set up a layer of authorization (authorization layer). "Client" can not log in directly to "service providers" can only login authorization layer, in order to distinguish between the user and the client area. "Client" Registration Authority layer with tokens (token), and passwords for different users. Users can login time, specify the authorized level of competence and the token is valid.

After the "client" login authorization layer, "Service Provider" under the authority of the scope and validity of the token to the "client" user data stored in the open.

 

The first part is the OpenID authentication system, namely how to URI to authenticate the user's identity. The current sites are relying on user name and password to login authentication, which means that we all need to register a user name and password for each site, even if you use the same password. If you use OpenID, your website address (URI) is your user name, and your password is stored on a secure OpenID service website (OpenID service you can build a website yourself, you can also choose a trusted OpenID service website to complete the registration).

And identity service providers as well as ⅥeID, ClaimID, CardSpace, Rapleaf, Trufina ID Card OpenID same attributes, etc., where the application ⅥeID general account of the most widely used.

 

Guess you like

Origin www.cnblogs.com/zoli/p/11236799.html