shiro——自定义Realm(安全数据源)

1、验证当前登陆的用户
2、从数据库读取当前用户相应的角色和权限,并赋值给当前的用户


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;

/**
 * MyRealm,自定义Realm类
 */
public class MyRealm extends AuthorizingRealm {

    private UserDao userDao = new UserDao();

    private DbUtil dbUtil = new DbUtil();

    /**
     * 验证当前登录的用户
     * 
     */
    @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 authcInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(),
                        "xx");

                return authcInfo;
            } else {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {

                dbUtil.closeCon(con);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    /**
     * 为当前登录的用户授予角色和权限
     * 

* 根据用户名从数据库读取相应的角色和权限,并赋值给当前的用户 */ @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; } }


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

/**
* 数据库工具类 DbUtil
* 
* @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/shiro_db", "root", "root");
       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("数据库连接失败");
       }
   }
}

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

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 pstmt = con.prepareStatement(sql);
        pstmt.setString(1, userName);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            resultUser = new User();
            resultUser.setId(rs.getInt("id"));
            resultUser.setUserName(rs.getString("userName"));
            resultUser.setPassword(rs.getString("password"));
        }
        return resultUser;
    }

    /**
     * 通过用户名获取用户的角色信息
     * 
     * @param con
     * @param userName
     * @return
     * @throws Exception
     */
    public Set getRoles(Connection con, String userName) throws Exception {
        Set roles = new HashSet();
        String sql = "select * from t_user u,t_role r where u.roleId=r.id and u.userName=?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, userName);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            roles.add(rs.getString("roleName"));
        }
        return roles;
    }

    /**
     * 通过用户名获取用户的权限信息
     * 
     * @param con
     * @param userName
     * @return
     * @throws Exception
     */
    public Set getPermissions(Connection con, String userName) throws Exception {
        Set permissions = new HashSet();
        String sql = "select * from t_user u,t_role r,t_permission p where u.roleId=r.id and p.roleId=r.id and u.userName=?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, userName);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            permissions.add(rs.getString("permissionName"));
        }
        return permissions;
    }
}


shiro.ini:

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

数据库:

t_permission表
t_role表
shiro——自定义Realm(安全数据源)_第1张图片
t_user表

你可能感兴趣的:(shiro——自定义Realm(安全数据源))