我正在努力解决以下问题。我有一个导航栏,我想显示/隐藏特定内容,具体取决于用户是否匿名/ role_user / role_admin。这是我的html:
<html lang="en" xmlns:th="http://www.thymeleaf.org xmlns:sec="http://www.w3.org/1999/xhtml">
<head>
<title>Beer Tag Home</title>
</head>
<body>
<nav class="navbar" role="navigation" id="mainNav">
<div class="container">
<a class="navbar-brand">Foo App</a>
<div class="navbar-collapse">
<ul class="navbar-nav">
<li class="nav-item"><a About</li>
<li class="nav-item">FAQ</li>
<div class="row" th:if="not${#authentication.isAuthenticated()}">
//this here will not even let spring boot up the app
<li class="nav-item">LOGIN</li>
</div>
<div class="row" <div th:if="${#httpServletRequest.isUserInRole('ROLE_USER')}">
<li class="nav-item">USER PANEL</li>
</div>
</ul>
</div>
</div>
</nav>
基本上,我想查看用户是否只有匿名用户才能登录。如果用户登录,则可以访问页面上的其他内容。这也是我的gradle依赖项:
compile(“ org.springframework.boot:spring-boot-devtools”)
compile 'mysql:mysql-connector-java'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.11.RELEASE'
compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity4', version: '3.0.4.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
我已经阅读了关于SO的几乎所有关于此主题的文章,但没有一个给出明确的答案。
谢谢。
答案 0 :(得分:0)
仅显示一个用于匿名的屏蔽:
<div th:if="!${#request.userPrincipal}">
<!-- content for anonymous -->
</div>
答案 1 :(得分:0)
还有一个不错的百里香Extras模块:https://github.com/thymeleaf/thymeleaf-extras-springsecurity
添加后,您可以像这样使用它:
<div sec:authorize="isAuthenticated()">
This content is only shown to authenticated users.
</div>
<div sec:authorize="hasRole('ROLE_ADMIN')">
This content is only shown to administrators.
</div>
<div sec:authorize="hasRole('ROLE_USER')">
This content is only shown to users.
</div>