Disable browser authentication dialog in spring security
I am using spring security 4, for some reason after completing authentication on my login page I get browser authentication dialog which forces me to authenticate again.
this is my security config:
http.antMatcher("/test")
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/index.html", "/login.html", "/", "/scripts/**",
"/bower_components/**", "/styles/**", "/views/**",
"/login", "/api/user/*").permitAll().anyRequest()
.authenticated().and().logout().logoutUrl("/api/logout").and()
.csrf().csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
source to share
What causes the authentication popup is the response header WWW-Authenticate: Basic
, which is set by the BasicAuthenticationEntryPoint .
Use a custom AuthenticationEntryPoint
one that doesn't install WWW-Authenticate: Basic
:
public class NoPopupBasicAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}
}
Add a custom authentication entry point to your security configuration:
http
.httpBasic()
.authenticationEntryPoint(new NoPopupBasicAuthenticationEntryPoint())
source to share
Use formLogin () instead of httpBasic (). Refactoring your config:
http
.antMatcher("/test")
.authorizeRequests()
.antMatchers("/index.html", "/login.html", "/", "/scripts/**",
"/bower_components/**", "/styles/**", "/views/**",
"/login", "/api/user/*").permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/your_login_page_here").permitAll()
.and().logout().logoutUrl("/api/logout").and()
.csrf().csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
In case /login.html is your login page, you would like to remove it from one of the allowed locations of allowAll ().
source to share