gpt4 book ai didi

java - 我可以在 Spring Security 中进行身份验证吗?

转载 作者:行者123 更新时间:2023-12-01 09:29:17 25 4
gpt4 key购买 nike

我正在使用 Spring Security 根据角色对用户进行身份验证。对 /** 进行身份验证会给出:

Page load failed with error: too many HTTP redirects

错误且未显示登录页面。

  protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login*").authenticated()
.antMatchers("/**").authenticated()
.and()
.formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/welcome")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout").logoutUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/accessDenied")
.and()
.csrf();
}

但如果我这样做:

protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").authenticated()
.antMatchers("/").authenticated()
.and()
.formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/welcome")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout").logoutUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/accessDenied")
.and()
.csrf();
}

此代码对 /** URL 进行身份验证有什么问题?

最佳答案

未经身份验证的用户无法访问您的登录页面:

.antMatchers("/login*").authenticated()

因此 Spring Security 重定向到您的登录页面,该页面又重定向到您的日志页面,...

您必须允许未经身份验证的用户访问您的登录页面,请参阅Spring Security Reference :

While the automatically generated log in page is convenient to get up and running quickly, most applications will want to provide their own log in page. To do so we can update our configuration as seen below:

protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login") 1
.permitAll(); 2
}

1 The updated configuration specifies the location of the log in page.

2 We must grant all users (i.e. unauthenticated users) access to our log in page. The formLogin().permitAll() method allows granting access to all users for all URLs associated with form based log in.

如果删除通配符 (*),则未经身份验证的用户都可以访问除 login/ 之外的所有页面。

关于java - 我可以在 Spring Security 中进行身份验证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39579881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com