Shiro授权

目标
1、shiro授权角色、权限
2、Shiro的注解式开发

在这里插入图片描述

授权

<select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
    where u.userid = ur.userid and ur.roleid = r.roleid
    and u.userid = #{userid}
</select>
<select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select p.permission from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
  where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
  and u.userid = #{userid}
</select>

Service层

package com.likang.service;

import com.likang.model.ShiroUser;
import org.apache.ibatis.annotations.Param;

import java.util.Set;

/**
 * @author 木子康
 */
public interface ShiroUserService {
    ShiroUser queryByName( String uname);

    int insert(ShiroUser record);

    Set<String> getRolesByUserId(Integer userid);

    Set<String> getPersByUserId(Integer userid);
}

重写自定义realm中的授权方法

package com.likang.shiro;

import com.likang.model.ShiroUser;
import com.likang.service.ShiroUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author 木子康
 */
public class MyRealm extends AuthorizingRealm {
    private ShiroUserService shiroUserService;

    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }

    public void setShiroUserService(ShiroUserService shiroUserService) {
        this.shiroUserService = shiroUserService;
    }

    /**
     * 授权的方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String uname=principalCollection.getPrimaryPrincipal().toString();
        ShiroUser shiroUser = this.shiroUserService.queryByName(uname);
        Set<String> persByUserId = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
        Set<String> rolesByUserId = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(rolesByUserId);
        info.setStringPermissions(persByUserId);
        return info;
    }

    /**
     * 身份认证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname=authenticationToken.getPrincipal().toString();
        String pwd=authenticationToken.getCredentials().toString();
        ShiroUser shiroUser=shiroUserService.queryByName(uname);

        AuthenticationInfo info=new SimpleAuthenticationInfo(
            shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                this.getName()
        );
        return info;
    }
}

注解式开发

常用注解介绍

  @RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true
  @RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
  @RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
  @RequiresRoles(value = {"admin","user"},logical = Logical.AND):表示当前Subject需要角色admin和user
  @RequiresPermissions(value = {"user:delete","user:b"},logical = Logical.OR):表示当前Subject需要权限user:delete或者user:b


Springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <aop:aspectj-autoproxy/>
    <context:component-scan base-package="com.likang"/>

    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
    <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--3) ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true"></property>
    </bean>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.apache.shiro.authz.UnauthorizedException">
                    unauthorized
                </prop>
            </props>
        </property>
        <property name="defaultErrorView" value="unauthorized"/>
    </bean>


    <!--4) 单独处理图片、样式、js等资源 -->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <!--<mvc:resources location="/images/" mapping="/images/**"/>-->
    <!--<mvc:resources location="/js/" mapping="/js/**"/>-->
    <mvc:resources location="/static/" mapping="/static/**"/>


</beans>

Controller

package com.likang.controller;

import com.likang.model.ShiroUser;
import com.likang.service.ShiroUserService;
import com.likang.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 木子康
 */
@Controller
public class ShiroUserController {
    @Autowired
    private ShiroUserService shiroUserService;

    @RequestMapping("login")
    public String login(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        UsernamePasswordToken token = new UsernamePasswordToken(uname,pwd);

        try {
//            这里会跳转到MyRealm中的认证方法
            subject.login(token);
            req.getSession().setAttribute("username",uname);
            return "main";
        }catch (Exception e){
            req.setAttribute("message","用户名密码错误");
            return "login";
        }
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }


    @RequestMapping("/register")
    public String register(HttpServletRequest req, HttpServletResponse resp){
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        String salt = PasswordHelper.createSalt();
        String credentials = PasswordHelper.createCredentials(pwd, salt);

        ShiroUser shiroUser=new ShiroUser();
        shiroUser.setUsername(uname);
        shiroUser.setPassword(credentials);
        shiroUser.setSalt(salt);
        int insert = shiroUserService.insert(shiroUser);
        if(insert>0){
            req.setAttribute("message","注册成功");
            return "login";
        }
        else{
            req.setAttribute("message","注册失败");
            return "register";
        }
    }

    @RequiresUser
    @ResponseBody
    @RequestMapping("passUser")
    public String passUser(){
        return "用户认证访问成功!!!";
    }
    @RequiresRoles(value = {"2"} ,logical = Logical.AND)
    @ResponseBody
    @RequestMapping("passRole")
    public String passRole(){
        return "角色访问成功!!!";
    }
    @RequiresPermissions(value = {"user:update","user:load"},logical = Logical.AND)
    @ResponseBody
    @RequestMapping("passPer")
    public String passPer(){
        return "权限访问成功!!!";
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值