shiro1

1.Shiro can help us: authentication, authorization, encryption, session management, integration with Web, caching.

2. Authentication (Authentication) : authentication / login, verify that the user is not have the appropriate status, such as the account password;

3. the Authorization (Authorization) : authorization, ie permission to verify, verify that a user has authenticated a privilege; that is to determine 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;

4. the Session Manager (Session Management) : 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;

5. The Cryptography (encryption) : encryption, secure data, such as encrypted passwords stored in the database, instead of storing the plaintext;

6. Web Support : Web support can be very easily integrated into the Web environment;

7.Caching: cache, such as users log in, their user information, with roles / permissions do not have to check every time, this can increase efficiency;

8. Concurrency : shiro support concurrent verification multithreaded applications, such as opening that is another thread in a thread, permissions can be automatically propagated in the past;

9. The Testing : providing a test support;

10. The the Run of As : allowing a user pretends to another user (if they allow) the identity of access;

11. Remember Me : Remember me, this is a very common feature, ie after the first login, then do not come back next time logged.

Note: Shiro does to maintain user, maintenance authority; these need to design our own / offer; then injected to Shiro through the corresponding interface can be.

12.shiro external architecture

 

 

 Objects to interact directly with the application code is Subject, that is Shiro's external API core is Subject; meaning that each API:

Subject : Objects body, the application code direct interaction is Subject, that is outside the core API Shiro is the Subject, on behalf of the current "user", the user is not necessarily a specific person, and whatever the current application is interactive Subject, such as web crawlers, robots; that is an abstract concept; all are bound to Subject SecurityManager, SecurityManager entrusted to interact with all of the Subject will ; be the Subject considered a facade; SecurityManager is the actual performer;

SecurityManager : security manager; that is, all safety-related operations will interact with the SecurityManager; and it manages all Subject ; we can see it is the core of Shiro, which is responsible for interacting with other components behind the introduction of, if studied SpringMVC, you can see it as DispatcherServlet front controller;

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.

That is fundamentally shiro:

For us, that is to say, a simple application Shiro:

1, the application code to perform authentication and authorization by Subject, and Subject commissioned to SecurityManager;

2, we need to Shiro of SecurityManager injection Realm, so that SecurityManager to get legitimate users and their privileges to judge .

From some of the content above you can also easily see Shiro does not provide maintenance user / permissions, but by Realm allows developers to inject yourself.

13.shiro internal structure

 

 

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

The SecurityManager : the equivalent of SpringMVC 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.

Authenticator : authentication, a body responsible for certification, which is an extension point, if you feel bad Shiro default, you can customize to achieve ; it requires authentication policy (Authentication Strategy), that is considered under what circumstances the user authentication passed; ( custom authentication policy)

Authrizer : authorizer, or access controller , for determining whether the subject has permission to perform the corresponding operation; i.e., a control function which user can access the application;

Realm : there may be one or more of the realm, can be considered a security entity data source, i.e. for obtaining the secure entity ; JDBC can be achieved, LDAP may be achieved, or the like to achieve a memory; provided by a user ;

Note: Shiro do not know your user / permissions are stored and in what format which is stored in; so we generally in the application needs to implement their own Realm;

SessionManager : If you wrote a Servlet should know the concept of the Session, Session does need someone to manage its life cycle, this component is SessionManager; and Shiro can be used not only in a Web environment, also be used as an ordinary JavaSE environment, EJB and other environmental; all of it, Shiro to abstract an own Session to manage data exchange between the body and the application; this is the case, for example, we in the Web environment with the beginning is a Web server; then turn on stage EJB server; then want the session data of both servers in one place, this time they can realize their distributed session (such as the data into Memcached server);

SessionDAO : DAO we have used, data access objects for CRUD session, for example, we want to Session saved to the database, you can implement your own SessionDAO, written by such as JDBC database; for example, want to put the Memcached Session, you can realize their Memcached SessionDAO; in addition SessionDAO can use the cache cache to improve performance;

The CacheManager : a cache controller, such as cache to manage users, roles, rights and the like; for data to change only rarely, into the cache can improve performance of access

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

14. Filter

When Shiro is applied to the web project, Shiro will automatically create some default filters for filtering client requests . For example, it related to authentication, authorization, and so on. The default interceptor can refer org.apache.shiro.web.filter.mgt.DefaultFilter enumerator interceptor:

anon org.apache.shiro.web.filter.authc.AnonymousFilter
authc org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasic org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
perms org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
port org.apache.shiro.web.filter.authz.PortFilter
rest org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
roles org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
ssl org.apache.shiro.web.filter.authz.SslFilter
user org.apache.shiro.web.filter.authc.UserFilter
logout org.apache.shiro.web.filter.authc.LogoutFilter
noSessionCreation org.apache.shiro.web.filter.session.NoSessionCreationFilter

 

/admins/**=anon # 表示该 uri 可以匿名访问

/admins/**=auth # 表示该 uri 需要认证才能访问

/admins/**=authcBasic # 表示该 uri 需要 httpBasic 认证

/admins/**=perms[user:add:*] # 表示该 uri 需要认证用户拥有 user:add:* 权限才能访问

/admins/**=port[8081] # 表示该 uri 需要使用 8081 端口

/admins/**=rest[user] # 相当于 /admins/**=perms[user:method],其中,method 表示 get、post、delete 等

/admins/**=roles[admin] # 表示该 uri 需要认证用户拥有 admin 角色才能访问

/admins/**=ssl # 表示该 uri 需要使用 https 协议

/admins/**=user # 表示该 uri 需要认证或通过记住我认证才能访问

/logout=logout # 表示注销,可以当作固定配置

note:

anon, authcBasic, auchc, user authentication is a filter.

perms, roles, ssl, rest, port filter is authorized.

15.Shiro certification process can be exceptions

Subject subject = SecurityUtils.getSubject();
if(!subject.isAuthenticated()){
  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName,password);
  usernamePasswordToken.setRememberMe(true);
  try{
     subject.login(usernamePasswordToken);
  }catch (UnknownAccountException e){
     System.out.print("账户不存在:"+e.getMessage());
  }catch (LockedAccountException e){
     System.out.print("账户被锁定:"+e.getMessage());
  }catch (IncorrectCredentialsException e){
     System.out.print("密码不匹配:"+e.getMessage());
  }
}

 16. Configure Realm Realm authentication and multi-strategy

/ *** 
* Configuration Realm 
* * / 
@Bean 
Realm UserRealm () { 
    TestRealm UserRealm new new TestRealm = (); 
    return UserRealm; 
} 
/ * * * 
 * Test The realm 
 * @return 
 * / 
@Bean 
Realm testRealm () { 
    return new new TestRealm (); 
} 
 
/ ** 
 * multi-Realm authentication policy 
 * @return 
 * / 
@Bean 
the Authenticator Authenticator () { 
    modularRealmAuthenticator modularRealmAuthenticator new new modularRealmAuthenticator = (); 
    // can be verified by using a validated way 
    modularRealmAuthenticator.setAuthenticationStrategy (atLeastOneSuccessfulStrategy ());  
    return modularRealmAuthenticator;
} 
/ ** 
 * Reaml are often used by all considered as the authentication policy 
 * @return 
 * / 
@Bean 
AuthenticationStrategy allSuccessfulStrategy () { 
    AllSuccessfulStrategy allSuccessfulStrategy new new AllSuccessfulStrategy = (); 
    return allSuccessfulStrategy; 
} 
/ ** 
 * Multi reaml all even by a certified by acting as policy 
 * @return 
 * / 
@Bean 
AuthenticationStrategy atLeastOneSuccessfulStrategy () { 
    atLeastOneSuccessfulStrategy atLeastOneSuccessfulStrategy new new atLeastOneSuccessfulStrategy = (); 
    return atLeastOneSuccessfulStrategy; 
}

 17. Configure Cache

@Bean 
public EhCacheManager ehCacheManager () { 
    EhCacheManager in EhCacheManager = new (); 
    em.setCacheManager (CacheManager ()); 
    em.setCacheManagerConfigFile ( "classpath: ehcach.xml"); 
    in return; 
} 
 
@Bean ( "cacheManager2") 
CacheManager CacheManager () { 
    return CacheManager.create (); 
}

18. Configure securityManager

/ *** 
 * Configuration securityManager 
 * @return 
 * / 
@Bean 
public securityManager the SecurityManager () { 
    DefaultWebSecurityManager securityManager new new DefaultWebSecurityManager = (); 
    // set a single realm. 
    SecurityManager.setRealm (UserRealm ()); 
    // plurality authorization realm by a verification can be as long as 
    List <Realm> = new new Realms the ArrayList <> (); 
    realms.add (UserRealm ()); 
    realms.add (UserRealm ()); 
    securityManager.setRealms (Realms); 
    // custom cache implemented using Redis 
// IF (Constant.CACHE_TYPE_REDIS.equals (cacheType)) { 
// securityManager.setCacheManager (rediscacheManager ()); 
// the else {}
        securityManager.setCacheManager (ehCacheManager ()); 
    //} 
    //securityManager.setSessionManager (SessionManager ()); 
    // multi Reaml certification strategy 
    securityManager.setAuthenticator (Authenticator ()); 
    return securityManager; 
}

 19. Configure shiroFilterFactoryBean fact, the rules Filter

/ *** 
 * Configuration shiroFilterFactoryBean 
 * configuration basic filtering rules 
 * @param securityManager 
 * @return 
 * / 
@Bean 
ShiroFilterFactoryBean shiroFilterFactoryBean (the SecurityManager securityManager) { 
    ShiroFilterFactoryBean shiroFilterFactoryBean new new ShiroFilterFactoryBean = (); 
    // Configuration Manager 
    shiroFilterFactoryBean.setSecurityManager (securityManager) ; 
    // configure login \ login success page \ failed on landing page 
    shiroFilterFactoryBean.setLoginUrl ( "/ login.html"); 
    shiroFilterFactoryBean.setSuccessUrl ( "/ index.html"); 
    shiroFilterFactoryBean.setUnauthorizedUrl ( "/ 403.html"); 
    / / configure the basic policy rules, those who need access to work rights in the order, configure directly 
    // support Ant style
    LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
    filterChainDefinitionMap.put("/login.html","anon");
    filterChainDefinitionMap.put("**/login/**","anon");
    filterChainDefinitionMap.put("/css/**", "anon");
    filterChainDefinitionMap.put("/js/**", "anon");
    filterChainDefinitionMap.put("/fonts/**", "anon");
    filterChainDefinitionMap.put("/img/**", "anon");
    filterChainDefinitionMap.put("/docs/**", "anon");
    filterChainDefinitionMap.put("/druid/**", "anon");
    filterChainDefinitionMap.put("/upload/**", "anon "); 
    // URL configured canceled
    filterChainDefinitionMap.put (" / Files / ** "," anon ");
    filterChainDefinitionMap.put("/logout", "logout");
    //
    filterChainDefinitionMap.put("/**", "authc");
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
    return shiroFilterFactoryBean;
}
 

20. The authentication code flow

1, the first call Subject.login (token) to log in, it will automatically be delegated to SecurityManager

2, SecurityManager responsible for real authentication logic; it will be commissioned to authenticate to the Authenticator (authenticator);

3, Authenticator (authenticator) is the real identity verifier, Shiro API in the core authentication entry point, where you can insert your own custom implementation;

4, Authenticator may entrust a multi Realm identity to the corresponding AuthenticationStrategy (authentication policies) verification, the default ModularRealmAuthenticator calls AuthenticationStrategy multi Realm authentication;

5, the corresponding token Authenticator will pass Realm, the Realm obtain identity verification information, if there is no return / exception is thrown by an authentication failed. Here you can configure multiple Realm, will be accessed in the corresponding order and strategy.

21. Authentication example

 

 22.Realm authentication and authorization

class TestRealm the extends AuthorizingRealm {public 
    @Override 
    protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken AuthenticationToken) throws AuthenticationException { 
        // About JWT considerations, password or want, but at the same time you want to use multiple Reamle, 
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) AuthenticationToken; 
        String username = usernamePasswordToken.getUsername (); 
        of System.out.print ( "query the username yoghurt"); 
        IF ( "none" .equals (username)) { 
           the throw new new UnknownAccountException ( "user does not exist"); 
        } 
        // authentication entity information , the object can be placed, after use can be taken out at any time, JSP tags can also go directly to the object 
        Object Principal = username;  
        acquired // database password
        Object = Credentials "1234567"; 
        objects // package with data, Shiro will take this object and passed in comparison Token password, verify that the login is successful 
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo (principal, credentials, getName ()); 
        simpleAuthenticationInfo return; 
    } 
    // this method is used to authorize the 
    // query whether the landing is entitled to limit the query If you set the cache will only check once 
    @Override 
    protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) { 
        // get the inside of is landing certification SimpleAuthenticationInfo info = new SimpleAuthenticationInfo (username, password, getName ()); the first parameter 
        Object = principalCollection.getPrimaryPrincipal the user (); 
        // will be converted to its own users, acquired from the database to the user the role privileges
        MenuService menuService = ApplicationContextRegister.getBean // (MenuService.class); 
        // here only query the privileges 
        // the Set <String> PERMS = menuService.listPerms (userId); 
        SimpleAuthorizationInfo info = new new SimpleAuthorizationInfo (); 
        // put in to 
        //info.setStringPermissions(perms); 
        return info; 
    } 
}

 23.

More than 5.2 Realm authentication policy: AuthenticationStrategy

• AuthenticationStrategy default implementation of the interface:

• FirstSuccessfulStrategy: As long as there is a Realm authentication is successful to return only the first successful authentication Realm authentication information, the other ignored;

• AtLeastOneSuccessfulStrategy: As long as there is a Realm authentication is successful can be, and different FirstSuccessfulStrategy, will return all Realm authentication is successful authentication information;

• AllSuccessfulStrategy: All Realm authentication is successful to be successful, and returns all Realm authentication is successful authentication information, if there is a failure would have failed. • ModularRealmAuthenticator default strategy is AtLeastOneSuccessfulStrategy

Code permissions ways:

 

 Rules rights provisions:

 

 

 

 

6.3 JSP tags:

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/cainame/p/11490528.html