尝试在POST请求时使用Spring Security 6 -> 403处理Thymeleaf注册表单

flseospp  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(67)

我是Sping Boot 的新手,正在尝试创建一个简单的注册+登录。然而,每当我尝试使用POST请求提交数据时,请求就会被阻止(403),并且我不会被重定向到成功页面。由于请求被阻止,这将导致稍后当我尝试验证提交的输入时出现指针异常。
浏览其他帖子,一个常见的问题似乎是csrf保护,我显式禁用了它。其他帖子中的另一个常见问题是没有授予正确的授权,我试图用.permitAll().anyRequest().authenticated()这样做。因为据我所知,我显式启用了“/register”的所有请求,我希望至少在Controller中的调试消息中获得凭据作为输出。
登记表;

<form th:action="@{register}" method="post" th:object="${registrationRequest}">
            <div class="mb-3">
                <label for="emailInput" class="form-label"></label>
                <input th:field="*{email}" th:classappend="${#fields.hasErrors('email')} ? 'is-invalid'" type="email" class="form-control" id="emailInput" placeholder="Email">
            </div>
            <div class="mb-3">
                <label for="usernameInput" class="form-label"></label>
                <input th:field="*{name}" th:classappend="${#fields.hasErrors('name')} ? 'is-invalid'" type="text" class="form-control" id="usernameInput" placeholder="Username">
            </div>
            <div class="mb-3">
                <label for="passwordInput" class="form-label"></label>
                <input th:field="*{password}" th:classappend="${#fields.hasErrors('password')} ? 'is-invalid'" type="password" class="form-control" id="passwordInput" placeholder="Password">
            </div>
            <div class="mb-3">
                <label for="passwordRepeatInput" class="form-label"></label>
                <input th:field="*{passwordRepeat}" th:classappend="${#fields.hasErrors('passwordRepeat')} ? 'is-invalid'" type="password" class="form-control" id="passwordRepeatInput" placeholder="Password confirmation">
            </div>

            <button type="submit" class="btn btn-outline-dark btn-custom">Sign up!</button>
        </form>

字符串
控制器中的路由;

@RequestMapping(value="register")
    public String showRegisterPage(Model model) {
        model.addAttribute("registrationRequest", new RegistrationRequest());
        return "user/user-add";
    }
    
    @PostMapping(value="register")
    public String processRegisterRequest(@ModelAttribute RegistrationRequest registrationRequest, BindingResult result) {
    
        System.out.println("DEBUG: " + registrationRequest.getName() + registrationRequest.getEmail() + registrationRequest.getPassword());
        System.out.println(result.getAllErrors());
    
        userService.register(registrationRequest);
        return "user/registration-success";
    }


可能配置错误的SecurityFilterChain;

@Bean
    public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                .requestMatchers(
                        "/",
                        "/register",
                        "/login",
                        "/css/style.css")
                .permitAll()
                .anyRequest()
                .authenticated())
                .csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable);

        return http.build();
    }


控制台错误输出;

2023-11-25T17:50:38.436+01:00 DEBUG 11889 --- [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2023-11-25T17:50:47.352+01:00 DEBUG 11889 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing POST /register
2023-11-25T17:50:47.354+01:00 DEBUG 11889 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Secured POST /register
DEBUG: nullnullnull
[]
DEBUG: nullnull
2023-11-25T17:50:47.360+01:00 DEBUG 11889 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2023-11-25T17:50:47.361+01:00 ERROR 11889 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "String.length()" because "password" is null] with root cause

java.lang.NullPointerException: Cannot invoke "String.length()" because "password" is null


编辑
添加了类RegistrationRequest;

import lombok.*;

@Getter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString

public class RegistrationRequest {
    private String email;
    private String name;
    private String password;
    private String passwordRepeat;
}

envsm3lx

envsm3lx1#

原来我的代码中有两个问题;
1.根据@ Toerktumplayer的评论;为了解决403错误,我需要将.formLogin(Customizer.withDefaults())添加到SecurityFilterChain。

@Bean
public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception {
    http.authorizeHttpRequests((authorize) -> authorize
            .requestMatchers("/","/register","/login","/css/style.css")
            .permitAll()
            .anyRequest()
            .authenticated())
            .formLogin(Customizer.withDefaults())
            .csrf(AbstractHttpConfigurer::disable)
            .cors(AbstractHttpConfigurer::disable);

    return http.build();
}

字符串

  1. RegistrationRequest中缺少@Setter注解,因此无法设置属性的值。
import lombok.*;
    
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
    
public class RegistrationRequest {
    private String email;
    private String name;
    private String password;
    private String passwordRepeat;
}

相关问题