Apache Shiro user manual of four Realm implementation

  • 2020-05-09 19:47:24
  • OfStack

It is mentioned in the internal implementation mechanisms of authentication and authorization, and the final processing will be handed over to Real for processing. Because in Shiro, it is ultimately through Realm that the user, role, and permission information in the application is obtained. Typically, in Realm, the validation information required by Shiro is obtained directly from our data source. It can be said that Realm is DAO dedicated to security frameworks.

1. Authentication implementation

As mentioned earlier, Shiro's authentication process is eventually handed over to Realm, which calls Realm's getAuthenticationInfo(token) method.
The method mainly performs the following operations:
1. Check the submitted token information for authentication
2. Get user information from a data source (usually a database) based on token information
3. Verify the matching of user information.
4. Verify that an AuthenticationInfo instance with user information encapsulated is returned.
5. If validation fails, AuthenticationException exception information is thrown.

All we need to do in our application is to customize an Realm class, inherit from the AuthorizingRealm abstract class, override the doGetAuthenticationInfo () method, and override the method to get 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 custom Realm, we override the doGetAuthorizationInfo() method and override the method to obtain user privileges.


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;
  }
}


Related articles: