shiro身份验证测试

一、登录验证

1、首先在shiro.ini里准备一些用户身份/凭据,后面这里会使用数据库代替,如:

[users]  
[main]
#realm
jdbcRealm=com.learnging.system.shiro.ShiroRealm
securityManager.realm=$jdbcRealm
authc = org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authc.loginUrl = /

[urls]
/index = authc 
/a/logout = logout	

2登录测试

准备知识: (1)当运行Web应用程序时,Shiro将创建一些有用的内置过滤器实例,并且自动的在[main]部分使用。如.ini文件配置,要使用authc,先定义其使用的类,这个类必须实现AuthenticatingFilter。这里也可以使用shiro已经实现好的一些AuthenticationFilter,如PassThruAuthenticationFilter,FormAuthenticationFilter。

(2)使用shiro的.ini文件路径前一定要加CLASSPATH、URL、FILE前缀,如classpath:shiro.ini;只需把shiro.ini放在resources文件夹下,它就能自动找到shiro文件。

测试用例如下:

package learning_system;
import junit.framework.Assert;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;


public class LoginLogoutTest
{
    @Test
    public void testHelloworld()
    {
        //1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
        Factory<org.apache.shiro.mgt.SecurityManager> factory =
            new IniSecurityManagerFactory("classpath:shiro.ini");

        //2、得到SecurityManager实例 并绑定给SecurityUtils
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");

        try
        {
            //4、登录,即身份验证
            subject.login(token);
        }
        catch (AuthenticationException e)
        {
            //5、身份验证失败
        }

        Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录

        //6、退出
        subject.logout();
    }
}

web项目可以省略以上的如下代码,web容器会帮你做:

        Factory<org.apache.shiro.mgt.SecurityManager> factory =
         new IniSecurityManagerFactory("classpath:shiro.ini");
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

转载于:https://my.oschina.net/u/2427561/blog/1517454

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值