欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

shiro自定义realm

程序员文章站 2022-05-16 12:03:20
我们知道shiro这个框架提供了信息认证和授权的功能性接口,但是shiro是不会帮我们维护数据的,shiro中的用户信息以及用户所对应的权限都是需要我们从数据库查询出来然后传给shiro相对应的接口,因此单单一个jdbcRealm已经无法满足我们的需求了,因为jdbcRealm是写死了的,里面查询的 ......

我们知道shiro这个框架提供了信息认证和授权的功能性接口,但是shiro是不会帮我们维护数据的,shiro中的用户信息以及用户所对应的权限都是需要我们从数据库查询出来然后传给shiro相对应的接口,因此单单一个jdbcrealm已经无法满足我们的需求了,因为jdbcrealm是写死了的,里面查询的只能是users表。所以,为了满足我们的需求,我们必须自定义realm,从而才能不局限于一张表的数据查询,还能加自己的一些判断逻辑。下面讲讲怎么实现自定义realm。

自定义realm首先我们就要写一个realm,而这个realm我们一般要继承authorizingrealm类,因为这个类里面就有实现接收用户认证信息和接收用户权限信息的两个方法,而realm就是用来从数据库查询这些数据的。下面是我自定义的realm:

package com.wujianwu.realm;

import java.sql.connection;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;

import javax.sql.datasource;

import org.apache.shiro.authc.authenticationexception;
import org.apache.shiro.authc.authenticationinfo;
import org.apache.shiro.authc.authenticationtoken;
import org.apache.shiro.authc.simpleauthenticationinfo;
import org.apache.shiro.authz.authorizationinfo;
import org.apache.shiro.realm.authorizingrealm;
import org.apache.shiro.subject.principalcollection;

import com.wujianwu.bean.user;

public class myrealm  extends authorizingrealm{

    private datasource datasource;
    @override
    public string getname() {
        // todo auto-generated method stub
        return "myrealm";
    }
    @override
    protected authenticationinfo dogetauthenticationinfo(authenticationtoken token) throws authenticationexception {
        string username = (string) token.getprincipal();
        simpleauthenticationinfo info = null;
        
        user user = getuserinfo(username);
        system.out.println("用户名"+user.getusername()+"==============");
        info = new simpleauthenticationinfo(user.getusername(), user.getpassword(),getname());
        
        return info;
    }
    
    @override
    protected authorizationinfo dogetauthorizationinfo(principalcollection arg0) {
        // todo auto-generated method stub
        return null;
    }
    public datasource getdatasource() {
        return datasource;
    }
    public void setdatasource(datasource datasource) {
        this.datasource = datasource;
    }
    
    private user getuserinfo(string username){
        user user = new user();
        string sql = "select username,password from users where username=?";
        connection connection = null;
        preparedstatement statement = null;
        resultset set = null;
        try {
            connection = datasource.getconnection();
            statement = connection.preparestatement(sql);
            statement.setstring(1, username);
            set = statement.executequery();
            
            if(set.next()) {
                string username1 = set.getstring(1);
                string password = set.getstring(2);
                user.setpassword(password);
                user.setusername(username1);
            }    
        } catch (sqlexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }finally {
            closeall(connection, set, statement);
        }
        return user;
    }
    
    private void closeall(connection conn,resultset set,preparedstatement statement) {
        try {
            if(set != null) {
                set.close();
            }
            if(statement != null) {
                statement.close();
            }
            if(conn != null) {
                conn.close();
            }
        } catch (sqlexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }

}

可以看到,我的realm只编写了接收认证信息这个方法的代码,毕竟我们还没学到授权= =。我这里其实也是模仿了jdbcrealm,在myrealm中设置了数据源的属性,然后通过subject.login(token)中传过来的token来获取用户输入的身份,然后根据身份区数据库查询出用户的凭证和其他信息(可以看到这里我用的还是users表,是因为我太懒了,直接用现有的表,当然这里是可以查询任何你想要查询的表的!),然后用simpleauthenticationinfo封装用户的信息返回给shiro去认证,实际上这里我们只是从数据库将用户数据查询出来封装然后返回给shiro而已,最终的认证还是shiro帮我们完成的。(注意,记得关闭资源,如我代码中的closeall方法)

好了,写好了自定义的realm,我们当然还需要把它配置到securitymanager中去,下面是配置文件shiro.ini的具体实现:

[main]
datasource=com.mchange.v2.c3p0.combopooleddatasource
datasource.driverclass=com.mysql.jdbc.driver
datasource.jdbcurl=jdbc:mysql://localhost:3306/test
datasource.user=root
datasource.password=root
myrealm=com.wujianwu.realm.myrealm
myrealm.datasource=$datasource
securitymanager.realm=$myrealm

可以看到,我们配置了myrealm中的datasource,并将最终的myrealm设置到securitymanager中去,从而实现了我们自定义realm的配置

然后就是测试了,还是那一套熟悉的流程= =,代码如下(这次懒得写注释了):

package com.wujianwu.test;

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.mgt.securitymanager;
import org.apache.shiro.subject.subject;
import org.apache.shiro.util.factory;
import org.slf4j.logger;
import org.slf4j.loggerfactory;

public class testmyrealm {

