Custom login REST endpoint

Viewed 167

I am trying to change default POST /login spring security endpoint for logging in to POST /api/users/login

I already tried doing that through

formLogin().loginProcessingUrl("/api/users/login")

or

formLogin().loginPage("/api/users/login")

but it didn't work. How do i do that? I can't find tutorial describing it or stack overflow answer. I also tried reading Spring Security documentation but it didn't help too.

My security config looks like this:

    private final MyUserDetailsService myUserDetailsService;

    private final PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //go from most restrictive url to least restrictive, from single urls to /**
        httpSecurity.csrf().disable().cors().and()
                .addFilter(new JwtAuthenticationFilter(authenticationManager()))
                .addFilter(new JwtAuthorizationFilter(authenticationManager()))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        //to allow h2 console page
        httpSecurity.headers().frameOptions().disable();
    }
1 Answers

In the WebSecurityConfigurerAdapter class there is to configure methods that you should override like so:

@Override
protected void configure(HttpSecurity http) throws Exception { 
   http.csrf().disable()
        .exceptionHandling()
        .authenticationEntryPoint(
                               unAuthorizedResponseAuthenticationEntryPoint)
       .and().sessionManagement()           
       .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
       .and()
       .authorizeRequests()
       .anyRequest()
       .authenticated();
    http.addFilterBefore(authenticationTokenFilter,
                          UsernamePasswordAuthenticationFilter.class);


}

@Override
public void configure(WebSecurity webSecurity) throws Exception {
    webSecurity
            .ignoring().antMatchers(HttpMethod.POST, "/api/auth/login")
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .and().ignoring()
            .antMatchers(HttpMethod.GET, "/").and().ignoring();
}

}

Please see in method:

public void configure(WebSecurity webSecurity) throws Exception

the line:

webSecurity.ignoring().antMatchers(HttpMethod.POST, "/api/auth/login")

This is where you put your custom authentication API endpoint!

And then you may proceed as I explained in the following question How to use custom UserDetailService in Spring OAuth2 Resource Server?

Related