Shiro, apacheshiro

Source: Internet
Author: User

Shiro, apacheshiro

Realm is also mentioned in Authentication and Authorization.

Whether it is authentication or permission verification, no matter how the data exists, we need to access some data and convert it to a format that Shiro can recognize.

Generally, a data source corresponds to a Realm. Therefore, an API related to the data source is used to implement a Realm.

Generally, identity-related data and permission-related data are stored in a data source. Therefore, a Realm implementation class can perform authentication and authorization.

 

Realm can be simply interpreted as DAO.

(Although the type hirarchy digoal generated by IDEA is very beautiful, it is too big... it is still used back to eclipse ..)

If you use. ini configuration, we can define N Realm in the [main] section, but we can use explicit and implicit (implicit) you can specify the Realm for securityManager in either of the following ways (meaning the IOC container ).

Specifying the display is a common method, that is, defining the Realm and then specifying the Realm in the desired order for the securityManager.

fooRealm = com.company.foo.RealmbarRealm = com.company.another.RealmbazRealm = com.company.baz.RealmsecurityManager.realms = $fooRealm, $barRealm, $bazRealm


The display method is relatively clear. Even if we do not change the definition of Realm, we can still let the verification and authorization be executed in the Realm in the order we specified for securityManager.

For some reason (maybe there are too many Realm defined ?) If you do not want to specify securityManager. realms, you can use the implicit method.

In other words, the above configuration is changed to the following form as an implicit method:

blahRealm = com.company.blah.RealmfooRealm = com.company.foo.RealmbarRealm = com.company.another.Realm

 

The implicit method is not specified. Only define is defined. Shiro searches for all Realm configurations and assigns them to securityManager one by one.

Shiro may surprise us if we just need to slightly change the definition of Realm in implicit mode.

 

In the article about Authentication, it refers to the Shiro framework workflow when a verification request appears.

Here we will record the work that Realm is responsible for (although it is said that at the beginning of securiyManager verification, it is up to Realm to retrieve and compare data from the data source ).

