Shiro框架學習(一)

Shiro認證的流程

這裏寫圖片描述

首先創建一個Maven項目
導入Shiro與Junit的依賴

  <dependencies>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
    </dependencies>

項目代碼

package com.imooc.test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

public class AuthenticationTest {
   SimpleAccountRealm simpleAccountRealm =  new SimpleAccountRealm();
    @Before
    public void addUser(){
        simpleAccountRealm.addAccount("test","123456");
    }
    @Test
    public void AuthenticationTest(){
        //構建SecurityManager環境
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(simpleAccountRealm);
        //主體提交認證請求
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("test", "123456");
        subject.login(token);
        System.out.println("isAuthentication:"+subject.isAuthenticated());
        subject.logout();
        System.out.println("isAuthentication:"+subject.isAuthenticated());
    }
}

運行結果
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章