Home > Article > Backend Development > Apache Shiro User Manual (4) Realm Implementation
Apache Shiro User Manual (4) Realm Implementation
It is mentioned in the internal implementation mechanism of authentication and authorization, and the final processing will be handed over to Real for processing. Because in Shiro, the user, role and permission information in the application is ultimately obtained through Realm. Normally, the verification information Shiro needs is obtained directly from our data source in Realm. It can be said that Realm is a DAO dedicated to the security framework.
1. Authentication implementation
As mentioned above, Shiro’s authentication process will eventually be handed over to Realm for execution, and at this time it will be called Realm's getAuthenticationInfo(token) method.
This method mainly performs the following operations:
1. Check the token information submitted for authentication
2. Obtain the data from the data source (usually a database) based on the token information Obtain user information
3. Verify the matching of user information.
4. If the verification is passed, an AuthenticationInfo instance encapsulating user information will be returned.
5. If verification fails, AuthenticationException exception information will be thrown.
What we need to do in our application is to customize a Realm class, inherit the AuthorizingRealm abstract class, overload doGetAuthenticationInfo (), and rewrite the method of obtaining user information.
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; User user = accountManager.findUserByUserName(token.getUsername()); if (user != null) { return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName()); } else { return null; } }
2. Authorization Implementation
The authorization implementation is very similar to the authentication implementation. In our customized Realm, overload the doGetAuthorizationInfo() method and rewrite the method of obtaining user permissions. Can.
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String userName = (String) principals.fromRealm(getName()).iterator().next(); User user = accountManager.findUserByUserName(userName); if (user != null) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); for (Group group : user.getGroupList()) { info.addStringPermissions(group.getPermissionList()); } return info; } else { return null; } }
The above is the content of the Realm implementation in the Apache Shiro User Manual (4). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!