Vaadin 24/SpringBoot 3/Spring Security- REST API auth failure redirects to Vaadin login instead of returning 401-Unauthorized

b1uwtaje  于 2023-05-29  发布在  Spring
关注(0)|答案(1)|浏览(349)

有Vaadin 23/Sping Boot 2的工作配置。更新到Vaadin 24/Sping Boot 3后,失败的身份验证会导致重定向到Vaadin登录页面,而不是返回HTTP 401-Unauthorized。失败的API授权似乎会流向Vaadin Security,而不是以401-Unauthorized终止。我希望所有/API请求都由Rest API Config处理,其他所有请求都由Vaadin处理。我的基本Spring安全配置:

//Config for the REST API
    @Configuration
    @Order(1)
    public static class MyRestApiSecurityConfig  {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and().csrf().disable()
                .securityMatcher("/api/**")
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            http.authorizeHttpRequests(auth -> auth
                            .anyRequest()
                            .hasAuthority(AppRoles.API))
                    .httpBasic()
                    .authenticationEntryPoint(new RestAuthenticationEntryPoint());
        }
    }
    //Config for Vaadin
    @Configuration
    @Order(2)
    public static class MyUIWebSecurity extends VaadinWebSecurity {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
            setLoginView(http, LoginView.class);
        }
    }

    public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}
qacovj5a

qacovj5a1#

而令人印象深刻的解决方案是将RestAuthenticationEntryPoint从:

response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized")

response.setStatus(response.SC_UNAUTHORIZED);

现在,REST API的auth失败返回401,而不是重定向到Vaadin登录。值得注意的是,之前response.sendError的方法在Vaadin 23/Sping Boot 2中工作正常

相关问题