Reputation: 1330
I'm struggling with the following. I have a nav-bar and i want to show/hide specific content depending on whether the user is anonymous/role_user/role_admin. Here is my 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>
Essentially I want to see if a user is Anonymous if so he can only log in. If a user is logged in he can access other content on the page. Here are my gradle dependencies as well:
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'
I've read almost all posts on SO regarding this subject, but none of them gives a definitive answer.
Thank you.
Upvotes: 2
Views: 1663
Reputation: 561
There is also a nice thymeleaf extras module: https://github.com/thymeleaf/thymeleaf-extras-springsecurity
After adding it you can use it like this:
<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>
Upvotes: 1
Reputation: 16604
To display a block for anonymous only:
<div th:if="!${#request.userPrincipal}">
<!-- content for anonymous -->
</div>
Upvotes: 3