0

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.company</groupId>
    <artifactId>blog</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>blog</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>15</java.version>
    </properties>


    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.7.3</version>
        </dependency>

        <!-- Добавилось автоматически -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>


        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

SpringSecurityDialect

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;

@Configuration
public class ThymeleafConfig {

    @Bean
    public SpringSecurityDialect springSecurityDialect() {
        return new SpringSecurityDialect();
    }
}

HTML

            <div>
<!--                <sec:authorize access="isAnonymous()">-->
                <sec:authorize access="!isAuthenticated()">
                    <form  th:action="@{/Authorization}" method="post">
                        <input type="submit" value="Авторизоваться">
                    </form>
                </sec:authorize>
            </div>

            <div>
                <sec:authorize access="isAuthenticated()">
                    <form  th:action="@{/logout}" method="post">
                        <input type="submit" value="Выйти">
                    </form>
                </sec:authorize>
            </div>

Не знаю куда деваться и что смотреть. Собрал свой код по кускам что изложено в документации и также на stackoverflow.

Что я делаю не так, или может чего-то не хватает. Хочу чтобы когда пользователь авторизовался, то "Авторизоваться" менялось на "Выйти"

У меня имеется защита, БД с ролями, переадресация на страницу в зависимости от роли (У каждой роли своя стартовая страница после входа).

Определенные пользователи могут авторизоваться. Авторизованные пользователи также могут смотреть главную страницу, но сейчас им доступна кнопка "Авторизоваться", а я хочу сделать, чтобы было "Выйти"

2 ответа 2

1

В документации по Spring Security Dialect sec:authorize это атрибут а не HTML элемент. Ваш код почти закончен и будет работать если поставить атрибут в коректный HTML таг. Например ...

<div sec:authorize="!isAuthenticated()">
    <form  th:action="@{/Authorization}" method="post">
          <input type="submit" value="Авторизоваться">
    </form>
</div>

<div sec:authorize="isAuthenticated()">
    <form  th:action="@{/logout}" method="post">
        <input type="submit" value="Выйти">
    </form>
</div>
2
  • Да, безусловно :) Я кстати говоря такой вариант тоже пробовал, но был безуспешен. Но Ваше сообщение дало мне знать, что я делал все правильно и просто потом поигрался с зависимостями и вуаля, я добился своей цели :))) 25 мая 2021 в 19:34
  • 1
    Ниже мой код который работает для меня 25 мая 2021 в 19:38
0
    <div class="float" sec:authorize="!isAuthenticated()">
                <form  th:action="@{/Authorization}" method="post">
                    <input type="submit" value="Авторизоваться">
                </form>
            </div>

            <div class="float" sec:authorize="isAuthenticated()">
                <form  th:action="@{/logout}" method="post">
                    <input type="submit" value="Выйти">
                </form>
            </div>

<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>


        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>

@Configuration
public class ThymeleafConfig {

    @Bean
    public SpringSecurityDialect springSecurityDialect() {
        return new SpringSecurityDialect();
    }

}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.