spring security with spring boot cant redirect after login

与世无争的帅哥 提交于 2021-01-28 07:22:59

问题


I encountered a problem when integrating spring security with spring boot.After Overwriting the WebSecurityConfigurerAdapter, I can't redirect to the successful page(wlecome.ftl) when I've accessed the login page.It's aways redirect to the login page(index.ftl) without error logs.

Is there anyting I missed?Help is aways appreciated,thanks!

SecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserDetailsService detailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/user/welcome")//add this but not work
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/**/favicon.ico");
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");
    }

Login.Controller

@Controller
public class LoginController {

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

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

index.ftl(the login page)

<!DOCTYPE html>
<#import "/spring.ftl" as spring />
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="<@spring.url '/login' />" method="post">
    username:<input type="text" name="username"><br>
    password:<input type="password" name="password"><br>
    <input type="submit" value="login">
</form>

</body>
</html>

welcome.ftl

<html>
  <head>

  </head>
<body>
  welcome
</body>
</html>

回答1:


You didn't set the successful login url and you anywhere redirect after login success. Put the:

defaultSuccessUrl("/user/welcome")

after the:

passwordParameter("...")

in your security configuration.




回答2:


try this

.defaultSuccessUrl("/user/welcome",true)


来源:https://stackoverflow.com/questions/50342040/spring-security-with-spring-boot-cant-redirect-after-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!