    private static final logger logger = loggerfactory.getlogger(testmyrealm.class);
    public static void main(string[] args) {
        factory<securitymanager> factory = new inisecuritymanagerfactory("classpath:shiro.ini");
        securitymanager securitymanager = factory.getinstance();
        securityutils.setsecuritymanager(securitymanager);
        subject subject = securityutils.getsubject();
        usernamepasswordtoken token = new usernamepasswordtoken("zhangsan", "123456");
        try {
            subject.login(token);
            if(subject.isauthenticated()) {
                logger.info("用户登录认证成功");
            }
        } catch (authenticationexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
            logger.error("用户名或者密码错误,登录失败");
        }
    }
}

数据库中对应的数据如下:

shiro自定义realm

运行完控制台打印如下:

2019-07-28 16:24:50,001 info [com.mchange.v2.log.mlog] - mlog clients using slf4j logging. 
2019-07-28 16:24:50,405 info [com.mchange.v2.c3p0.c3p0registry] - initializing c3p0-0.9.5.2 [built 08-december-2015 22:06:04 -0800; debug? true; trace: 10] 
2019-07-28 16:24:50,520 info [org.apache.shiro.config.inisecuritymanagerfactory] - realms have been explicitly set on the securitymanager instance - auto-setting of realms will not occur. 
2019-07-28 16:24:50,545 info [com.mchange.v2.c3p0.impl.abstractpoolbackeddatasource] - initializing c3p0 pool... com.mchange.v2.c3p0.combopooleddatasource [ acquireincrement -> 3, acquireretryattempts -> 30, acquireretrydelay -> 1000, autocommitonclose -> false, automatictesttable -> null, breakafteracquirefailure -> false, checkouttimeout -> 0, connectioncustomizerclassname -> null, connectiontesterclassname -> com.mchange.v2.c3p0.impl.defaultconnectiontester, contextclassloadersource -> caller, datasourcename -> 2zm2h6a4fg70y51p9sdrv|7e0ea639, debugunreturnedconnectionstacktraces -> false, description -> null, driverclass -> com.mysql.jdbc.driver, extensions -> {}, factoryclasslocation -> null, forceignoreunresolvedtransactions -> false, forcesynchronouscheckins -> false, forceusenameddriverclass -> false, identitytoken -> 2zm2h6a4fg70y51p9sdrv|7e0ea639, idleconnectiontestperiod -> 0, initialpoolsize -> 3, jdbcurl -> jdbc:mysql://localhost:3306/test, maxadministrativetasktime -> 0, maxconnectionage -> 0, maxidletime -> 0, maxidletimeexcessconnections -> 0, maxpoolsize -> 15, maxstatements -> 0, maxstatementsperconnection -> 0, minpoolsize -> 3, numhelperthreads -> 3, preferredtestquery -> null, privilegespawnedthreads -> false, properties -> {user=******, password=******}, propertycycle -> 0, statementcachenumdeferredclosethreads -> 0, testconnectiononcheckin -> false, testconnectiononcheckout -> false, unreturnedconnectiontimeout -> 0, useroverrides -> {}, usestraditionalreflectiveproxies -> false ] 
用户名zhangsan==============
2019-07-28 16:24:50,842 info [org.apache.shiro.session.mgt.abstractvalidatingsessionmanager] - enabling session validation scheduler... 
2019-07-28 16:24:50,847 info [com.wujianwu.test.testmyrealm] - 用户登录认证成功 

可以看到,确确实实调用到了我们自定义的realm(因为打印出了我在myrealm中想要输出的东西“用户名zhangsan==============”)。

因为我们这里只是单单一个shiro框架,所以我们在查询数据库数据时才用了jdbc那一套流程,之后进行ssm整合时就不用这么麻烦了,直接在realm中注入mapper,然后调mapper的方法查询就行了,当然这些都是题外话,以后实现了我也会更新到博客中。

以上就是自定义realm的具体实现,有什么补充或修改的请在评论区留言,谢谢!