shiro-自定义Realm

自定义Realm

若想自定义realm只需要实现AuthorizingRealm这个类
在这里插入图片描述

这个AuthorizingRealm是个抽象类,其中它自己有doGetAuthorizationInfo(授权)这个方法,它继承的AuthentcatingRealm中有doGetAuthenticationInfo(认证)这个方法

package com.jing.realm;

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;

public class CustomRealm extends AuthorizingRealm {
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户名
        String username = (String) token.getPrincipal();
        System.out.println("username = " + username);
        // 这里直接将用户名写死了,进行判断
        if ("admin".equals(username)) {
            // 创建一个AuthenticationInfo接口的实现类SimpleAuthenticationInfo
            // 参数1:用户名,参数2:密码,参数3:realmName
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("admin", "123456",this.getName());
            return authenticationInfo;
        }
        return null;
    }
}

在这里插入图片描述

package com.jing.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

public class CustomAuthenticatorRealm {
    public static void main(String[] args) {

        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        securityManager.setRealm(new CustomRealm());

        SecurityUtils.setSecurityManager(securityManager);

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
        try {
            boolean authenticated = subject.isAuthenticated();
            System.out.println("authenticated = " + authenticated);
            subject.login(token);
            authenticated = subject.isAuthenticated();
            System.out.println("authenticated = " + authenticated);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值