如何使用自定义的Spring Boot登录表单调用控制器发布方法

时间:2019-04-24 12:06:03

标签: spring-security

我是Spring Security的新手。我有简单的mvc应用程序,当我想调用控制器的post方法(请求映射值与loginProcessingUrl的值相同)时会出现问题。

控制器类:

@Controller
public class LoginController {

    @RequestMapping(value = "/showlogin", method = RequestMethod.GET)
    public String showLogin() {
        System.out.println("Showing login...");
        return "login";
    }

    // this method is not being invoked
    @RequestMapping(value = "/authuser", method = RequestMethod.POST)
    public void printUserData() {
        System.out.println("Printing user data...");
    }
}

配置类:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        User.UserBuilder users = User.withDefaultPasswordEncoder();

        auth.inMemoryAuthentication()
              .withUser(users.username("dejan").password("dejan").roles("EMPLOYEE"))
                .withUser(users.username("marko").password("marko").roles("ADMINISTRATOR"));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/showlogin")
                .loginProcessingUrl("/authuser")
                .permitAll()
                .and()
                .csrf().disable();
    }
}

自定义登录页面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form th:action="@{/authuser}" method="post">
        Username: <input type="text" name="username" />
        Password: <input type="password" name="password" />
        <input type="submit" value="Login" />
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

我猜你的问题在这里:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .anyRequest().authenticated()
            ...

}

将此更改为:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .and()
            .formLogin()
            .loginPage("/showlogin")
            .loginProcessingUrl("/authuser")
            .permitAll()
            .and()
            .anyRequest().authenticated()
            .csrf().disable();
}

答案 1 :(得分:0)

continueChainBeforeSuccessfulAuthentication中有一个名为AbstractAuthenticationProcessingFilter的属性可以做到这一点。但似乎它并未公开任何配置,

因此,您需要自己创建UsernamePasswordAuthenticationFilter而不是formLogin,并将continueChainBeforeSuccessfulAuthentication设置为true

相关问题