在 Thymeleaf 和 Spring 的标头中传递 JWT 令牌

问题描述 投票:0回答:0

我想将 JWT 令牌作为

Authorization
标头与我的请求一起传递,但我正在使用 Thymeleaf 和 Spring Security 在我的控制器可以在
HttpResponse
中添加标头之前拦截请求。如何在每个请求中传递令牌?

    @Bean
    public SecurityFilterChain config(HttpSecurity http) throws Exception {
        http
                 .csrf()
                .disable()
                .authorizeHttpRequests()
                .requestMatchers("/css/**","/scss/**","/vendor/**","/img/**","/js/**").permitAll()
                .requestMatchers("/auth","register").permitAll()
                .anyRequest().authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider())
                .formLogin(form -> form
                                .loginPage("/login")
                                .defaultSuccessUrl("/dashboard")
                                .permitAll()
                 )
                .logout()
                .logoutSuccessUrl("/logout")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .permitAll()
                .and()
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

我的控制器

POST
请求
/login

    @PostMapping("/login")
    public ModelAndView processLogin(HttpServletResponse res) {
        String jwttoken="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkZXkiLCJpYXQiOjE2ODMxNzkxODMsImV4cCI6MTY4MzI2NTU4M30.3-_7VrfDg91TUKvHh18JIclt-NTmcx9UnZnsNMoCKyA";
        res.setHeader(HttpHeaders.AUTHORIZATION, "Bearer "+ jwttoken);

        ModelAndView mv = new ModelAndView("login");
        return mv;
    }
spring spring-security jwt authorization spring-thymeleaf
© www.soinside.com 2019 - 2024. All rights reserved.