Shiro详细使用

一、权限的管理

1.1 什么是权限管理

基本上涉及到用户参与的系统都要进行权限管理,权限管理属于系统安全的范畴,权限管理实现`对用户访问系统的控制,按照安全规则或者安全策略控制用户可以访问而且只能访问自己被授权的资源。

权限管理包括用户身份认证授权两部分,简称认证授权。对于需要访问控制的资源用户首先经过身份认证,认证通过后用户具有该资源的访问权限方可访问。

1.2 什么是身份认证

身份认证,就是判断一个用户是否为合法用户的处理过程。最常用的简单身份认证方式是系统通过核对用户输入的用户名和口令,看其是否与系统中存储的该用户的用户名和口令一致,来判断用户身份是否正确。对于采用指纹]等系统,则出示指纹;对于硬件Key等刷卡系统,则需要刷卡。

1.3 什么是授权

授权,即访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某些资源没有权限是无法访问的。

二、什么是Shiro

Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications.

Shiro 是一个功能强大且易于使用的Java安全框架,它执行身份验证、授权、加密和会话管理。使用Shiro易于理解的API,您可以快速轻松地保护任何应用程序—从最小的移动应用程序到最大的web和企业应用程序。

Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权、加密、会话管理等功能,组成了一个通用的安全认证框架。

三、Shiro的核心架构

在这里插入图片描述

3.1 Subject

Subject即主体,外部应用与subject进行交互,subject记录了当前操作用户,将用户的概念理解为当前操作的主体,可能是一个通过浏览器请求的用户,也可能是一个运行的程序。 Subjectshiro中是一个接口,接口中定义了很多认证授相关的方法,外部程序通过subject进行认证授,而subject是通过SecurityManager安全管理器进行认证授权。

3.2 SecurityManager

SecurityManager即安全管理器,对全部的subject进行安全管理,它是shiro的核心,负责对所有的subject进行安全管理。通过SecurityManager可以完成subject的认证、授权等,实质上SecurityManager是通过Authenticator进行认证,通过Authorizer进行授权,通过SessionManager进行会话管理等。

SecurityManager是一个接口,继承了Authenticator, Authorizer, SessionManager这三个接口。

3.3 Authenticator

Authenticator即认证器,对用户身份进行认证,Authenticator是一个接口,shiro提供ModularRealmAuthenticator实现类,通过ModularRealmAuthenticator基本上可以满足大多数需求,也可以自定义认证器。

3.4 Authorizer

Authorizer即授权器,用户通过认证器认证通过,在访问功能时需要通过授权器判断用户是否有此功能的操作权限。

3.5 Realm

Realm即领域,相当于datasource数据源,securityManager进行安全认证需要通过Realm获取用户权限数据,比如:如果用户身份数据在数据库那么realm就需要从数据库获取用户身份信息。

注意:不要把realm理解成只是从数据源取数据,在realm中还有认证授权校验的相关的代码。

3.6 SessionManager

sessionManager即会话管理,shiro框架定义了一套会话管理,它不依赖web容器的session,所以shiro可以使用在非web应用上,也可以将分布式应用的会话集中在一点管理,此特性可使它实现单点登录。

3.7 SessionDAO

SessionDAO即会话dao,是对session会话操作的一套接口,比如要将session存储到数据库,可以通过jdbc将会话存储到数据库。

3.8 CacheManager

CacheManager即缓存管理,将用户权限数据存储在缓存,这样可以提高性能。

3.9 Cryptography

Cryptography即密码管理,shiro提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。

四、shiro中的认证

4.1 认证

身份认证,就是判断一个用户是否为合法用户的处理过程。最常用的简单身份认证方式是系统通过核对用户输入的用户名和口令,看其是否与系统中存储的该用户的用户名和口令一致,来判断用户身份是否正确。

4.2 shiro中认证的关键对象
  • Subject:主体
    访问系统的用户,主体可以是用户、程序等,进行认证的都称为主体。

  • Principal:身份信息
    是主体(subject)进行身份认证的标识,标识必须具有唯一性,如用户名、手机号、邮箱地址等,一个主体可以有多个身份,但是必须有一个主身份(Primary Principal)。

  • credential:凭证信息
    是只有主体自己知道的安全信息,如密码、证书等。

4.3 认证流程

在这里插入图片描述

4.4 认证的开发

1. 创建项目并引入依赖

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-core</artifactId>
  <version>1.5.3</version>
</dependency>

2.引入shiro配置文件并加入如下配置

[users]
xiaochen=123
zhangsan=456

在这里插入图片描述
3. 开发认证代码

public class TestAuthenticator {
    public static void main(String[] args) {
        //1.创建securityManager对象
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //2.给安全管理器设置realm
        defaultSecurityManager.setRealm(new IniRealm("classpath:shiro.ini"));
        //设置为自定义realm获取认证数据
        //defaultSecurityManager.setRealm(new CustomerRealm());
        //3.SecurityUtils给全局安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //4.获取主体对象
        Subject subject = SecurityUtils.getSubject();
        //5.创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("xiaochen", "123");
        try {
            //用户登录
            System.out.println("认证状态:" + subject.isAuthenticated());
            subject.login(token);
            System.out.println("认证状态:" + subject.isAuthenticated());
            System.out.println("登录成功~~");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!!");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误!!!");
        }
    }
}
  • DisabledAccountException(帐号被禁用)

  • LockedAccountException(帐号被锁定)

  • ExcessiveAttemptsException(登录失败次数过多)

  • ExpiredCredentialsException(凭证过期)等

4.5 自定义Realm

上边的程序使用的是Shiro自带的IniRealmIniRealmini配置文件中读取用户的信息,大部分情况下需要从系统的数据库中读取用户信息,所以需要自定义realm

1. Shiro提供的Realm
在这里插入图片描述
2. 根据认证源码认证使用的是SimpleAccountRealm
SimpleAccountRealm的部分源码中有两个方法一个是认证,一个是授权。

public class SimpleAccountRealm extends AuthorizingRealm {
		//.......省略
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        SimpleAccount account = getUser(upToken.getUsername());
        if (account != null) {
            if (account.isLocked()) {
                throw new LockedAccountException("Account [" + account + "] is locked.");
            }
            if (account.isCredentialsExpired()) {
                String msg = "The credentials for account [" + account + "] are expired";
                throw new ExpiredCredentialsException(msg);
            }
        }
        return account;
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = getUsername(principals);
        USERS_LOCK.readLock().lock();
        try {
            return this.users.get(username);
        } finally {
            USERS_LOCK.readLock().unlock();
        }
    }
}

3. 自定义realm

public class CustomerRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //在token中获取用户名
        String principal = (String) token.getPrincipal();
        System.out.println(principal);
        //根据身份信息使用jdbc mybatis查询相关数据库
        if ("xiaochen".equals(principal)) {
            return new SimpleAuthenticationInfo(principal, "123", this.getName());
        }
        return null;
    }
}
4.6 使用MD5和Salt

实际应用是将盐和散列后的值存在数据库中,自动realm从数据库取出盐和加密后的值由shiro完成密码校验。
1. 自定义md5+saltrealm

public class CustomerRealm2 extends AuthorizingRealm {
    /**
     * 认证方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 授权方法
     * @param token
     * @return
     * @throws
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        if ("xiaochen".equals(principal)) {
            String password = "3c88b338102c1a343bcb88cd3878758e";
            String salt = "Q4F%";
            return new SimpleAuthenticationInfo(principal, password,
                    ByteSource.Util.bytes(salt), this.getName());
        }
        return null;
    }

2. 使用md5 + salt认证

public class TestAuthenticatorCusttomerRealm {
    public static void main(String[] args) {
        //创建securityManager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //IniRealm realm = new IniRealm("classpath:shiro.ini");
        //设置为自定义realm获取认证数据
        CustomerRealm customerRealm = new CustomerRealm();
        //设置md5加密
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        defaultSecurityManager.setRealm(customerRealm);
        //将安装工具类中设置默认安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        //创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("xiaochen", "123");
        try {
            //用户登录
            subject.login(token);
            System.out.println("登录成功~~");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!!");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误!!!");
        }
    }
}

五、shiro中的授权

5.1 授权

授权,即访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某些资源没有权限是无法访问的。

5.2 关键对象

授权可简单理解为whowhat(which)进行How操作:

  • Who,即主体(Subject),主体需要访问系统中的资源。
  • What,即资源(Resource),如系统菜单、页面、按钮、类方法、系统商品信息等。资源包括资源类型和资源实例,比如商品信息为资源类型,类t0的商品为资源实例,编号001的商品信息也属于资源实例。
  • How,权限/许可(Permission),规定了主体对资源的操作许可,权限离开资源没有意义,如用户查询权限、用户添加权限、某个类方法的调用权限、编号为001用户的修改权限等,通过权限可知主体对哪些资源都有哪些操作许可。
5.3 授权流程

在这里插入图片描述

5.4 授权方式
  • 基于角色的访问控制
    • RBAC基于角色的访问控制(Role-Based Access Control)是以角色为中心进行访问控制
      if(subject.hasRole("admin")){
         //操作什么资源
      }
      
  • 基于资源的访问控制
    • RBAC基于资源的访问控制(Resource-Based Access Control)是以资源为中心进行访问控制。

      if(subject.isPermission("user:update:01")){ //资源实例
        //对01用户进行修改
      }
      if(subject.isPermission("user:update:*")){  //资源类型
        //对01用户进行修改
      }
      
5.5 权限字符串

权限字符串的规则是:资源标识符:操作:资源实例标识符,意思是对哪个资源的哪个实例具有什么操作,“:”是资源/操作/实例的分割符,权限字符串也可以使用*通配符。
例子:

  • 用户创建权限:user:create,或user:create:*
  • 用户修改实例001的权限:user:update:001
  • 用户实例001的所有权限:user:*:001
5.6 Shiro中授权编程实现方式

1. 编程式

Subject subject = SecurityUtils.getSubject();
if(subject.hasRole(“admin”)) {
	//有权限
} else {
	//无权限
}

2. 注解式

@RequiresRoles("admin")
public void hello() {
	//有权限
}

3. 标签式

JSP/GSP 标签:在JSP/GSP 页面通过相应的标签完成:
<shiro:hasRole name="admin">
	<!— 有权限—>
</shiro:hasRole>
注意: Thymeleaf 中使用shiro需要额外集成!
5.7 开发授权

1. realm的实现

public class CustomerRealm3 extends AuthorizingRealm {
    /**
     * 认证方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("primaryPrincipal = " + primaryPrincipal);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addStringPermission("user:update:*");
        simpleAuthorizationInfo.addStringPermission("product:*:*");
        return simpleAuthorizationInfo;
    }

    /**
     * 授权方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        if ("xiaochen".equals(principal)) {
            String password = "3c88b338102c1a343bcb88cd3878758e";
            String salt = "Q4F%";
            return new SimpleAuthenticationInfo(principal, password,
                    ByteSource.Util.bytes(salt), this.getName());
        }
        return null;
    }
}

2. 授权

public static void main(String[] args) {
    //创建securityManager
    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    //IniRealm realm = new IniRealm("classpath:shiro.ini");
    //设置为自定义realm获取认证数据
    CustomerRealm3 customerRealm = new CustomerRealm3();
    //设置md5加密
    HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
    credentialsMatcher.setHashAlgorithmName("MD5");
    //设置散列次数
    credentialsMatcher.setHashIterations(1024);
    customerRealm.setCredentialsMatcher(credentialsMatcher);
    defaultSecurityManager.setRealm(customerRealm);
    //将安装工具类中设置默认安全管理器
    SecurityUtils.setSecurityManager(defaultSecurityManager);
    //获取主体对象
    Subject subject = SecurityUtils.getSubject();
    //创建token令牌
    UsernamePasswordToken token = new UsernamePasswordToken("xiaochen", "123");
    try {
        //用户登录
        subject.login(token);
        System.out.println("登录成功~~");
    } catch (UnknownAccountException e) {
        e.printStackTrace();
        System.out.println("用户名错误!!");
    } catch (IncorrectCredentialsException e) {
        e.printStackTrace();
        System.out.println("密码错误!!!");
    }
    //认证通过
    if (subject.isAuthenticated()) {
        //基于角色权限管理
        boolean admin = subject.hasRole("admin");
        System.out.println(admin);

        boolean permitted = subject.isPermitted("product:create:001");
        System.out.println(permitted);
    }
}

六、整合SpringBoot项目实战

6.0 整合思路

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Spring加Shiro写一个简单的登录功能的详细代码。 1. 配置Shiro 在Spring的配置文件中,配置Shiro的相关内容: ``` <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm"/> </bean> <bean id="myRealm" class="com.example.MyRealm"/> <bean class="org.springframework.web.filter.DelegatingFilterProxy"> <property name="targetFilterLifecycle" value="true"/> </bean> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="/login"/> <property name="successUrl" value="/index"/> <property name="filterChainDefinitions"> <value> /login = anon /logout = logout /** = authc </value> </property> </bean> ``` 在上述配置中,我们配置了Shiro的安全管理器、自定义Realm、Shiro的过滤器等。 2. 编写登录页面 在登录页面中,我们需要使用表单来提交用户名和密码。为了与Shiro进行集成,我们需要在表单中添加名为“rememberMe”的复选框,用于实现记住我功能。 ``` <form method="post" action="/login"> <input type="text" name="username" placeholder="用户名"> <input type="password" name="password" placeholder="密码"> <input type="checkbox" name="rememberMe">记住我 <button type="submit">登录</button> </form> ``` 3. 编写自定义Realm 我们需要继承Shiro的Realm类,并实现其中的认证和授权方法。 ``` public class MyRealm extends AuthorizingRealm { /** * 认证方法 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); String password = new String(upToken.getPassword()); // 根据用户名从数据库中获取用户信息 User user = userService.findByUsername(username); if (user == null) { throw new UnknownAccountException("用户不存在"); } if (!password.equals(user.getPassword())) { throw new IncorrectCredentialsException("密码错误"); } return new SimpleAuthenticationInfo(user, password, getName()); } /** * 授权方法 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { User user = (User) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.setRoles(user.getRoles()); info.setStringPermissions(user.getPermissions()); return info; } } ``` 在上述代码中,我们从数据库中获取用户信息,并对用户名和密码进行验证。如果验证通过,则返回一个AuthenticationInfo对象,在后续的认证流程中使用。 在授权方法中,我们从用户信息中获取用户的角色和权限等信息,用于后续的授权流程。 4. 编写登录Controller 在登录Controller中,我们需要处理用户提交的表单数据,并进行Shiro认证流程。 ``` @Controller public class LoginController { @RequestMapping("/login") public String login(HttpServletRequest request) { String exceptionClassName = (String) request.getAttribute("shiroLoginFailure"); if (exceptionClassName != null) { if (UnknownAccountException.class.getName().equals(exceptionClassName)) { request.setAttribute("errorMsg", "用户不存在"); } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) { request.setAttribute("errorMsg", "密码错误"); } else if (AuthenticationException.class.getName().equals(exceptionClassName)) { request.setAttribute("errorMsg", "认证失败"); } else if (LockedAccountException.class.getName().equals(exceptionClassName)) { request.setAttribute("errorMsg", "账号被锁定"); } else { request.setAttribute("errorMsg", "未知错误"); } } return "login"; } } ``` 在上述代码中,我们判断Shiro认证过程中是否出现异常,并将异常信息存储到request中,用于在登录页面中显示错误信息。 5. 编写登录成功跳转Controller 在登录成功后,我们需要跳转到指定的页面。在Spring MVC中,我们可以使用redirect方式来实现。 ``` @Controller public class IndexController { @RequestMapping("/index") public String index() { return "index"; } } ``` 在上述代码中,我们配置了一个/index的请求映射,用于跳转到index页面。 6. 编写注销Controller 在注销Controller中,我们需要清除Shiro中的缓存信息,并跳转到登录页面。 ``` @Controller public class LogoutController { @RequestMapping("/logout") public String logout() { SecurityUtils.getSubject().logout(); return "redirect:/login"; } } ``` 在上述代码中,我们使用SecurityUtils.getSubject()来获取当前用户的Subject对象,并调用其logout()方法来清除缓存。最后,我们使用redirect方式跳转到登录页面。 以上就是使用Spring加Shiro写一个简单的登录功能的详细代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值