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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38962099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:57:47  来源:igfitidea点击:

Spring Boot Security redirect after successful login - undefined

javaspringsecurityspring-securityspring-boot

提问by Andrei R?nea

I have followed the spring boot security tutorialbut the end result has an issue consisting in that after successful login the browser is redirect to /undefined.

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

I have even cloned the code referenced in the tutorial, thinking I have typed something wrong, or forgot to add a component or something. No, the same issue is there.

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

Searching on Stackoverflow I found out that you need to define the default success URL in the configuremethod of the WebSecurityConfigurerAdapterlike so:

在 Stackoverflow 上搜索我发现你需要configureWebSecurityConfigurerAdapter像这样的方法中定义默认的成功 URL :

.defaultSuccessUrl("/")

but still no go. Accessing a protected resource leads to the login page and upon successful login I don't get redirected to the protected resource. I get to the '/undefined' page. Forcing the success works, however:

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

.defaultSuccessUrl("/", true)

... but this is not what I would need because after successful login the user should be redirected to secured resource (initially) requested.

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



Here's the relevant parts of the project:

这是项目的相关部分:

WebSecurityConfig:

网络安全配置:

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");
    }
}

Controller:

控制器:

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";
    }
}

There are views defined for index, loginand salut(if needed I will add their contents)

有用于定义视图indexlogin以及salut(如果需要的话,我会添加自己的内容)

and the build.gradle file:

和 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')
}

回答by Peter Lustig

You can add a successHandler to redirect like this:

您可以添加一个 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, "/");
    }
})

回答by sean

I had the same issue and this is a workaround that I used. First have a mapping for your root "/" that is unprotected

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

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

Have it redirect to where you want the user to go initially like home for example

例如,让它重定向到您希望用户最初像家一样去的地方

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

Make sure the root url is open in your security configuration like...

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

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

What will happen is now it will hit the root /, and redirect to home which is restricted and send them to the loginpage with a return url of home. it will then write correctly as /home when they first login

现在会发生什么,它会命中根 /,然后重定向到受限制的 home,然后将它们发送到带有 home 返回 url 的登录页面。当他们第一次登录时,它会正确地写为 /home

For some reason spring security is not respecting the default success url, and it could be a configuration issue with your web server causing it. On my local machine I don't have this issue, but on some other machines I do. The workaround works in both places, since you always end up with a returnUrl.

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