2016-08-15 7 views
1

Я следил за spring boot security tutorial, но в результате у конечного результата возникла проблема, состоящая в том, что после успешного входа в систему браузер перенаправляет на /undefined.Spring Boot Security перенаправляется после успешного входа в систему - undefined

Я даже клонировал код, упомянутый в учебнике, думая, что я набрал что-то неправильно или забыл добавить компонент или что-то в этом роде. Нет, та же проблема есть.

Поиск по Stackoverflow я узнал, что вам нужно определить URL успеха по умолчанию в configure способе WebSecurityConfigurerAdapter так:

.defaultSuccessUrl("/") 

, но до сих пор не идут. Доступ к защищенному ресурсу приводит к странице входа в систему и при успешном входе в систему я не перенаправляюсь на защищенный ресурс. Я перехожу на страницу «/ undefined». Принуждение успех работы, однако:

.defaultSuccessUrl("/", true) 

... но это не то, что мне нужно, потому что после успешного входа в систему пользователь должен быть перенаправлен на обеспеченного ресурса (первоначально) просил.


Вот соответствующие части проекта:

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

Контроллер:

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

ответ

3

Вы можете добавить 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, "/") 
    } 
}) 
1

I была та же проблема, и это обходной путь, который я использовал. Во-первых есть отображение вашего корня «/», который является незащищенным

@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() 

Что будет теперь это ударит корень /, и перенаправить к дому, который ограничен и отправить их на loginpage с возвращаемым адресом дома. он будет правильно писать как/home при первом входе в систему

По какой-то причине весенняя безопасность не соответствует URL-адресу успеха по умолчанию, и это может быть проблема с конфигурацией, вызвавшая ее веб-сервер.На моей локальной машине у меня нет этой проблемы, но на некоторых других машинах я это делаю. Обходной путь работает в обоих местах, так как вы всегда получаете returnUrl.

Смежные вопросы