why spring security makes spring mvc 's postma

2019-09-19 15:53发布

when I config spring security like this

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Bean
    public UserDetailsService userDetailsService(){
        return new MyUserDetailsService();
    }

    @Bean
    public MyAuthenticationProvider myAuthenticationProvider(){
        MyAuthenticationProvider provider = new MyAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService());
        return provider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub

        http
            .csrf()
                .disable()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll();
    }
}

and then I config my controller like this

    @GetMapping("/login")
    public String showLoginPage(){
        System.out.println("GetMapping");
        return "login";
    }

    @PostMapping("/login")
    public void authUser(@RequestParam String username,@RequestParam String password){
//      just for testing
        System.out.println("PostMapping");
    }

and then I visit my login page and enter my username and password, but the console doesn't print "PostMapping", which means the program doesn't go into my method "authUser" with @PostMapping.

Though my program runs successfully, but it makes me quite confuse.I suppose spring security doing some work automatically, but now I have no idea where to add my Authentications to the SecurityContextHolder.

I hope somebody can help and thanks very much

1条回答
Rolldiameter
2楼-- · 2019-09-19 16:29

It has done by UsernamePasswordAuthenticationFilter, and the default processing path is Post /login, and the Authentication already exist in SecurityContextHolder, you can get it in controller.

If you want to disable form login, change to this.

http
    .csrf()
    .disable()
    .authorizeRequests()
        .antMatchers("/login").permitAll()
        .anyRequest().authenticated().and()
    .formLogin().disable();
查看更多
登录 后发表回答