shiro角色授权与注解开发
shiro授权角色、权限
授权
ShiroUserMapper添加方法
在ShiroUserMapper.xml中新增内容
根据用户登录的id进行查询权限id
<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层
ShiroUserService
package com.tanle.service;
import com.tanle.model.ShiroUser;
import org.apache.ibatis.annotations.Param;
import java.util.Set;
/**
* @author tanle
* @site www.tanle.com
* @company xxx公司
* @create 2020-11-02 19:51
*/
public interface ShiroUserService {
public ShiroUser queryByName(String username);
Set<String> getRolesByUserId(Integer userid);
Set<String> getPersByUserId(Integer userid);
}
ShiroUserServiceImpl
package com.tanle.service.impl;
import com.tanle.mapper.ShiroUserMapper;
import com.tanle.model.ShiroUser;
import com.tanle.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* @author tanle
* @site www.tanle.com
* @company xxx公司
* @create 2020-11-02 19:51
*/
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
@Autowired
private ShiroUserMapper shiroUserMapper;
@Override
public ShiroUser queryByName(String username) {
return shiroUserMapper.queryByName(username);
}
@Override
public Set<String> getRolesByUserId(Integer userid) {
return shiroUserMapper.getRolesByUserId(userid);
}
@Override
public Set<String> getPersByUserId(Integer userid) {
return shiroUserMapper.getPersByUserId(userid);
}
}
重写自定义realm中的授权方法
MyRealm
package com.tanle.shiro;
import com.tanle.model.ShiroUser;
import com.tanle.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.authz.permission.RolePermissionResolver;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.util.Collection;
import java.util.Set;
/**
* @author tanle
* @site www.tanle.com
* @company xxx公司
* @create 2020-11-02 19:54
*/
public class MyRealm extends AuthorizingRealm {
private ShiroUserService shiroUserService;
public ShiroUserService getShiroUserService() {
return shiroUserService;
}
public void setShiroUserService(ShiroUserService shiroUserService)
{
this.shiroUserService = shiroUserService;
}
/**授权的方法
* AuthorizingRealm
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String uname=principalCollection.getPrimaryPrincipal().toString();
ShiroUser shiroUser = this.shiroUserService.queryByName(uname);
/*当前用户所拥有的的权限*/
Set<String> perids = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
Set<String> roleIds = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
/*角色设置*/
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
info.setRoles(roleIds);
info.setStringPermissions(perids);
return info;
}
/**
* 身份认证的方法
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
// 获取身份(Principal)
String username=authenticationToken.getPrincipal().toString();
// 获取凭证/密码(Credentials)
String pwd=authenticationToken.getCredentials().toString();
// 调用方法
ShiroUser shiroUser = shiroUserService.queryByName(username);
/**
* 第一个参数:principal(身份)
* 第二个参数:hashedCredentials(凭证)
* 第三个参数:credentialsSalt(凭证盐)
* 第四个参数:realmName(realm的名字)
*/
AuthenticationInfo info =new SimpleAuthenticationInfo(
shiroUser.getUsername(),
shiroUser.getPassword(),
ByteSource.Util.bytes(shiroUser.getSalt()),
// this代表类名,类对象的实例MyRealm
this.getName()
);
return info;
}
}
测试结果
这里登录的是数据库ls的账户
有个人密码修改与老师简介的查看权限其他无权限查看
注解式开发
常用注解介绍
@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-servlet.xml中添加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"
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.tanle"/>
<!--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>
<!--shiro-->
<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.tanle.controller;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* @author tanle
* @site www.tanle.com
* @company xxx公司
* @create 2020-11-02 19:57
*/
@Controller
public class ShiroUserController {
/**
* 登录
* @param req
* @return
*/
@RequestMapping("/login")
public String login(HttpServletRequest req){
String uname=req.getParameter("username");
String pwd=req.getParameter("password");
UsernamePasswordToken token=new UsernamePasswordToken(uname,pwd);
Subject subject = SecurityUtils.getSubject();
try {
// 这里会跳转到MyRealm中的认证方法
subject.login(token);
req.getSession().setAttribute("username",uname);
return "main";
}catch (Exception e){
req.setAttribute("message","用户名密码错误!!!!");
return "login";
}
}
/**
* 退出
* @param req
* @return
*/
@RequestMapping("/logout")
public String logout(HttpServletRequest req){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/login.jsp";
}
/*shiro注解*/
@RequiresUser
@ResponseBody
@RequestMapping("/passUser")
public String passUer(){
return "身份认证成功 能够访问";
}
@RequiresRoles(value = {"1","4"},logical = Logical.AND)
@ResponseBody
@RequestMapping("/passRole")
public String passRole(){
return "角色认证成功 能够访问";
}
@RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
@ResponseBody
@RequestMapping("/passPer")
public String passPer(){
return "权限认证成功 能够访问";
}
}
在main.jsp中添加
<ul>
shiro注解
<li>
<a href="${pageContext.request.contextPath}/passUser">用户认证</a>
</li>
<li>
<a href="${pageContext.request.contextPath}/passRole">角色</a>
</li>
<li>
<a href="${pageContext.request.contextPath}/passPer">权限认证</a>
</li>
</ul>
结果
zs只能查看身份认证的按钮内容
ls、ww可以看权限认证按钮内容
zdm可以看所有按钮的内容