在pom.xml中添加:
<!--shiro整合thymeleaf的包-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
然后需要在ShiroConfig配置
//整合shiroDialect: 用来整合shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect() {
return new ShiroDialect();
}
接下来在前端页面添加头部命名空间:
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
然后使用shiro权限标签:
这样 只有拥有相应权限 才会显示对应的标签内容
<body>
<h1>首页</h1>
//notAuthenticated标签:用户未进行身份验证,
//即没有调用Subject.login进行登录,包括"记住我"也属于未进行身份验证
<shiro:notAuthenticated>
<a th:href="@{/toLogin}">登录</a>
</shiro:notAuthenticated>
//guest标签:
// 用户没有身份验证时显示相应信息,即游客访问信息。
<shiro:guest>
</shiro:guest>
<p th:text ="${msg}" ></p>
</hr>
<div shiro:hasPermission ="user:add">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission ="user:update">
<a th:href="@{/user/update}">update</a>
</div>
<hr>
//authenticated标签:用户身份验证通过,
//即 Subjec.login 登录成功 不是记住我登录的
<shiro:authenticated>
<a th:href="@{/loginOut}"><button>注销</button></a>
</shiro:authenticated>
</body>
!-- authenticated 用户已经经过身份验证,但不是记住我登录的 -->
<shiro:authenticated>
<shiro:principal />已经经过身份验证<br><br>
</shiro:authenticated>
<!-- 用户没有进行身份验证,记住我自动登录的属于没有进行身份验证 -->
<shiro:notAuthenticated>
用户没有进行身份验证,记住我自动登录的属于没有进行身份验证<br><br>
</shiro:notAuthenticated>
<!-- guest :用户没有验证时显示相应信息 ,如登录等相关信息-->
<shiro:guest>
<a href="login.jsp">登录</a><br><br>
</shiro:guest>
<!-- 当前用户有任意一个角色将会显示body体中的内容 -->
<shiro:hasAnyRoles name="admin,user,manager">
<shiro:principal></shiro:principal>拥有admin/user/manager中的角色<br><br>
</shiro:hasAnyRoles>
<!-- 当前用户有相应的权限,将显示body体中的信息 -->
<shiro:hasPermission name="customer:delete">
<shiro:principal />拥有customer:delete权限<br><br>
</shiro:hasPermission>
<!-- 当前用户没有相应的权限,将显示body体中的信息 -->
<shiro:lacksPermission name="customer:delete">
没有权限customer:delete<br><br>
</shiro:lacksPermission>
<!-- 当前用户没有相应的角色,将显示body中的信息 -->
<shiro:lacksRole name="manager">
<shiro:principal></shiro:principal>没有manager角色<br><br>
</shiro:lacksRole>
<!-- user: 用户已经经过认证/记住我登录后 显示相应的信息 -->
<shiro:user>
<a href="logout">登出</a><br><br>
</shiro:user>
<!-- 当前用户是否拥有该角色,有就显示相关信息 -->
<shiro:hasRole name="admin">
<a href="admin.jsp">Admin Page</a><br><br>
</shiro:hasRole>
shiro注解使用规则:
shiro注解可在 controller 跟 service 中使用
@RequiresAuthentication
表示当前Subject已经通过login 进行了身份验证,
即 Subject. isAuthenticated() 返回 true
@RequiresUser
表示当前Subject 已经身份验证 或者 通过记住我登录 的
@RequiresGuest
表示当前Subject 没有身份验证 或 通过记住我登录过,即是游客身份
@RequiresRoles(value={“admin”, “user”},
logical= Logical.AND)
表示当前 Subject 需要角色为 admin 和 user
@RequiresPermissions(value={“user:create”, “user:delete”},
logical= Logical.OR)
表示当前 Subject 需要权限 user:create 或 user:delete
后续:注解使用?