Форма логина Spring security на главной странице

Рейтинг: 0Ответов: 1Опубликовано: 31.01.2023

Возможно сделать форму логина на главной странице используя spring security? Если ввести .loginPage("/"), форма логина перестает работать, при этом если ввести .loginPage("/*"), то форма начинает работать, но в строке браузера например при ошибке ввода появляется эта самая звездочка, возможно сделать это как то более грамотно?

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
     public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests()
                    .requestMatchers("/adminPage/**").hasRole("ADMIN")
                    .requestMatchers("/userPage/**").hasAnyRole("USER", "ADMIN")
                    .requestMatchers("/registrationPage/**", "/**").permitAll()
                .and()
                .formLogin()
                    .loginPage("/")
                    .permitAll()
                .and()
                .logout()
                    .logoutSuccessUrl("/")
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true)
                .and()
                .httpBasic();
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Контроллер формы

@Controller
@AllArgsConstructor
public class RegistrationController {
    private final UserService userService;

    // Login form
    @PostMapping("/login")
    public String loginForm(@RequestParam String username) {
        userService.loadUserByUsername(username);
        return "redirect:/";
    }

    // Registration form
    @PostMapping("/registrationForm")
    public String registrationForm(User user, Model model) {
        if (!userService.registrationUser(user)) {
            model.addAttribute("usernameError", "Уже есть такой пользователь");
            return "registrationPage";
        }
        userService.registrationUser(user);
        return "redirect:/";
    }
}

Контроллер страницы

@Controller
@AllArgsConstructor
public class PageController {
    private final AdminService adminService;
    private final UserService userService;
    private final PostService postService;

    // Index page
    @GetMapping("/")
    public String index(@AuthenticationPrincipal User user, Model model) {
        model.addAttribute("users", user);
        model.addAttribute("posts", postService.showAllPosts());
        return "index";
    }

    // Registration page
    @GetMapping("/registrationPage")
    public String registrationPage() {
        return "registrationPage";
    }

Html

<div class="login col-3">
  <div sec:authorize="isAuthenticated()">
    <div th:each="user : ${users}">
      <a th:text="Profile + ' ' + ${user.username}" th:href="@{/userPage/{id}(id=${user.id})}"/>
      <form th:action="@{/logout}" method="post">
        <input type="submit" value="Logout">
      </form>
    </div>
  </div>

  <div sec:authorize="!isAuthenticated()">
    <div class="form">
      <form name="f" th:action="@{/login}" method="post">
        <fieldset>
          <label for="username">Username</label>
          <input type="text" id="username" name="username"/>
          <label for="password">Password</label>
          <input type="password" id="password" name="password"/>
          <div class="form-actions">
            <button type="submit" class="btn">Log in</button>
          </div>
          <div>
            <a th:href="@{/registrationPage}">Registration</a>
          </div>
        </fieldset>
      </form>
    </div>
  </div>
</div>

Ответы

▲ 0Принят

Решил вопрос сам, не знаю насколько правильно, но все же работает. В html форме убрал слово 'login'

<form name="f" th:action="@{/}" method="post">

Ну и в контроллере который за него отвечал тоже, и все заработало как надо

// Login form
    @PostMapping("/")
    public String loginForm(@RequestParam String username) {
        userService.loadUserByUsername(username);
        return "redirect:/";
    }