Spring Security 强制显示登录屏幕,即使已经指定了“permit all”。

huangapple go评论64阅读模式
英文:

Spring Security forces log in screen even with permit all specification

问题

我有一个基本的Spring Security过滤器链,使用表单登录。每当我尝试绕过登录界面时,它都会重定向回登录界面。

具体来说,尝试访问"public"仍然会重定向回登录页面。

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity sec) throws Exception {
    sec.csrf().disable()
        .authorizeHttpRequests()
        .requestMatchers("home/normal")
        .hasRole("NORMAL")
        .requestMatchers("home/admin")
        .hasRole("ADMIN")
        .requestMatchers("/home/public", "/home/add")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .formLogin();
    return sec.build();
}
英文:

I have a basic spring security filter chain with form login. And whenever I try to bypass the login screen it just redirects back to it.

Specifically, trying to access public still redirects back to the login page.

    @Bean
    public SecurityFilterChain securityFilterChain (HttpSecurity sec) throws Exception
    {
        sec.csrf().disable()
                .authorizeHttpRequests()
                .requestMatchers("home/normal")
                .hasRole("NORMAL")
                .requestMatchers("home/admin")
                .hasRole("ADMIN")
                .requestMatchers("/home/public", "/home/add")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin();
        return sec.build();
    }

答案1

得分: 0

我相信这可能发生的原因不是因为在请求服务器页面时的 /home/public/home/add,而是因为浏览器也会请求站点图标,因此它们会向服务器发出 /favicon.ico 请求,请确保也允许这个请求。

因此,请按照以下方式更新你的代码:

...
.requestMatchers("/home/public", "/home/add", "/favicon.ico")
.permitAll()

你可以在浏览器中打开开发工具并检查网络选项卡,看看是否有任何对服务器的XHR请求需要被允许。

英文:

I believe this could happen not because of the /home/public nor /home/add when you request a page from the server, browsers will request the favicon as well so they issue /favicon.ico request against the server so make sure to allow it as well

So update your code as follows:

...
.requestMatchers("/home/public", "/home/add", "/favicon.ico")
.permitAll()

You can open the dev tools in the browser and check the network tab if there are any XHR requests against a server that needed to be allowed also.

huangapple
  • 本文由 发表于 2023年6月2日 05:12:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定