Shiro学习笔记(5)-- 自定义 Realm

本节基于数据库对用户、角色、权限进行验证:

1、创建用户、角色、权限三张表,并在表中增加上节shiro.ini配置文件中的相应数据:


2、创建一个DBUtil.Java工具类:

package com.yang.util;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 数据库工具类
 * @author 
 *
 */
public class DbUtil {

	/**
	 * 获取数据库连接
	 * @return
	 * @throws Exception
	 */
	public Connection getCon() throws Exception{
		Class.forName("com.mysql.jdbc.Driver");
		Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_shiro", "root", "123456");
		return con;
	}
	
	/**
	 * 关闭数据库连接
	 * @param con
	 * @throws Exception
	 */
	public void closeCon(Connection con)throws Exception{
		if(con!=null){
			con.close();
		}
	}
	
	public static void main(String[] args) {
		DbUtil dbUtil=new DbUtil();
		try {
			dbUtil.getCon();
			System.out.println("数据库连接成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("数据库连接失败");
		}
	}
}

3、在pom.xml文件中引入mysql的驱动包:

<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.37</version>
	</dependency>

4、创建User.java实体类:

package com.yang.entity;

public class User {
	
	private Integer id;
	private String userName;
	private String password;
	
	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 getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

5、创建UserDao.java:

package com.yang.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

import com.yang.entity.User;

public class UserDao {
	
	/**
	 * 获取当前用户信息
	 * @param con
	 * @param userName
	 * @return
	 * @throws Exception
	 */
	public User getByUserName(Connection con,String userName)throws Exception{
		User resultUser = null;
		String sql = "select * from t_user where userName = ?";
		PreparedStatement preparedStatement = con.prepareStatement(sql);
		preparedStatement.setString(1, userName);
		ResultSet resultSet = preparedStatement.executeQuery();
		if(resultSet.next()){
			resultUser = new User();
			resultUser.setId(resultSet.getInt("id"));
			resultUser.setUserName(resultSet.getString("userName"));
			resultUser.setPassword(resultSet.getString("password"));
		}
		return resultUser;
	}
	
	/**
	 * 获取当前用户的所有角色
	 * @param con
	 * @param userName
	 * @return
	 * @throws Exception
	 */
	public Set<String> getRoles(Connection con,String userName)throws Exception{
		Set<String>  roles = new HashSet<String>();
		String sql = "select * from t_user u,t_role r where u.roleId = r.id and userName = ?";
		PreparedStatement preparedStatement = con.prepareStatement(sql);
		preparedStatement.setString(1, userName);
		ResultSet resultSet = preparedStatement.executeQuery();
		while(resultSet.next()){
			roles.add(resultSet.getString("roleName"));
		}
		return roles;
	}
	
	/**
	 * 获取当前用户角色对应的权限
	 * @param con
	 * @param userName
	 * @return
	 * @throws Exception
	 */
	public Set<String> getPermissions(Connection con,String userName)throws Exception{
		Set<String> permissions = new HashSet<String>();
		String sql = "select * from t_user u,t_role r,t_permission p where u.roleId = r.id and p.roleId = r.id and userName = ?";
		PreparedStatement preparedStatement = con.prepareStatement(sql);
		preparedStatement.setString(1, userName);
		ResultSet resultSet = preparedStatement.executeQuery();
	    while(resultSet.next()){
	    	permissions.add(resultSet.getString("permissionName"));
	    }
		return permissions;
	}
	
}

6、创建自定义realm类MyRealm.java:

package com.yang.realm;

import java.sql.Connection;

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.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.yang.dao.UserDao;
import com.yang.entity.User;
import com.yang.util.DbUtil;

public class MyRealm extends AuthorizingRealm{
	
	private UserDao userDao = new UserDao();
	private DbUtil dbUtil = new DbUtil();
	

	/**
	 * 为当前登录的用户授予角色和权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Connection con = null;
		try {
			con = dbUtil.getCon();
			authorizationInfo.setRoles(userDao.getRoles(con, userName));
			authorizationInfo.setStringPermissions(userDao.getPermissions(con, userName));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return authorizationInfo;
	}

	
	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String)token.getPrincipal();
		Connection con = null;
		try {
			con = dbUtil.getCon();
			User user = userDao.getByUserName(con, userName);
			if(user!=null){
				AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), "a");
				return authenticationInfo;
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

}











7、修改shiro.ini配置文件:

[main]
authc.loginUrl=/login
roles.unauthorizedUrl=/unauthorized.jsp
perms.unauthorizedUrl=/unauthorized.jsp
myRealm=com.yang.realm.MyRealm
securityManager.realms=$myRealm
[urls]
/login=anon
/admin*=authc
/student=roles[teacher]
/teacher=perms["user:create"]







猜你喜欢

转载自blog.csdn.net/maonian1762/article/details/80509046