成功登录后 Spring Boot Security 重定向 - 未定义

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

我已经遵循了spring boot安全教程,但最终结果有一个问题,成功登录后,浏览器重定向到

/undefined

我什至克隆了教程中引用的代码,认为我输入了错误的内容,或者忘记添加组件或其他内容。不,同样的问题也存在。

在 Stackoverflow 上搜索我发现你需要在

configure
WebSecurityConfigurerAdapter
方法中定义默认的成功 URL,如下所示:

.defaultSuccessUrl("/")

但还是不行。访问受保护的资源会进入登录页面,成功登录后我不会重定向到受保护的资源。我进入“/未定义”页面。然而,强迫成功是有效的:

.defaultSuccessUrl("/", true)

...但这不是我需要的,因为成功登录后,用户应该被重定向到(最初)请求的安全资源。


以下是该项目的相关部分:

网络安全配置:

package ro.rinea.andrei.Security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("password").roles("USER");
    }
}

控制器:

package ro.rinea.andrei.Controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WebController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/salut")
    public String salut() {
        return "salut";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}

index
login
salut
定义了视图(如果需要,我将添加它们的内容)

和 build.gradle 文件:

buildscript {
    ext {
        springBootVersion = '1.4.0.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'tstBut'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    compile('org.springframework.boot:spring-boot-devtools')
    compile('org.springframework.boot:spring-boot-starter-jdbc')
    compile('org.springframework.boot:spring-boot-starter-jersey')
    compile('org.springframework.boot:spring-boot-starter-mobile')
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.boot:spring-boot-starter-validation')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-web-services')
    compile('org.springframework.boot:spring-boot-starter-security')
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.springframework.restdocs:spring-restdocs-mockmvc')
}
java spring security spring-security spring-boot
3个回答
18
投票

您可以添加 successHandler 来进行重定向,如下所示:

private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
   ...
   .formLogin()
   .loginPage("/login")
   .successHandler(new AuthenticationSuccessHandler() {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        redirectStrategy.sendRedirect(request, response, "/");
    }
})

2
投票

我遇到了同样的问题,这是我使用的解决方法。 首先有一个不受保护的根“/”的映射

@RequestMapping(value = { "/" }, method = RequestMethod.GET)
public ModelAndView projectBase() {
    return new ModelAndView("redirect:/home");
}

将其重定向到您希望用户最初去的地方,例如家

@RequestMapping(value = { "/home" }, method = RequestMethod.GET)
public ModelAndView getHome() {
    ModelAndView model = new ModelAndView("account/home");
    model.addObject("user", userFacade.getJsonForUser(userFacade.getUserForClient()));
    return model;
}

确保根 URL 在您的安全配置中打开,例如...

 http.
    authorizeRequests()
    .antMatchers("/").permitAll()

现在会发生的事情是,它将到达根 /,并重定向到受限制的 home,并将它们发送到返回 url 为 home 的登录页面。当他们第一次登录时,它会正确写入 /home

由于某种原因,spring security 不尊重默认的成功 url,这可能是您的 Web 服务器的配置问题导致的。在我的本地计算机上我没有这个问题,但在其他一些计算机上却有。该解决方法在两个地方都有效,因为您总是会得到一个 returnUrl。


0
投票

2024方法

使用 defaultSuccessUrl 成功登录后重定向用户。您可以添加第二个参数(布尔值alwaysUse),但我不会推荐它,它总是会在成功登录后重定向用户。

.formLogin((form) -> form
    .loginPage("/login")
    .defaultSuccessUrl("/home")
    .permitAll())
.logout((logout) -> logout.permitAll());
© www.soinside.com 2019 - 2024. All rights reserved.