Java Spring安全配置-添加新用户时出现错误代码302

plicqrtu  于 2023-05-05  发布在  Spring
关注(0)|答案(1)|浏览(163)

登录,注册和注销的实现已经完成,并在postman中进行了测试,表现出应有的行为。
尽管如此,当我试图构建表单来处理身份验证时,我遇到了几个问题。
简而言之,我实现了一个login.html和一个register.html。两个服务都有单独的控制器。详情见下文
register.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Register</title>
</head>
<body>
<h1>Register</h1>
<form method="post" action="/register">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" required><br><br>
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" required><br><br>
    <input type="submit" value="Register">
    <a href="/login" class="btn btn-primary">Login</a>
</form>
</body>
</html>

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login</title>
</head>
<body>
<h1>Login</h1>
<!-- Display error message if there is a login error -->
<div th:if="${error}">
    <p style="color: red;">Incorrect username or password.</p>
</div>
<form method="post" action="/login">
    <label for="email">email:</label>
    <input type="text" name="email" id="email" required><br><br>
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" required><br><br>
    <input type="submit" value="Login">
    <a href="/register" class="btn btn-primary">Register</a>
</form>
</body>
</html>

LoginControllerRegisterController

@Controller
@RequestMapping("/register")
@RequiredArgsConstructor
public class RegisterController {

    private final AuthenticationService authService;

    @GetMapping
    public String showRegisterForm() {
        return "register";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String register(@RequestParam String username, @RequestParam String password, HttpServletResponse response, Model model) {
        System.out.println("I'm here");
        AuthenticationResponse authResponse = authService.register(new RegistrationRequest(username,  password));
        // Set token as cookie
        Cookie cookie = new Cookie("jwtToken", authResponse.getAccessToken());
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        return "dashboard";
    }
}

@Controller
@RequestMapping("/login")
@RequiredArgsConstructor
public class LoginController {

    private final AuthenticationService authService;

    @GetMapping
    public String showLoginForm() {
        return "login";
    }

    @PostMapping
    public String login(@RequestParam String username, @RequestParam String password, HttpServletResponse response, Model model) {
        try{
            AuthenticationResponse authResponse = authService.authenticate(new AuthenticationRequest(username, password));
            // Set token as cookie
            Cookie cookie = new Cookie("jwtToken", authResponse.getAccessToken());
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return "redirect:/dashboard";
        }catch (AuthenticationException e) {
            model.addAttribute("error", true);
            return "login";
        }
    }
}

另外,我将提供`securityFilterChain'配置:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAthFilter jwtAthFilter;
    private final AuthenticationProvider authenticationProvider;
    private final LogoutHandler logoutHandler;

    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeHttpRequests()
                .requestMatchers("/dashboard").permitAll()
                .and()
                .authorizeHttpRequests()
                .requestMatchers("/account").authenticated()
                .and()
                .formLogin(form -> form.loginPage("/register").permitAll())
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAthFilter, UsernamePasswordAuthenticationFilter.class)
                .logout()
                .logoutUrl("/auth/logout")
                .addLogoutHandler(logoutHandler)
                .logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext());
        return http.build();
    }
}

我认为这与SecurityConfig类中的错误配置有关。自从我尝试通过注册发送帖子以来,我每次都会回到注册页面。
第一个问题,可能是根本原因,如下所示:

  1. webapp启动。
  2. register.html表单显示正确
    1.在密码和用户名字段中插入值
    1.当按下提交按钮时,出现错误代码302,页面被重定向到http://localhost:5000/register?error url。
    备注:
    1.我还尝试访问http://localhost:5000/dashboard URL,但它无法访问,但它被定义为它应该是
    1.在调试模式下,我遇到了这样的情况:由于没有显示日志,也没有在断点处停止,因此没有调用RegisterController中的POST请求
    1.数据库中也没有创建用户(可能是因为错误代码302,流没有到达该点。
    不幸的是,大多数的答案都是声明不推荐的WebSecurityConfigurerAdapter类,所以我认为这将是一个好主意,讨论这个主题的其他新手。
    谢谢你
xfb7svmp

xfb7svmp1#

我找到了答案,但我将留一个问题,以防有人有同样的错误:
不要在securityFilterChain中使用以下属性来注册新用户:
.formLogin(form -> form.loginPage("/register.html").permitAll())
而不是像requestMatchers()那样:
.requestMatchers("/register").permitAll()
这似乎很简单,但这也是过程的一部分。
祝你好运!

相关问题