【笔记】05.自定义Realm实现认证

05自定义Realm实现认证

  • Shiro默认使用自带的IniRealm,IniRealm从ini配置文件中读取用户的信息,大部分情况下需要从系统的数据库中读取用户信息,所以需要自定义Realm

1.Realm接口

  • 最基础的是Realm接口,CachingRealm负责缓存处理,AuthenticatingRealm负责认证,AuthorizingRealm负责授权,通常已定义的realm继承AuthorizingRealm

2.实现步骤

1.创建项目
2.创建User类
package com.domain;
/*
@author qw
@date 2021/3/28 - 10:44
**/

import java.util.Date;

public class User {

    private Integer id;
    private String username;
    private String pwd;
    private Date createtime;

    public User(){

    }
    public User(Integer id, String username, String pwd, Date createtime) {
        this.id = id;
        this.username = username;
        this.pwd = pwd;
        this.createtime = createtime;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
}
3.创建UserService
package com.service;
/*
@author qw
@date 2021/3/28 - 10:44
**/

import com.domain.User;

public interface UserService {

    /**
     * 根据用户名查询用户对象
     */
    public User queryUserByUserName(String username);
}
4.创建UserServiceImpl
package com.service.impl;
/*
@author qw
@date 2021/3/28 - 10:45
**/

import com.domain.User;
import com.service.UserService;

import java.util.Date;

public class UserServiceImpl implements UserService {

    public User queryUserByUserName(String username) {
        User user = null;
        switch(username){
            case "zhangsan":
                user = new User(1, "zhangsan", "123456", new Date());
                break;
            case "lisi":
                user = new User(1, "lisi", "123456", new Date());
                break;
            case "wangwu":
                user = new User(1, "wangwu", "123456", new Date());
                break;
        }
        return user;
    }
}
5.创建UserRealm
package com.realm;
/*
@author qw
@date 2021/3/28 - 10:44
**/

import com.domain.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
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.realm.AuthenticatingRealm;

public class UserRealm extends AuthenticatingRealm {

    private UserService userService = new UserServiceImpl();

    /**
     * 做认证
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        token.getCredentials();
        System.out.println(username);
        /**
         * 以前登录的逻辑是:把用户和密码全部发到数据库 去匹配
         * 在shiro里:先根据用户名把用户对象查询出来,再来做密码匹配
         */
        User user = userService.queryUserByUserName(username);
        if (null != user) {
            /**
             * 参数说明:
             * 参数1:可以传任意对象
             * 参数2:从数据库里查询出来的密码
             * 参数3:当前类名
             */
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPwd(), this.getName());
            return info;
        } else {
            // 用户不存在 shiro会抛 UnknownAccountException 异常
            return null;
        }
    }

}
6.修改shiro.ini(可改可不改)
[main]
#创建UserRealm对象
userRealm=com.realm.UserRealm
#把当前对象给安全管理器
#securityManager=org.apache.shiro.mgt.DefaultSecurityManager
securityManager.realm=$userRealm
7.测试
package com.shiro;
/*
@author qw
@date 2021/3/27 - 21:05
**/

import com.realm.UserRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
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 TestAuthorizationApp {
    //日志输出工具
    private static final transient Logger log = LoggerFactory.getLogger(TestAuthorizationApp.class);

    @SuppressWarnings("deprecation")
    public static void main(String[] args) {

        String username = "zhangsan";
        String password = "123456";

        log.info("My First Apache Shiro Application");
        // 1. 创建安全管理器的工厂对象
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 2. 使用工厂创建安全管理器
        DefaultSecurityManager securityManager = (DefaultSecurityManager) factory.getInstance();
        // 3. 创建UserRealm
        UserRealm realm = new UserRealm();
        // 4. 给securityManager注入UserRealm
        securityManager.setRealm(realm);
        // 5. 把当前的安全管理器绑定到当前的线程
        SecurityUtils.setSecurityManager(securityManager);
        // 6. 使用SecurityUtils.getSubject得到主体对象
        Subject subject = SecurityUtils.getSubject();
        // 7. 封装用户名和密码
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        // 8. 得到认证
        try {
            //判断用户名是否存在 & 密码是否正确
            subject.login(token);
            System.out.println("认证通过");

            Object principal = subject.getPrincipal();
            System.out.println(principal);

        } catch (IncorrectCredentialsException e) {
            System.out.println("密码不正确");
        } catch (UnknownAccountException e) {
            System.out.println("用户名不存在");
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值