【问题标题】:Showing specific content for anonymous users with Thymeleaf Security使用 Thymeleaf Security 为匿名用户显示特定内容
【发布时间】:2019-08-09 17:46:47
【问题描述】:

我正在努力解决以下问题。我有一个导航栏,我想根据用户是否是匿名/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 依赖项:

编译("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 的帖子,但没有一个给出明确的答案。

谢谢。

【问题讨论】:

    标签: spring spring-boot spring-security thymeleaf


    【解决方案1】:

    还有一个不错的百里香附加模块: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>
    

    【讨论】:

    • 我试过了。似乎无法识别 sec:authorize 属性,只显示全部。不过谢谢!
    【解决方案2】:

    仅显示匿名块:

    <div th:if="!${#request.userPrincipal}">
      <!-- content for anonymous -->
    </div>
    

    【讨论】:

    • 像魅力一样工作。谢谢! :)
    猜你喜欢
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2020-07-05
    相关资源
    最近更新 更多