您的位置:首页 > 运维架构 > Apache

Apache Shiro 权限控制 使用自定义的JdbcRealm(3)

2018-02-27 17:54 435 查看
使用自定义的realm 时需要配置shiro.ini 文件 以及建一个类  MyJdbcRealm  继承自  AuthorizingRealm 重写其中的两个方法        /**
* 登录验证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
            return null;
        }
        /**
* 为当前登录的用户授予角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
            return null;
        }
在shiro中配置
[main]
authc.loginUrl=/login
roles.unauthorizedUrl=/unauthorized.jsp
perms.unauthorizedUrl=/unauthorized.jsp
myRealm=com.taisen.realm.MyJdbcRealm
securityManager.realms=$myRealm
[urls]
/login=anon
/admin=authc
/student=roles[teacher]

/teacher=perms["teacher:query","teacher:add"]

下面是具体的实现方法:
需要连接数据库  DBUtilpublic class DBUtil {

private static final String username = "root";
private static final String password = "root";
private static final String className = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/db_shiro?useUnicode=true&characterEncoding=utf8&useSSL=false";

public static Connection conn = null;
public static PreparedStatement pstmt = null;

public static Connection getConnection() throws Exception{
Class.forName(className);
conn = DriverManager.getConnection(url, username, password);
return conn;
}

public static void close(Connection conn,PreparedStatement pstmt,ResultSet rs) throws SQLException{
conn.close();
pstmt.close();
if(rs != null){
rs.close();
}
}

public static void close(Connection conn,PreparedStatement pstmt) throws SQLException{
close(conn,pstmt,null);
}

public static void main(String[] args) {
try {
Connection conn = getConnection();
if(conn != null){
System.out.println("数据库连接成功!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}操作数据库UserDao:public class UserDao {

private Connection connection;

public UserDao() throws Exception {
// TODO Auto-generated constructor stub
connection = DBUtil.getConnection();
}

public User getByUserName(String userName) throws Exception{
User resultUser = null;

String sql = "select * from t_user where userName = ?";
PreparedStatement pstmt = connection.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"));
}
DBUtil.close(connection, pstmt,rs);
return resultUser;
}

/*public static void main(String[] args) throws Exception {
UserDao userDao = new UserDao();
User user = userDao.getByUserName("java");
System.out.println(user);
}*/

/**
* 根据userName 获取到roles
* @param userName
* @return
* @throws SQLException
*/
public Set<String> getRoles(String userName) throws SQLException {
Set roles = new HashSet();
String sql = "select * from t_role r LEFT JOIN t_user u on r.id = u.role_id where u.userName = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, userName);
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
roles.add(rs.getString("roleName"));
}
return roles;
}

/**
* 根据传入的userName 返回得到的perms
* @param object
* @return
* @throws SQLException
*/
public Set<String> getPerms(String userName) throws SQLException {
Set permissions = new HashSet();
String sql = "select * from t_user u,t_role r,t_permission p where u.role_id = r.id and p.role_id = r.id and u.userName = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, userName);
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
permissions.add(rs.getString("permissionName"));
}
DBUtil.close(connection, pstmt, rs);
return permissions;
}

}重点 MyJdbcRealm。  在点击登录按钮后后到Controller中的login方法  调用subject.login(token)方法时会调用下面的自定义
Realmpublic class MyJdbcRealm extends AuthorizingRealm{

/**
* 登录验证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
AuthenticationInfo auth = null;
try {
UserDao userdao = new UserDao();
String username = (String) token.getPrincipal(); //获取到userName
User user = userdao.getByUserName(username);
if(user != null){
auth = new SimpleAuthenticationInfo(username, user.getPassword(),"XX");
return auth;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return auth;
}
return auth;
}

/**
* 为当前登录的用户授予角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
String userName = (String)principals.getPrimaryPrincipal();
UserDao userdao;
SimpleAuthorizationInfo auth = null;
try {
userdao = new UserDao();
auth = new SimpleAuthorizationInfo();
auth.setRoles(userdao.getRoles(userName));
auth.setStringPermissions(userdao.getPerms(userName));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return auth;
}

}每次发起请求时都会验证权限。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Shiro自定义Realm