简体   繁体   English

成功登录后的Spring Boot安全重定向 - 未定义

[英]Spring Boot Security redirect after successful login - undefined

I have followed the spring boot security tutorial but 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 configure method of the WebSecurityConfigurerAdapter like so: 在Stackoverflow上搜索我发现你需要在WebSecurityConfigurerAdapterconfigure方法中定义默认的成功URL, WebSecurityConfigurerAdapter所示:

.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. 我进入'/ undefined'页面。 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: 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 , login and salut (if needed I will add their contents) 有为indexloginsalut定义的视图(如果需要,我将添加其内容)

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

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

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... 确保您的安全配置中的根网址已打开,例如...

 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. 现在会发生什么事情,它将触及root /,并重定向到受限制的主页,并将其发送到登录页面,并返回主页的返回URL。 it will then write correctly as /home when they first login 然后它会在首次登录时正确地写为/ 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. 出于某种原因,Spring安全性不尊重默认的成功URL,并且它可能是导致它的Web服务器的配置问题。 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. 解决方法适用于这两个地方,因为您总是以returnUrl结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM