【shiro】--- Customize realm

           The editor is busy looking for a job recently and neglected the update of the blog. It really shouldn't be, so let's make it up now! (*^__^*) Hee hee...  

       In the previous code examples, realm was written in shiro.ini by itself , but this is definitely not the case in practical applications. Which permissions, roles, and users must be defined in the database, and then we write realm by ourselves , from the database The roles and permissions obtained in shiro.ini can be assigned to the currently logged-in user to achieve the effect of writing to death in shiro.ini.

Step 1: Build a library

 

Step 2: On the basis of the previous Pom, add the MySQL-driven jar package

The third step: define dao, operate the database

public class UserDao {

// Get user information by user name

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); // Assign parameter values ​​to sql

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;

}

 

/**

 * Get character

 * @param connection

 * @param userName

 * @return

 * @throws Exception

 */

public Set<String> getRoles(Connection connection, 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 u.userName=?";

PreparedStatement pstmt =connection.prepareStatement(sql);

pstmt.setString(1, userName);// Assign parameter values ​​to sql

ResultSet rs=pstmt.executeQuery();

while (rs.next()) {

roles.add(rs.getString("roleName"));                        

}

return roles;

}

 

/**

 * Get permission

 * @param connection

 * @param userName

 * @return

 */

public Set<String> getPermissions(Connection connection, 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 u.userName=?";

PreparedStatement pstmt =connection.prepareStatement(sql);

pstmt.setString(1, userName);//sql赋参数值

ResultSet rs=pstmt.executeQuery();

while (rs.next()) {

permissions.add(rs.getString("permissionName"));                        

}

return permissions;

}

 

}

 

 

第四步:自定义realm,给用户赋角色,权限

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 connection=null;

try {

connection=dbUtil.getCon();

authorizationInfo.setRoles(userDao.getRoles(connection,userName));

authorizationInfo.setStringPermissions(userDao.getPermissions(connection,userName));

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

dbUtil.closeCon(connection);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 

return null;

}

 

/**

 * 验证当前登录的用户

 */

@Override

protected AuthenticationInfo doGetAuthenticationInfo(

AuthenticationToken token) throws AuthenticationException {

String userName=(String)token.getPrincipal();//通过token获取用户名

Connection con =null;

try {

con=dbUtil.getCon();

User user=userDao.getByUserName(con, userName);

if (user!=null) {

//将从数据获得的用户名和密码传入,将来方便和前台用户传过来的用户名和密码做比对

AuthenticationInfo auInfo =new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xx");

return auInfo;

}else{

return null;

}

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

dbUtil.closeCon(con);

 

} catch (Exception e) {

e.printStackTrace();

}

}

return null;

}

 

}

 

第五步:登录拦截器的代码和上一篇博客的一样。

第六步:shiro.ini的内容:

[main]

authc.loginUrl=/login

roles.unauthorizedUrl=/unauthorized.jsp

perms.unauthorizedUrl=/unauthorizedUrl.jsp

 

myRealm=com.java1234.realm.MyRealm

securityManager.realms=$myRealm

 

[urls]

/login=anon

/admin=authc

/student=roles[teacher]

/teacher=perms["user:create"]

 

 

这样就可以完成自定义realm。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325635461&siteId=291194637