当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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?

网友答案:

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 /.

分享给朋友:
您可能感兴趣的文章:
随机阅读: