Shiro (2)-Architecture and Configuration

Source: Internet
Author: User
Document directory
  • Isremembered

Authentication is the process in which the user can confirm the identity of the login user.

To use Shiro authentication, perform the following steps:

1. Obtain the authentication and creden。 of the subject.

// let's login the current user so we can check against roles and permissions:        if (!currentUser.isAuthenticated()) {            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");            token.setRememberMe(true);

2. Submit the authentication and creden。 to the authentication system.

Subject currentUser = SecurityUtils.getSubject();currentUser.login(token);

3. Determine whether access is allowed, retry authentication, or block access.

try {                currentUser.login(token);            } catch (UnknownAccountException uae) {                log.info("There is no user with username of " + token.getPrincipal());            } catch (IncorrectCredentialsException ice) {                log.info("Password for account " + token.getPrincipal() + " was incorrect!");            } catch (LockedAccountException lae) {                log.info("The account for username " + token.getPrincipal() + " is locked.  " +                        "Please contact your administrator to unlock it.");            }            // ... catch more exceptions here (maybe custom ones specific to your application?            catch (AuthenticationException ae) {                //unexpected condition?  error?            }

The remember me function includes two methods. One is

Isremembered
boolean isRemembered()
Non-Anonymous login users can remember the last topic information.
Isauthenticated
boolean isAuthenticated()
Valid creden are required to log on to the system. Otherwise, the value is false.
 
Authorized Operation
An example of authorization is whether a page can be accessed, a button can be operated, and data can be edited.
How to Use Authorization in Shiro
1. Programming
Determine whether there is an administrator role
if (currentUser.hasRole("admin")) {
Determine whether a user has the printing permission
Permission printPermission = new PrinterPermission(“laserjet3000n”,“print”);
If (currentUser.isPermitted(printPermission)) {    //do one thing (show the print button?)} else {    //don’t show the button?}

You can also use a string for verification.

String perm = “printer:print:laserjet4400n”;if(currentUser.isPermitted(perm)){    //show the print button?} else {    //don’t show the button?}

 

2. Use the annotation Method
Determine whether a user has the permission to create an account
//Will throw an AuthorizationException if none//of the caller’s roles imply the Account //'create' permission\u000B@RequiresPermissions(“account:create”)public void openAccount( Account acct ) {     //create the account}
Determine the user role. If the user meets the role, use the corresponding method.
//Throws an AuthorizationException if the caller//doesn’t have the ‘teller’ role:@RequiresRoles( “teller” )public void openAccount( Account acct ) {     //do something in here that only a teller    //should do}
3. Use JSP taglib
Determine whether a user has administrative permissions
<%@ taglib prefix=“shiro” uri=http://shiro.apache.org/tags %>
 
Shiro:
Take a look at the official figure

The application calls subject (topic). The topic can be a user or another system that interacts with the system. The topic is bound to Shiro permission management, securitymanager (Security Management ), it controls security operations related to topics. Realm is a bridge between security and data. It encapsulates configuration information such as Dao, you can specify the connected data source, or you can use other authentication methods, such as LDAP.

Then let's take a look at the detailed architecture diagram:

Subject (Org. Apache. Shiro. Subject. Subject)

Topic: third parties that interact with the system, such as users, cron services, and third-party applications.

Securitymanager (Org. Apache. Shiro. Mgt. securitymanager)

Shiro is the core of the system. It coordinates the operations, verification, and configuration used by the subject.

Authenticator (Org. Apache. Shiro. authc. authenticator)

The Authentication Component verifies the identity of users attempting to log on to the system. It contains an authentication strategy

(Org. Apache. Shiro. authc. Pam. authenticationstrategy) component. Configure conditions for successful and failed verification.

Authorizer (Org. Apache. Shiro. authz. Authorizer)

Authorization component refers to the mechanism by which a user accesses a specific application.

Sessionmanager (Org. Apache. Shiro. session. Mgt. sessionmanager)

Manage how a session creates a lifecycle. Sessiondao is a persistent operation for managing meeting data: sessiondao (Org. Apache. Shiro. session. Mgt. EIS. sessiondao), which indicates executing the CRUD operation of sessionmanager.

Cachemanager (Org. Apache. Shiro. cache. cachemanager)

Cache Management module.

Cryptography (Org. Apache. Shiro. crypto .*)

Encryption module.

Realms (Org. Apache. Shiro. realm. realm)

A bridge that can be processed in multiple ways.

 

Multiple configuration methods:

Configure with spring, JBoss, guice, etc.

1. Programming Configuration

For example:

Realm realm = //instantiate or acquire a Realm instance.  We'll discuss Realms later.SecurityManager securityManager = new DefaultSecurityManager(realm);//Make the SecurityManager instance available to the entire application via static memory:SecurityUtils.setSecurityManager(securityManager);

2. sessionmanager object graph

If you want to use sessionmanager to configure custom sessiondao information, perform custom session management

...DefaultSecurityManager securityManager = new DefaultSecurityManager(realm);SessionDAO sessionDAO = new CustomSessionDAO();((DefaultSessionManager)securityManager.getSessionManager()).setSessionDAO(sessionDAO);...

3. ini configuration

1) Create an INI from securitymanager

You can read ini configuration file information in multiple ways, such as file systems and class paths.

import org.apache.shiro.SecurityUtils;import org.apache.shiro.util.Factory;import org.apache.shiro.mgt.SecurityManager;import org.apache.shiro.config.IniSecurityManagerFactory;...Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");SecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);

2) read from the INI instance

Similar to properties

import org.apache.shiro.SecurityUtils;import org.apache.shiro.util.Factory;import org.apache.shiro.mgt.SecurityManager;import org.apache.shiro.config.Ini;import org.apache.shiro.config.IniSecurityManagerFactory;...Ini ini = new Ini();//populate the Ini instance as necessary...Factory<SecurityManager> factory = new IniSecurityManagerFactory(ini);SecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);

After loading, you can operate on the ini configuration.

4. ini configuration

Each node is independent and cannot be repeated. Annotations can be used # or;

Configuration example

# =======================# Shiro INI configuration# =======================[main]# Objects and their properties are defined here, # Such as the securityManager, Realms and anything# else needed to build the SecurityManager[users]# The 'users' section is for simple deployments# when you only need a small number of statically-defined # set of User accounts.[roles]# The 'roles' section is for simple deployments# when you only need a small number of statically-defined# roles.[urls]# The 'urls' section is used for url-based security# in web applications.  We'll discuss this section in the# Web documentation

1) [main]

Configure the sessionmanager instance and its dependencies.

Configuration example

[main]sha256Matcher = org.apache.shiro.authc.credential.Sha256CredentialsMatchermyRealm = com.company.security.shiro.DatabaseRealmmyRealm.connectionTimeout = 30000myRealm.username = jsmithmyRealm.password = secretmyRealm.credentialsMatcher = $sha256MatchersecurityManager.sessionManager.globalSessionTimeout = 1800000

Define an object

[main]myRealm = com.company.shiro.realm.MyRealm...

Simple attribute settings

...myRealm.connectionTimeout = 30000myRealm.username = jsmith...

The configuration information will be transferred to the corresponding set method.

...myRealm.setConnectionTimeout(30000);myRealm.setUsername("jsmith");...

Reference Value

You can use the $ symbol to reference an instance of the previously defined object.

...sha256Matcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher...myRealm.credentialsMatcher = $sha256Matcher...

Nested attributes

...securityManager.sessionManager.globalSessionTimeout = 1800000...

Will be injected into the following program

securityManager.getSessionManager().setGlobalSessionTimeout(1800000);

Reference other attributes

sessionListener1 = com.company.my.SessionListenerImplementation...sessionListener2 = com.company.my.other.SessionListenerImplementation...securityManager.sessionManager.sessionListeners = $sessionListener1, $sessionListener2

Key-Value configuration

object1 = com.company.some.Classobject2 = com.company.another.Class...anObject = some.class.with.a.Map.propertyanObject.mapProperty = key1:$object1, key2:$object2

2) [users]

This configuration information is valid when there are few users.

[users]admin = secretlonestarr = vespa, goodguy, schwartzdarkhelmet = ludicrousspeed, badguy, schwartz

3) [roles]

This configuration can be used if the role information is small.

[roles]# 'admin' role has all permissions, indicated by the wildcard '*'admin = *# The 'schwartz' role can do anything (*) with any lightsaber:schwartz = lightsaber:*# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with# license plate 'eagle5' (instance specific id)goodguy = winnebago:drive:eagle5

4) [URLs]

Configure accessible resource information such as URLs.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.