Shiro实现登陆及授权,ajax请求无权限的json返回

  1. Shiro的介绍
    ① Apache Shiro: Java安全框架,有身份验证、授权、密码学和会话管理。
    ② Shiro是开源项目
    ③ 安全框架分类
    a) Spring security 重量级安全框架
    b) Apache Shiro轻量级安全框架
    ④ Java中框架轻重量级的区别
    a) 学习成本
    b) 实际开发过程中的性能开销大小
    ⑤ Shiro对于权限判定是分两步走:身份认证[登录]、授权管理[url权限]
  2. Shiro的功能
    Shiro实现登陆及授权,ajax请求无权限的json返回

主要是四大基础功能
① Authentication(身份认证):有时也简称为“登录”,这是一个证明用户是他们所说的他们是谁的行为。
② Authorization(授权):访问控制的过程,也就是绝对“谁”去访问“什么”权限。
③ Session Management:管理用户特定的会话,即使在非 Web 或 EJB 应用程序。
④ Cryptography:通过使用加密算法保持数据安全同时易于使用。
4. Shiro在应用程序中的执行流程
Shiro实现登陆及授权,ajax请求无权限的json返回

  1. Shiro的核心API
    ① Subject:Shiro与外部交互的核心API,可以是任何语言写的程序
    ② SecurityManager:Subject管理器,所有的Shiro权限判定都有他完成
    ③ UsernamePasswordToken:把前台传入的username和password封装成token对象传给SecurityManager处理
    ④ SessionManager:会话管理器,可以直接对session执行CRUD
    ⑤ CacheManager:缓存管理器
    ⑥ SimpleHash:密码学核心代码,根据加密规则对源数据进行加密

理论说多了 头痛,直接上代码:
自定义Realm实现授权及认证【1. 继承org.apache.shiro.realm.AuthorizingRealm抽象类】

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;


    /**
     * 授权方法(告诉shrio当前用户有哪些权限)
     * @param principalCollection
     * @return
     */  
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        获得当前登陆用户名
        Employee  username= (Employee) principalCollection.getPrimaryPrincipal();
//        查询当前用户名所有的权限
        List<Permission> permissions = permissionService.selectByEmployeeId(username.getId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (Permission permission : permissions) {
//            将当前用户权限设置进去
            info.addStringPermission(permission.getSn());
        }
        return info;
    }

    /**
     * 认证方法(及登陆认证)
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        强转获得登陆的用户和登陆的密码
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        Employee employee = employeeService.findByUserame(username);
        if (employee==null) {
//            当用户不存在的时候抛出用户不存在的异常
            throw new UnknownAccountException(username);
        }
//封装info对象
        Object principal = employee;
        Object hashedCredentials = employee.getPassword();//凭证,数据库中加了密的密码
        ByteSource salt = ByteSource.Util.bytes(MD5Utils.SALT);//盐值
        //        getName()在多认证方式的时候使用,单认证实现类用处不大
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,hashedCredentials,salt,getName());
        return info;
    }
}

工具类

  /**
     * MD5的工具类
     */
        public class MD5Utils {
            public static String SALT = "crm";//盐值
            public static final int COUNT = 1000;//加密次数
        
            /**
             * 加密
             * @param source
             * @return
             */
            public static String encrypt(String source){
                String algorithmName = "MD5";//加密算法
                SimpleHash sh = new SimpleHash(algorithmName,source,SALT,COUNT);
                return sh.toString();
            }
        }

shiro配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


    <!--shiro的核心对象SecurityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--配置自己的认证,授权类-->
        <property name="realm" ref="MyRealm"/>
    </bean>

    <bean id="MyRealm" class="cn.test.ddd.shrio.MyRealm">
        <!--配置shrio的认证匹配规则-->
        <property name="credentialsMatcher">
            <!--配置匹配器-->
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!--设置加密算法及加密次数-->
                <property name="hashAlgorithmName" value="MD5"/>
                <property name="hashIterations" value="1000"/>
            </bean>
        </property>
    </bean>


    <!--配置shiro过滤器-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!--
       登录的url
       当访问需要身份认证才能访问的资源时,如果没有认证,则跳转到这个页面
         -->
        <property name="loginUrl" value="/index.jsp"/>
        <!--认证成功后的主页面-->
        <property name="successUrl" value="/main"/>
        <!--访问没有授权的网站时转跳的网页-->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <!--该处对映自动调用权限过滤工厂bean的id-->
        <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"/>
        <!--自定义拦截器,拦截访问权限,当被拦截的权限是ajax请求,的时候返回json字符串给以提示,否则转跳无权限页面-->
        <property name="filters">
            <map>
                <!--该Key值得使用在
                自定义FilterChainDefinitionMapFactory类中字符串拼接
                map.put(permission.getResource(), "perms["+permission.getSn()+"]");//需要判断权限的路径
                -->
                <entry key="perms">
                    <bean class="cn.test.ddd.shrio.ShiroPermsFilter"/>
                </entry>
            </map>
        </property>

   <!--     <property name="filterChainDefinitions">
            <value>
                &lt;!&ndash;anon 需要放行的资源及URL&ndash;&gt;
                /login.jsp = anon
                /login = anon
                /static/** = anon
                &lt;!&ndash;logout 退出的资源路径&ndash;&gt;
                /logout = logout
                # everything else requires authentication:
                &lt;!&ndash; 需要匿名拦截的  资源及路径&ndash;&gt;
                /** = authc
            </value>
        </property>-->
    </bean>
    <!--配自己的权限过滤工厂-->
    <bean id="chainDefinitionMapFactory" class="cn.test.ddd.web.filter.FilterChainDefinitionMapFactory"/>
    <!--配置自动调用我们的过滤工厂的方法-->
    <bean factory-bean="chainDefinitionMapFactory" factory-method="getPermissionMap" id="filterChainDefinitionMap"/>
</beans>

spring引入shrio配置

<import resource="applicationContext-shiro.xml"/>

获取权限判断的map实现类

/**
 * 该类为获取数据库中需要判断那些路径需要权限才能访问的
 */
public class FilterChainDefinitionMapFactory {
    @Autowired
    private IPermissionService permissionService;

    public Map<String, String> getPermissionMap(){
//        LinkedHashMap是一个有序的map集合
        Map<String, String> map = new LinkedHashMap<>();
        List<Permission> all = permissionService.getAll();
        map.put("/login", "anon");//放行的路径
        map.put("/logout", "logout");//退出的路径
        map.put("/static/**", "anon");//放行静态资源
        for (Permission permission : all) {
            map.put(permission.getResource(), "perms["+permission.getSn()+"]");//需要判断权限的路径
        }
        map.put("/**", "authc");//匿名身份验证
        return map;
    }
    
}

web.xml配置shiro拦截器

 <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

当需要过滤ajax请求判断权限,跟踪源码发现最后实现无权限转跳的实现类是PermissionsAuthorizationFilter ,所以自定义一个类继承该类,覆写方法,加以判断是否是ajax请求,添加对应处理。

public class ShiroPermsFilter extends PermissionsAuthorizationFilter {
    /**
     * shiro认证perms资源失败后回调方法
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //获取当前用户
        Subject subject = this.getSubject(httpServletRequest, httpServletResponse);
        //判断是否已经认证
        if (subject.getPrincipal() == null) {
            //没有认证则重定向到登录页面
            this.saveRequestAndRedirectToLogin(httpServletRequest, httpServletResponse);
        }else {
//认证过了
            String requestedWith = httpServletRequest.getHeader("X-Requested-With");
            if (StringUtils.isNotEmpty(requestedWith) &&
                    StringUtils.equals(requestedWith, "XMLHttpRequest")) {//如果是ajax返回指定格式数据
//           //是ajax请求
                httpServletResponse.setContentType("text/json;charset=UTF-8");//设置响应头
//                返回json 数据,告知无权限
                httpServletResponse.getWriter().write("{\"success\":false,\"message\":\"对不起,你没有这个权限!\",\"errorCode\":-10001}");
            } else {//如果是普通请求进行重定向
                //不是ajax请求
                String unauthorizedUrl = this.getUnauthorizedUrl();
                if (StringUtils.isNotEmpty(unauthorizedUrl)) {
                    WebUtils.issueRedirect(httpServletRequest, httpServletResponse, unauthorizedUrl);
                } else {
                    WebUtils.toHttp(httpServletResponse).sendError(401);
                }
            }

        }
        return false;
    }
}