Shiro-java环境配置使用

1.自定义Realm使用完成验证

1.1自定义realm类:继承AuthorizingRealm,实现其验证和授权方法

package com.gavin.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.dqpi.service.UserService;
import com.gavin.model.User;

public class CustomRealm extends AuthorizingRealm {

	//设置realm的名称
	@Override
	public void setName(String name) {
		// TODO Auto-generated method stub
		super.setName("CustomRealm");
	}
	
	//用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	//用于认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		//1.从token中取出用户的身份信息
		//方式一
		String userName = (String) token.getPrincipal();
		String password = new String((char [])token.getCredentials());
		
		//方式二
//	    UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
//		String userName = (String) usernamePasswordToken.getUsername();//用户名
//		String password = new String(usernamePasswordToken.getPassword());//密码
		
		//2.根据用户的账号从数据库中查询
		System.out.println("从数据库中查询“"+userName+"“的信息");
		UserService userService = new UserService();
		//调用login方法获得查询获得的集合
		List<User> users = userService.login(userName);
        
		//3.如果查询不到抛出账户不存在异常
		if(users.isEmpty()) {
			throw new UnknownAccountException();
		}
		
		//4.如果查询到进行判断是否可以完成登录
		else {
			String userPassword = users.get(0).getPassword();
			System.out.println(password);
			//如果密码正确,返回验证信息AuthenticationInfo
			if(userPassword.equals(password)) {
				SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, password, this.getName());
				return simpleAuthenticationInfo;
			}
			//如果密码不正确抛出验证信息异常
			else {
				throw new IncorrectCredentialsException();
			}
		}
	}

}

注:这里使用的UserService在下面给出,使用的是hibernate框架

package com.dqpi.service;

import java.util.List;

import com.gavin.dao.UserDao;
import com.gavin.daoimp.UserDaoImp;
import com.gavin.model.User;

public class UserService {
	UserDao userDao = new UserDaoImp();
	
	public List<User> login(String name){
		return userDao.login(name);
	}
}
package com.gavin.daoimp;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.dqpi.util.HibernateUtil;
import com.gavin.dao.UserDao;
import com.gavin.model.User;

public class UserDaoImp implements UserDao {

	@Override
	public List<User> login(String name) {
		List <User> userList = new ArrayList<User>();
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from User c where c.name='"+name+"'");
		userList = (List <User>)query.list();
		
		session.getTransaction().commit();
		HibernateUtil.getSessionFactory().close();
		return userList;
	}

}

1.2在配置文件中注入realm

[main]
#自定义realm
CustomRealm=com.gavin.realm.CustomRealm
#配置到securityManager中,相当于spring中的注入
securityManager.realms=$CustomRealm

1.3hibernate的配置文件

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/Shiro_Realm?serverTimezone=UTC</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>

        <!-- JDBC connection pool (use the built-in) -->
         <property name="connection.pool_size">1</property> 

        <!-- SQL dialect -->
         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property> 

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
 		<property name="format_sql">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
         <mapping class="com.gavin.model.User"/>
		<!--指向我们的model  -->
    </session-factory>

</hibernate-configuration>

注:使用的是mysql的数据库,可以自己更改连接信息

1.4Hibernate的工具类

package com.dqpi.util;
import java.text.Annotation;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil
{
    private static final SessionFactory sessionFactory;
    static
    {
        try
        {
            Configuration cfg = new Configuration().configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();

            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable e)
        {
            throw new ExceptionInInitializerError(e);
        }
    }
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }

}

1.5Model层

package com.gavin.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {
 
	private int id;
	private String name;//用户名  主键
    private String password;//密码
    private String manager;//权限
    
    @GeneratedValue
    public int getId() {
		return id;
	}

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

    public String getManager() {
		return manager;
	}

	public void setManager(String manager) {
		this.manager = manager;
	}

	@Id
	public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    @Override
 	public String toString() {
 		return "User [name=" + name + ", password=" + password + ", manager=" + manager + "]";
 	}
}

1.6测试方法

 public static void main(String[] args) {
        if(login("lisi","123")){
            System.out.println("登录成功!");
        }
    }
    public static Boolean login(String username,String password){
        //准备
        //获取SecurityManager工厂,试用Ini配置文件初始化SecurityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:realm.ini");
        //得到SecurityManager的实例,并绑定给SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //得到Subject及创建用户/密码身份验证Token(即用户身份/凭证)
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            currentUser.login(token);
            
            return true;
        }
        catch ( UnknownAccountException uae ) {
            System.out.println("账户或密码错误");
        }
        catch ( IncorrectCredentialsException ice ) {
            System.out.println("账户或密码错误");
        }
        catch ( LockedAccountException lae ) {
            System.out.println("账号被锁定,请联系管理员");
        }
        catch ( ExcessiveAttemptsException eae ) {
            System.out.println("错误次数过多,请稍后再试");
        }
        catch ( AuthenticationException ae ) {
            System.out.println("登录失败");
    }
        //登出
        currentUser.logout();
        return false;
    }

注意:在测试方法中捕获异常,并打印相应的错误信息。

最后上源码地址:

链接: https://pan.baidu.com/s/1a3T5LXMrP7up-5oS5LZKiA

提取码: j7rs

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Phil Jackson

你的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值