为什么Spring Security FilterChain处理@Controller和@RestController请求的方式不同

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

我有一个带有以下过滤器链的 Spring OAuth2-Client:

SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests(authorize -> {
                    authorize.requestMatchers("/", "/home").permitAll();
                    authorize.anyRequest().authenticated();
                })
                .formLogin(withDefaults())
                .oauth2Login(withDefaults())
                .build();
    }

我有一个具有以下 2 个端点的控制器:

@GetMapping("home")
public String home(){
    return "home.html"
}


@GetMapping("securedHome")
public String securedHome(){
    return "securedHome.html";
}

如果我对此使用 @RestController 注释,Spring 安全性将按预期工作。我能够访问 /home,它会返回一个值为“home.html”的字符串,如果我转到 /securedHome,它会将我重定向到登录页面,登录后我可以看到该页面。

但是,如果我使用@Controller注释,当我尝试访问/home时,Spring Security会将我重定向到登录页面,即使在我的filterChain中我对此请求有permitAll()。

我试图理解为什么会这样,但我迷失了。我尝试查看文档并寻找答案,但找不到。

如果有人可以帮助我在 Spring Security 的迷宫中导航,我将非常感激。

java spring spring-boot spring-security spring-security-oauth2
1个回答
0
投票

如果使用

@RestController
,则无法返回视图(通过在Spring/springboot中使用Viewresolver),并且是的,在这种情况下不需要
@ResponseBody
。这就是为什么当您点击 /home 时它会返回一个字符串。

如果您使用

@Controller
,您可以在 Spring Web MVC 中返回视图。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.