dev
dev

Reputation: 451

I am able to make authentication in Spring Security?

I am using Spring Security to authenticate users based on role. Authenticating for /** is giving:

Page load failed with error: too many HTTP redirects

error and login page is not shown.

  protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
            .antMatchers("/login*").authenticated()
            .antMatchers("/**").authenticated()
            .and()
            .formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/welcome")
            .usernameParameter("username").passwordParameter("password")
            .and()
            .logout().logoutSuccessUrl("/login?logout").logoutUrl("/login?logout")
            .and()
            .exceptionHandling().accessDeniedPage("/accessDenied")
            .and()
            .csrf();
        }

But if I do like this:

protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/login").authenticated()
        .antMatchers("/").authenticated()
        .and()
        .formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/welcome")
        .usernameParameter("username").passwordParameter("password")
        .and()
        .logout().logoutSuccessUrl("/login?logout").logoutUrl("/login?logout")
        .and()
        .exceptionHandling().accessDeniedPage("/accessDenied")
        .and()
        .csrf();
    }

What is wrong in this code to authenticate for /** URL?

Upvotes: 0

Views: 79

Answers (1)

dur
dur

Reputation: 17010

Your login page is not accessible for unauthenticated users:

.antMatchers("/login*").authenticated()

so Spring Security redirects to your login page, which redirects to your loging page, ...

You have to allow unauthenticated users to get your login page, see Spring Security Reference:

While the automatically generated log in page is convenient to get up and running quickly, most applications will want to provide their own log in page. To do so we can update our configuration as seen below:

protected void configure(HttpSecurity http) throws Exception {
  http
      .authorizeRequests()
          .anyRequest().authenticated()
          .and()
      .formLogin()
          .loginPage("/login") 1
          .permitAll();        2
}

1 The updated configuration specifies the location of the log in page.

2 We must grant all users (i.e. unauthenticated users) access to our log in page. The formLogin().permitAll() method allows granting access to all users for all URLs associated with form based log in.

If you remove the wildcards (*) all pages are accessible for unauthenticated users except login and /.

Upvotes: 1

Related Questions