shiro授权 及 注解式开发

shiro授权 及 注解式开发

基础了解:

①:Shiro 简介 及 与 web 容器的集成:https://blog.csdn.net/qq_44854784/article/details/102534157

②:Shiro认证 及 SSM整合:https://blog.csdn.net/qq_44854784/article/details/102557732

shiro授权角色、权限

思路图:
在这里插入图片描述
ShiroUserMapper.xml

  <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>

ShiroUserMapper

	Set<String> getRolesByUserId(Integer uid);

    Set<String> getPersByUserId(Integer uid);

MyRealm

package com.Tang.shiro;

import com.Tang.model.ShiroUser;
import com.Tang.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 java.util.Set;

/**
 * @author Tang
 */
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 principals) {
        ShiroUser shiroUser = this.shiroUserService.queryByName(principals.getPrimaryPrincipal().toString());
        Set<String> roleids = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
        Set<String> perids = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleids);
        info.setStringPermissions(perids);
        return info;
    }

    /**
     * 认证
     * @param token         从jsp传递过来的用户名密码组合成的一个token对象
     * @return
     * @throws AuthenticationException
     *
     * 认证过程:
     * 1.数据源(ini--》数据库)
     * 2.AuthenticationInfo将数据库的用户信息给subject主题做shiro认证的
     *      2.1.需要在当前的realm中调用service来验证,当前用户是否在数据库中存在
     *      2.2.盐加密
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String uname = token.getPrincipal().toString();
        String pwd = token.getCredentials().toString();
        ShiroUser shiroUser = this.shiroUserService.queryByName(uname);
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                this.getName()//MyRealm的全路径
        );
        return info;
    }
}

shiro注解式开发

常用注解:

@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

配置spring-MVC.xml

    <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>

Controller中运用注解

    /**
     * 用户认证注解
     * @param req
     * @param resp
     * @return
     */
    @RequiresUser
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest req,HttpServletResponse resp){
        return "admin/addUser";
    }

    /**
     * 角色认证注解
     * @param req
     * @return
     */
    @RequiresRoles(value = {"1","4"},logical = Logical.OR)
    @RequestMapping("/passRole")
    public String passRole(HttpServletRequest req,HttpServletResponse resp){
        return "admin/listUser";
    }

    /**
     * 权限认证注解
     * @param req
     * @return
     */
    @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
    @RequestMapping("/passPer")
    public String passPer(HttpServletRequest req,HttpServletResponse resp){
        return "admin/resetPwd";
    }


    @RequestMapping("/unauthorized")
    public String unauthorized(HttpServletRequest req,HttpServletResponse resp){
        return "unauthorized";
    }

测试:main.jsp

    shiro注解标签
    <li>
        <r:hasPermission name="user:create">
            <a href="${pageContext.request.contextPath}/passUser">用户认证</a>
        </r:hasPermission>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passRole">角色认证</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passPer">权限认证</a>
    </li>
发布了75 篇原创文章 · 获赞 12 · 访问量 3896

猜你喜欢

转载自blog.csdn.net/qq_44854784/article/details/102596525