在自定义的realm中进行权限控制
- 在shiro-config.xml追加
/user/delete = perms["delete"]
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<!-- 配置登录页 -->
<property name="loginUrl" value="/login.jsp" />
<!-- 配置登录成功后的页面 -->
<property name="successUrl" value="/list.jsp" />
<property name="unauthorizedUrl" value="/unauthorized.jsp" />
<property name="filterChainDefinitions">
<value>
<!-- 静态资源允许访问 -->
<!-- 登录页允许访问 -->
/login.jsp = anon
/test/login = anon
/user/delete = perms["delete"]
/logout = logout
<!-- 其他资源都需要认证 -->
/** = authc
</value>
</property>
</bean>
此时访问/user/delete需要delete权限,在自定义Realm中为用户授权。
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
User user = new User();
user.setUsername(username);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//为用户授权,只需将用户的权限添加到info即可
info.addStringPermission("delete");
List roleList = userService.getRole(user);
if(roleList != null){
for (Role role : roleList) {
authorizationInfo.addRole(role.getName());
}
return authorizationInfo;
}
return null;
}
##使用shiro注解为用户授权 1. 在shiro-config.xml开启shiro注解(硬编码,不好用)
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
2. 在service方法上配置注解@RequiresPermissions(“user:delete”)
@RequiresPermissions("user:delete")
public void delete(){
//逻辑代码
}
使用shiro标签进行权限控制
- 在jsp页面引入shiro标签库
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
- 在页面中使用标签
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="proPath" value="${pageContext.request.contextPath }" />
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- <shiro:principal>代表的是登录的认证名-->
${successMsg } Welcome! <shiro:principal></shiro:principal>
<br><br>
<!-- 有这个角色则会显示User Page链接-->
<shiro:hasAnyRoles name="user">
<a href="${proPath }/user.jsp"> User Page</a>
</shiro:hasAnyRoles>
<br><br>
<!-- 有这个角色则会显示Admin Page链接-->
<shiro:hasAnyRoles name="admin">
<a href="${proPath }/admin.jsp"> Admin Page</a>
</shiro:hasAnyRoles>
<!-- 有这个delete权限则会显示删除按钮-->
<shiro:hasPermission name="delete">
<input type="button" value="删除">
</shiro:hasPermission>
<br><br>
<a href="${proPath }/test/logout">Logout</a>
</body>
</html>
编程方式实现用户权限控制
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole("admin")){
//有权限
}else{
//无权限
}