Take ModularRealmAuthenticator as an example:

   protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {        AuthenticationStrategy strategy = getAuthenticationStrategy();        AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);        if (log.isTraceEnabled()) {            log.trace("Iterating through {} realms for PAM authentication", realms.size());        }        for (Realm realm : realms) {            aggregate = strategy.beforeAttempt(realm, token, aggregate);            if (realm.supports(token)) {                log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);                AuthenticationInfo info = null;                Throwable t = null;                try {                    info = realm.getAuthenticationInfo(token);                } catch (Throwable throwable) {                    t = throwable;                    if (log.isDebugEnabled()) {                        String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";                        log.debug(msg, t);                    }                }                aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);            } else {                log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);            }        }        aggregate = strategy.afterAllAttempts(token, aggregate);        return aggregate;    }

 

Before Realm starts processing the verification logic, Authenticator calls the supports Method of Realm to verify whether the current Realm supports the obtained AuthenticationToken.

Generally, Realm checks the token type. For example, in AuthenticatingRealm, it checks whether the types are the same.

public boolean supports(AuthenticationToken token) {    return token != null && getAuthenticationTokenClass().isAssignableFrom(token.getClass());}

 

In addition, in constructor of AuthenticatingRealm, the default type is

authenticationTokenClass = UsernamePasswordToken.class;


If Realm supports submitted tokens, authenticator calls the getAuthenticationInfo (token) method.

Take AuthenticatingRealm as an example (Note: final ):

public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {    AuthenticationInfo info = getCachedAuthenticationInfo(token);    if (info == null) {        //otherwise not cached, perform the lookup:        info = doGetAuthenticationInfo(token);        log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);        if (token != null && info != null) {            cacheAuthenticationInfoIfPossible(token, info);        }    } else {        log.debug("Using cached authentication info [{}] to perform credentials matching.", info);    }    if (info != null) {        assertCredentialsMatch(token, info);    } else {        log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);    }    return info;}

 

If the verification information can be obtained from the cache, the next step is to check whether the Password Matches, that is, assertCredentialsMatch (token, info ).

If no verification information exists in the cache, call the following method.

protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;

 

Here, we will not consider the cache, But what doGetAuthenticationInfo should do.

Some people (such as me) directly complete the verification in this method. When the verification passes, the SimpleAuthenticationInfo instance is returned. If the verification fails, a verification exception is thrown.

However, the following assertCredentialsMatch indicates that doGetAuthenticationInfo is not intended to be used in this way. This usage will make CredentialMatcher meaningless.

Refer to the implementation of JdbcRealm, but query and return the SimpleAuthenticationInfo instance based on the identity (user name.

Then let assertCredentialsMatch compare token and authenticationInfo.

protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {    CredentialsMatcher cm = getCredentialsMatcher();    if (cm != null) {        if (!cm.doCredentialsMatch(token, info)) {            //not successful - throw an exception to indicate this:            String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";            throw new IncorrectCredentialsException(msg);        }    } else {        throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +                "credentials during authentication.  If you do not wish for credentials to be examined, you " +                "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");    }}

 

Now that we have mentioned CredentialMatcher, let's take a look at its meaning. First, the default CredentialMatcher of AuthenticatingRealm is...

public AuthenticatingRealm() {    this(null, new SimpleCredentialsMatcher());}


If we only compare the password characters, we don't have to make such an interface (can we compare string comparison with pluggable + customizable ?)

As mentioned before, the prinal Al and Credential of the AuthenticationToken can be of any type. It is not just as simple as comparing the password characters simply by comparing them.

SimpleCredentialsMatcher is used to compare whether two credential values are the same.

Its doCredentialsMatch method returns the return value of its equals method.

protected boolean equals(Object tokenCredentials, Object accountCredentials) {    if (log.isDebugEnabled()) {        log.debug("Performing credentials equality check for tokenCredentials of type [" +                tokenCredentials.getClass().getName() + " and accountCredentials of type [" +                accountCredentials.getClass().getName() + "]");    }    if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {        if (log.isDebugEnabled()) {            log.debug("Both credentials arguments can be easily converted to byte arrays.  Performing " +                    "array equals comparison");        }        byte[] tokenBytes = toBytes(tokenCredentials);        byte[] accountBytes = toBytes(accountCredentials);        return Arrays.equals(tokenBytes, accountBytes);    } else {        return accountCredentials.equals(tokenCredentials);    }}

 

Of course, the implementation class is not just SimpleCredentialsMatcher...

 

SimpleCredentialsMatcher is also followed by HashedCredentialsMatcher, and then deprecated.

Speaking of HashedCredentialsMatcher, he just adds a salt to the password to improve security.

The hashSalted attribute is not considered, because from Shiro 1.1, salt is a non-null value returned according to the getCredentialSalt () method of SaltedAuthenticationInfo.

public HashedCredentialsMatcher() {    this.hashAlgorithm = null;    this.hashSalted = false;    this.hashIterations = 1;    this.storedCredentialsHexEncoded = true; //false means Base64-encoded}

 

Speaking of salting, You Have To Say SaltedAuthenticationInfo. This interface inherits AuthenticationInfo, that is, in addition to principal and credential, it also has a credentialsSalt.

public interface SaltedAuthenticationInfo extends AuthenticationInfo {    /**     * Returns the salt used to salt the account's credentials or {@code null} if no salt was used.     *     * @return the salt used to salt the account's credentials or {@code null} if no salt was used.     */    ByteSource getCredentialsSalt();}

 

HashedCredentialsMatcher has a default salt, which uses its principal as the salt. Later, this method was deprecated.

Shiro prohibits salt from retrieving user logon information from the data source starting from 1.1.

@Deprecatedprotected Object getSalt(AuthenticationToken token) {    return token.getPrincipal();}

This series of methods and attributes will disappear from Shiro 2.0.

 

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.