Writing in the front

In our last article, Shiro Certification Process source Code Analysis – The Initial Stage of Qi Training, we briefly analyzed Shiro’s certification process. As you can see, if you need to authenticate using information from other data sources, you need to customize a Realm that inherits the AuthorizingRealm class and implements two methods, one for authorization and the other for authentication.

In this article, we will show you how to customize a Realm object to switch authentication information sources.

Custom Reaml

/** Customize Realm objects *@authorLaifeng [email protected] *@version 1.0
 * @date2020/10/4 11 * /
public class MySqlRealm extends AuthorizingRealm {

    /** ** ** *@authorLaifeng [email protected] *@dateThe 2020-10-04 11:01:50 *@param principalCollection
     * @return org.apache.shiro.authz.AuthorizationInfo
     * @throws AuthenticationException
     * @version1.0 * /
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    /**认证
     * @authorLaifeng [email protected] *@dateThe 2020-10-04 11:01:50 *@param authenticationToken
     * @return org.apache.shiro.authz.AuthorizationInfo
     * @throws AuthenticationException
     * @version1.0 * /
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1. Obtain the user name from the token
        String principal = (String) authenticationToken.getPrincipal();

        //2. Query database by username (mock)
        if (principal == "xiangbei") {
            AuthenticationInfo authInfo = new SimpleAuthenticationInfo("xiangbei"."123".this.getName());
            return authInfo;
        }
        return null; }}Copy the code

Use custom Realms for authentication in the authenticator

/** Authentication manager *@authorLaifeng [email protected] *@version 1.0
 * @date2020/10/4 11:11 * /
public class CurrentSystemAuthenticator {
    private DefaultSecurityManager securityManager;
    public CurrentSystemAuthenticator(a) {
        // Create security manager
        securityManager = new DefaultSecurityManager();

        // Set a custom realm
        this.securityManager.setRealm(new MySqlRealm());

        // Set the security manager to the security utility class
        SecurityUtils.setSecurityManager(securityManager);

    }

    public void authenticate(String username,String password){
        // Get the current login topic
        Subject subject = SecurityUtils.getSubject();

        / / generated toeken
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        // Perform authentication
        try {
            subject.login(token);
        }catch (UnknownAccountException | IncorrectCredentialsException e) {
            System.out.println("Incorrect username or password");
        }


        // Prints the authentication status
        if (subject.isAuthenticated()){
            System.out.println(token.getPrincipal()+"Approved!");
        }else {
            System.out.println(token.getPrincipal()+"Certification failed!"); }}}Copy the code

test

The situation of passing the certification

Use case code

/** Test authentication *@authorLaifeng [email protected] *@version 1.0
 * @date2020/9/21 0:49 * /
public class TestAuthenticator {
    private  Authenticator authenticator=null;

    @Before
    public void init(a) {
        authenticator = new Authenticator();
    }

    @Test
    public void testAuth(a){

        authenticator.authenticate("xiangbei"."123"); }}Copy the code

The output

Xiangbei certified!Copy the code

The authentication fails

The certification does not pass the situation in Shiro is divided into several cases, specific can see my last article “Shiro certification process source analysis – Early qi training” on shiro certification anomaly analysis, commonly used are as follows:

  1. Incorrect account (non-existent)
  2. Password mistake
  3. Account locked
  4. Password expiration

In actual projects, for the sake of security, a prompt similar to “incorrect user name or password” is displayed for incorrect accounts and passwords to avoid account leakage.

The following is a demonstration of this situation

Use case code

/ * * *@authorLaifeng [email protected] *@version 1.0
 * @dateThe loathsome 2020/10/4 * /
public class AuthcTest {
    private CurrentSystemAuthenticator authenticator;
    @Before
    public void init(a) {
        this.authenticator = new CurrentSystemAuthenticator();
    }

    @Test
    public void testAuthc(a){
        this.authenticator.authenticate("xiangbei"."13"); }}Copy the code

The output

Incorrect username or password xiangbei authentication failed!Copy the code

Write in the last

This article will walk you through how to switch shiro authentication data sources using custom Realm objects. The integration of MySQL will be covered in a later article when SpringBoot is integrated.

The next article will briefly cover password encryption in Shiro and how to configure it for use.

Download the code for this article at github.com/code81192/a…