简体   繁体   中英

Implement Spring Security Login via a POST /login API

I'm creating an app/web-page having its own login/register view/page.

My back-end service is in Java and using Spring Security to manage user's authentication.

Basic Goal is (from an app):-

  1. Register a user via a /register API. (Register page already on client-side)
  2. Display a login page (already on client-side).
  3. Hit /login api to authenticate user with provided username and password. (provided in JSON POST request)
  4. On success, return a cookie to be used for next actions/api calls to authenticate logged-in user.

Both Login & Register APIs are to enable as public.

Here's my spring security config

//all imports

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private PasswordEncoder passwordEncoder;


    @Autowired
    public SecurityConfig(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login", "/register").permitAll() //to allow these urls
                .anyRequest().authenticated().and()
                 // dont want Spring's Login page to get rendered
                .formLogin().loginProcessingUrl("/login").and().rememberMe(); 
    }


    @Override
    @Bean
    protected UserDetailsService userDetailsService() {
        //for HTTP Basic Auth - but needs to be removed to implement Cookie based authentications
        UserDetails userDetails = User.builder().
                username("admin").
                password(passwordEncoder.encode("admin")).
                roles("ADMIN").
                build();

        return new InMemoryUserDetailsManager(userDetails);

    }
}

My concern is that loginProcessingUrl() doesn't redirect my URL https://<domain>/login request to its mapped controller method which internally gets users from DB & validates. Also https://<domain>/register POST api doesn't work, it ask for login every time.

Went through all Spring DOCs & tutorials but no one seemed to answer such cases.

How this can be achieved?

loginProcessingUrl("/path") is the path that tells Spring security to process credentials. Note that this will not pass request to your Controller method.

What you should do to show your own login page instead of the default one is use loginPage("/login") . This is the GET request which returns an HTML page.

You may be interested in AuthenticationSuccessHandler.

Refer this example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM