Shiro主要用来进行权限管理。简单的介绍如下:

一、概念

Shiro是一个安全框架,可以进行角色、权限管理。

Shiro主要功能如下: Authentication(认证):用户身份识别,通常被称为用户“登录” Authorization(授权):访问控制。比如某个用户是否具有某个操作的使用权限。 Session Management(会话管理):特定于用户的会话管理,甚至在非web 或 EJB 应用程序。 Cryptography(加密):在对数据源使用加密算法加密的同时,保证易于使用。 二、主要的类

1.Subject:当前用户,Subject可以是一个人,也可以是第三方服务 2.SecurityManager:管理所有Subject,可以配合内部安全组件。

3.principals:身份,即主体的标识属性,可以是任何东西,如用户名、邮箱等,唯一即可。一个主体可以有多个principals,但只有一个Primary principals,一般是用户名/密码/手机号。 4.credentials:证明/凭证,即只有主体知道的安全值,如密码/数字证书等。 最常见的principals和credentials组合就是用户名/密码了。

5.Realms:用于进行权限信息的验证,需要自己实现。 6.Realm 本质上是一个特定的安全 DAO:它封装与数据源连接的细节,得到Shiro 所需的相关的数据。 在配置 Shiro 的时候,你必须指定至少一个Realm 来实现认证(authentication)和/或授权(authorization)。 我们需要实现Realms的Authentication 和 Authorization。其中 Authentication 是用来验证用户身份,Authorization 是授权访问控制,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。

7.SimpleHash,可以通过特定算法(比如md5)配合盐值salt,对密码进行多次加密。

三、Shiro配置

1.Spring集成Shiro一般通过xml配置,SpringBoot集成Shiro一般通过java代码配合@Configuration和@Bean配置。

2.Shiro的核心通过过滤器Filter实现。Shiro中的Filter是通过URL规则来进行过滤和权限校验,所以我们需要定义一系列关于URL的规则和访问权限。

3.SpringBoot集成Shiro,我们需要写的主要是两个类,ShiroConfiguration类,还有继承了AuthorizingRealm的Realm类

ShiroConfiguration类,用来配置Shiro,注入各种Bean。

包括过滤器(shiroFilter)、安全事务管理器(SecurityManager)、密码凭证(CredentialsMatcher)、aop注解支持(authorizationAttributeSourceAdvisor)等等

Realm类,包括登陆认证(doGetAuthenticationInfo)、授权认证(doGetAuthorizationInfo)

 

四:实战部分

此处演示2个用户进行登陆系统,有着不同的权限,实现用户只能操作自己权限下面的菜单,对其他菜单无法操作。此处的菜单演示使用2个写死的菜单。基于SpringBoot共使用3种实现方式进行演示,说明其中的优缺点,根据个人实际情况选择。

 

4.1、公共部分,引入依赖

<!--shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency> <!-- shiro ehcache --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <exclusions> <exclusion> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> </exclusion> </exclusions> <version>1.4.0</version> </dependency> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
 

 

4.2、数据库部分,一切从简

4.3、下面开始有不同的部分,第一种方式用黄色标识,第二种用绿色,第三种用蓝色标识。

配置一个Realm来实现登陆认证和授权、

import com.example.demo.entity.User; import com.example.demo.mapper.RoleMapper; import com.example.demo.mapper.UserMapper; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired;import java.util.HashSet; import java.util.List; import java.util.Set;

/**

  • 自定义的Realm 实现授权和认证 / public class UserRealm extends AuthorizingRealm { //此处注意下面自动装载可能为空,是在shrio配置类中配置 private UserMapper userMapper; private RoleMapper roleMapper; @Autowired private void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } @Autowired private void setRoleMapper(RoleMapper roleMapper) { this.roleMapper = roleMapper; } /*
  • 授权
  • @param principals * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { User user = (User) SecurityUtils.getSubject().getPrincipal(); Set<String> roles = new HashSet<>(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); List<String> role = roleMapper.findRoleByUser(user.getUserName()); role.stream().forEach(s -> { roles.add(s); }); info.setRoles(roles);

/** *  如果需要在页面中使用 shiro:hasPermission="guest" *  需要在shrio中配置 shiroDialect,并加上下面这句 */ //info.addStringPermissions(role); return info; }

/**

  • 认证
  • @param token * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usertoken = (UsernamePasswordToken) token; User user = userMapper.selectByUserName(usertoken.getUsername()); if (user == null) { throw new AccountException("用户名不存在"); } if (!user.getPassWord().equals(new String((char[]) usertoken.getCredentials()))) { throw new AccountException("密码不正确"); } return new SimpleAuthenticationInfo(user, usertoken.getPrincipal(), getName()); } }
 

4.4 配置shrio配置类,这里也可以配置缓存相关信息。

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerExceptionResolver;import java.util.LinkedHashMap; import java.util.Map;

@Configuration public class ShrioConfig { @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // 必须设置 SecurityManager shiroFilterFactoryBean.setSecurityManager(securityManager); // setLoginUrl 如果不设置值,默认会自动寻找Web工程根目录下的"/login.jsp"页面 或 "/login" 映射 shiroFilterFactoryBean.setLoginUrl("/"); // 设置无权限时跳转的 url; shiroFilterFactoryBean.setUnauthorizedUrl("/403"); // 设置拦截器 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); //游客,开发权限 filterChainDefinitionMap.put("/errorPage", "anon"); //用户,需要角色权限 “user”   //管理员,需要角色权限 “admin”         //注意:此处是第一种配置,是直接在这里写死的权限和路径信息        filterChainDefinitionMap.put("/user/addUser", "roles[admin]");         filterChainDefinitionMap.put("/user/selectUser", "roles[guest]");  //注意下面 是第二种方式,和上面只能配置一个 //        filterChainDefinitionMap.put("/user/addUser", "authc"); //        filterChainDefinitionMap.put("/user/selectUser", "authc");

//开放登陆/退出接口 filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/logout", "anon"); //其余接口一律拦截 //主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截 filterChainDefinitionMap.put("/**", "authc");

shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); System.out.println("Shiro拦截器工厂类注入成功"); return shiroFilterFactoryBean; }

/**

  • 注入 securityManager */ @Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 设置realm. securityManager.setRealm(customRealm()); return securityManager; }

/**

  • ShiroDialect为了在thymeleaf里使用shiro的标签的bean
  • @return */ @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); }

/**

  • 处理未授权的时候跳转问题
  • @return */ @Bean public HandlerExceptionResolver solver() { HandlerExceptionResolver handlerExceptionResolver = new MyExceptionResolver(); return handlerExceptionResolver; }

/**

  • 开启shiro aop注解支持.  必需
  • 使用代理方式;所以需要开启代码支持;否则@RequiresRoles等注解无法生效
  • @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; }

@Bean public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); advisorAutoProxyCreator.setProxyTargetClass(true); return advisorAutoProxyCreator; }

/**

  • 自定义身份认证 realm;
  • <p> * 必须写这个类,并加上 @Bean 注解,目的是注入 CustomRealm,
  • 否则会影响 CustomRealm类 中其他类的依赖注入 */ @Bean public UserRealm customRealm() { return new UserRealm(); } }
4.5、LoginController中部分逻辑(登陆登出,403,error等页面)
@RequestMapping("/") public String login() { return "login"; }/** * 错误页面 * @return */ @RequestMapping("/errorPage") public String error() { return "/error"; }

/**

  • 未授权跳转页面
  • @return */ @RequestMapping("/403") public String error403() { return "403"; }

/**

  • 用户中心
  • @param request * @return */

@RequestMapping("/home") public String selectInformation(HttpServletRequest request) { return "index"; }

/**

  • 登出
  • @param request * @return */ @RequestMapping("/loginOut") public String loginOut(HttpServletRequest request) { SecurityUtils.getSubject().logout(); return "redirect:/"; }

/**

  • 处理登陆逻辑
  • @param request * @return */ @RequestMapping(value = "/login", method = RequestMethod.POST) public String toLogin(HttpServletRequest request) { String userName = request.getParameter("userName"); String passwd = request.getParameter("password"); UsernamePasswordToken token = new UsernamePasswordToken(userName, passwd); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); return "redirect:/home"; } catch (Exception e) { request.getSession().setAttribute("msg", "登陆失败,用户名或密码不正确"); return "redirect:/errorPage"; } }
 

4.6 登陆页面省略,此处贴的是登陆成功的页面home页面

//注意:第一种和第三种都是这个写法,下面注释的是第二种

<h1><a th:href="@{/user/addUser}" >添加用户 -admin权限</a></h1> <h1><a th:href="@{/user/selectUser}">用户列表--guest权限</a></h1>

<!--<h1><a th:href="@{/user/addUser}" shiro:hasPermission="admin">添加用户 -admin权限</a></h1>--> <!--<h1><a th:href="@{/user/selectUser}" shiro:hasPermission="guest">用户列表&#45;&#45;guest权限</a></h1>-->

 

第一种配置:

主要是在shrio配置类中写死了路径和权限的关系,html中只是普通的写法,如果未授权会自动跳转到shrio配置类中的/403页面。 缺点是写的多,路径要规范。其他自行思考

shiroFilterFactoryBean.setUnauthorizedUrl("/403");

第二种配置:

区别是在shrio类中拦截所有路径,具体权限控制是在html中写的,比如:

<!--<h1><a th:href="@{/user/addUser}" shiro:hasPermission="admin">添加用户 -admin权限</a></h1>--> <!--<h1><a th:href="@{/user/selectUser}" shiro:hasPermission="guest">用户列表&#45;&#45;guest权限</a></h1>-->

这样的话如果没有权限根本不会显示这个菜单,只显示有权限的菜单。切需要在shrio配置类中配置在thymeleaf使用所需的插件。如下:

@Bean
public ShiroDialect shiroDialect() {
    return new ShiroDialect();
}

第三种配置:

此配置在配置类也是拦截所有,而且页面中也是和第一种一样的普通写法,具体权限控制是在controller中控制,也有人说最好在service中配置,此处是在controller中配置。也就是常见的 几个注解,比如:

@RequiresRoles("guest") 

基于SpringBoot需要在shrio配置类中加入以下配置:

/**
 * 开启shiro aop注解支持.  必需
 * 使用代理方式;所以需要开启代码支持;否则@RequiresRoles等注解无法生效
 *
 * @param securityManager
 * @return
 */
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
    AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
    authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
    return authorizationAttributeSourceAdvisor;
}

@Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
    DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
    advisorAutoProxyCreator.setProxyTargetClass(true);
    return advisorAutoProxyCreator;
}

这样的话没有权限的菜单也会显示出来,可以点击,但是不会跳转到配置的未授权该跳转的页面。后台会报错没有权限,前台没有信息。处理办法是自定义一个异常处理器,捕获到未授权异常就手动跳转到未授权页面。配置如下:

在shrio中配置这个异常处理器

/**
 * 处理未授权的时候跳转问题
 *
 * @return
 */
@Bean
public HandlerExceptionResolver solver() {
    HandlerExceptionResolver handlerExceptionResolver = new MyExceptionResolver();
    return handlerExceptionResolver;
}

新定义一个异常处理器

public class MyExceptionResolver implements HandlerExceptionResolver{

    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("==============异常开始=============");
        //如果是shiro无权操作,因为shiro 在操作auno等一部分不进行转发至无权限url
        if(ex instanceof AuthorizationException){
// 在此处跳转到403未授权页面
            ModelAndView mv = new ModelAndView("redirect:/403");
            return mv;
        }
        return  null;
    }


这样的话就可以实现拦截到未授权异常跳转到403了。

此文仅仅粘贴部分代码,全部代码下载地址是:shrio