1. 程式人生 > >(三)自定義Realm

(三)自定義Realm

ssi 定義 try time public getname tid vax getc

  • 引入依賴

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.shyroke.www</groupId>
    <
artifactId>firstShiro</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>firstShiro Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <shiro.version>1.3.2</shiro.version
> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </
dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.21</version> <scope>runtime</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version> <scope>runtime</scope> </dependency> <!-- Shiro dependencies: --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> </dependencies> <build> <finalName>firstShiro</finalName> </build> </project>

  • 自定義的realm MapRealm.java
package realms;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;

public class MapRealm implements Realm {

    /**
     * userMap變量:用於存放用戶身份和憑證(用戶名和密碼)
     */
    private static Map<String, String> userMap;

    static {
        userMap = new HashMap<String, String>();
        userMap.put("user1", "value1");
        userMap.put("user2", "value2");
    }

    /**
     * 該Realm的名字
     */
    public String getName() {
        return "mapRealm";
    }

    /**
     * 該Realm支持的token類型
     */
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String userName = token.getPrincipal().toString();
        String passWord = new String((char[]) token.getCredentials());

        if (!userMap.containsKey(userName))
            throw new UnknownAccountException("用戶名錯誤");
        if (!passWord.equals(userMap.get(userName)))
            throw new IncorrectCredentialsException("密碼錯誤");

        AuthenticationInfo info = new SimpleAuthenticationInfo(userName, passWord, getName());
        return info;
    }

}

  • shiro.ini
[main]
mapRealm=realms.MapRealm
securityManager.realms=$mapRealm

[users]
yhj=123
zs=456

技術分享

  • 測試類
package test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

public class TestMain {
    public static void main(String[] args) {
        SecurityManager securityManager=new IniSecurityManagerFactory("classpath:shiro.ini").getInstance(); 
        SecurityUtils.setSecurityManager(securityManager);
        
        Subject subject=SecurityUtils.getSubject();
    
        UsernamePasswordToken token=new UsernamePasswordToken("user2","value2");
        try {
            subject.login(token);
            System.out.println(token.getUsername()+"\t"+new String((char[])token.getPassword()));
        } catch (UnknownAccountException e) {
            System.out.println(e.getMessage());
        }catch(IncorrectCredentialsException e){
            System.out.println(e.getMessage());
        }
        
    }
}
  • 具體的流程大概是:當程序執行到subject.login(token)時候,執行自定義realm即MapRealm的boolean supports(AuthenticationToken token)方法,如果該Realm支持該token返回true,繼續執行MapRealm的AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)方法,如果該Realm不支持該token返回false,拋出異常:ealm [realms.MapRealm@1cd072a9] does not support authentication token [org.apache.shiro.authc.UsernamePasswordToken - user2, rememberMe=false]
  • 結果:

技術分享

(三)自定義Realm