前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Shiro学习笔记六(自定义Reaml-使用数据库设置 user roles permissions)

Shiro学习笔记六(自定义Reaml-使用数据库设置 user roles permissions)

作者头像
梅花
发布2020-09-28 16:04:43
3550
发布2020-09-28 16:04:43
举报

1.工程目录

pom文件还和以前设置的一样就是添加了一个数据库驱动,

代码语言:javascript
复制
 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- 添加servlet支持 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    
    <!-- 添加jstl支持 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    
    <!-- 添加日志支持 -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
    
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    
    <!-- 添加shiro支持 -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.2.4</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-web</artifactId>
        <version>1.2.4</version>
    </dependency>
    
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.12</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.37</version>
    </dependency>
    
    
  </dependencies>

shiro.ini中的配置

代码语言:javascript
复制
[main]
authc.loginUrl=/login
roles.unauthorizedUrl=/unauthorized.jsp
perms.unauthorizedUrl=/unauthorized.jsp


myRealm=com.zuoyan.shiro.realm.MyRealm
securityManager.realms=$myRealm

[urls]
/login=anon
/admin*=authc
/student=roles[teacher]
/teacher=perms["user:create"]

简单的解释说明一下Realm,这个我解释不清楚,就引用了别人博客上面的

对于什么是Realm,我使用过之后,个人总结一下:shiro要进行身份验证,就要从realm中获取相应的身份信息来进行验证,简单来说,我们可以自行定义realm,在realm中,从数据库获取身份信息,然后和 用户输入的身份信息进行匹配。这一切都由我们自己来定义。

下面就贴出我们自定义realm 的代码

代码语言:javascript
复制
 1 package com.zuoyan.shiro.realm;
 2 
 3 import java.sql.Connection;
 4 
 5 import org.apache.shiro.authc.AuthenticationException;
 6 import org.apache.shiro.authc.AuthenticationInfo;
 7 import org.apache.shiro.authc.AuthenticationToken;
 8 import org.apache.shiro.authc.SimpleAuthenticationInfo;
 9 import org.apache.shiro.authz.AuthorizationInfo;
10 import org.apache.shiro.authz.SimpleAuthorizationInfo;
11 import org.apache.shiro.realm.AuthorizingRealm;
12 import org.apache.shiro.subject.PrincipalCollection;
13 
14 import com.zuoyan.shiro.dao.UserDao;
15 import com.zuoyan.shiro.entity.User;
16 import com.zuoyan.shiro.utils.DbUtil;
17 
18 public class MyRealm extends AuthorizingRealm{
19 
20     private UserDao userDao=new UserDao();
21     private DbUtil dbUtil=new DbUtil();
22     
23     /*
24      * 用于授权
25      */
26     @Override
27     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
28         String userName=(String)principals.getPrimaryPrincipal();
29         SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
30         Connection con=null;
31         try{
32             con=dbUtil.getCon();
33             authorizationInfo.setRoles(userDao.getRoles(con,userName));
34             authorizationInfo.setStringPermissions(userDao.getPermissions(con,userName));
35         }catch(Exception e){
36             e.printStackTrace();
37         }finally{
38             try {
39                 dbUtil.closeCon(con);
40             } catch (Exception e) {
41                 // TODO Auto-generated catch block
42                 e.printStackTrace();
43             }
44         }
45         return authorizationInfo;
46     }
47     
48     /*
49      * 用于认证
50      */
51 
52     @Override
53     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
54         String userName=(String)token.getPrincipal();
55         Connection con=null;
56         try{
57             con=dbUtil.getCon();
58             User user=userDao.getByUserName(con, userName);
59             if(user!=null){
60                 AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xx");
61                 return authcInfo;
62             }else{
63                 return null;
64             }
65         }catch(Exception e){
66             e.printStackTrace();
67         }finally{
68             try {
69                 dbUtil.closeCon(con);
70             } catch (Exception e) {
71                 // TODO Auto-generated catch block
72                 e.printStackTrace();
73             }
74         }
75         return null;
76     }
77 
78 }
代码语言:javascript
复制
AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xx");
对于这句话,我一开始的理解就是 先查出来标准的账号密码在自定义中的Realm中进行比对,但是正确的是这里设置的是标准的账号密码
比对应该是在下一步

UserDao的就是在数据库中进行查找
代码语言:javascript
复制
 1 package com.zuoyan.shiro.dao;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.util.HashSet;
 7 import java.util.Set;
 8 
 9 import com.zuoyan.shiro.entity.User;
10 
11 
12 
13 public class UserDao {
14 
15     public User getByUserName(Connection con,String userName)throws Exception{
16         User resultUser=null;
17         String sql="select * from t_user where userName=?";
18         PreparedStatement pstmt=con.prepareStatement(sql);
19         pstmt.setString(1, userName);
20         ResultSet rs=pstmt.executeQuery();
21         if(rs.next()){
22             resultUser=new User();
23             resultUser.setId(rs.getInt("id"));
24             resultUser.setUserName(rs.getString("userName"));
25             resultUser.setPassword(rs.getString("password"));
26         }
27         return resultUser;
28     }
29 
30     public Set<String> getRoles(Connection con, String userName) throws Exception{
31         Set<String> roles=new HashSet<String>();
32         String sql="select * from t_user u,t_roles r where u.roleId=r.id and u.userName=?";
33         PreparedStatement pstmt=con.prepareStatement(sql);
34         pstmt.setString(1, userName);
35         ResultSet rs=pstmt.executeQuery();
36         while(rs.next()){
37             roles.add(rs.getString("roleName"));
38         }
39         return roles;
40     }
41 
42     public Set<String> getPermissions(Connection con, String userName)throws Exception {
43         Set<String> permissions=new HashSet<String>();
44         String sql="select * from t_user u,t_roles r,t_permission p where u.roleId=r.id and p.roleId=r.id and u.userName=?";
45         PreparedStatement pstmt=con.prepareStatement(sql);
46         pstmt.setString(1, userName);
47         ResultSet rs=pstmt.executeQuery();
48         while(rs.next()){
49             permissions.add(rs.getString("permissionName"));
50         }
51         return permissions;
52     }
53 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-12-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档