Custom AuthenticationEntryPoint

A custom AuthenticationEntryPoint can be used to set necessary response headers, content-type, and so on before sending the response back to the client.

The org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint class is a built-in AuthenticationEntryPoint implementation, which will get invoked for basic authentication to commence. A custom entry point can be created by implementing the org.springframework.security.web.AuthenticationEntryPoint interface. The following is an example implementation:

@Component
public final class CustomAuthenticationEntryPoint implements
AuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request, final
HttpServletResponse response, final AuthenticationException
authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}

When a client accesses resources without authentication, this entry point kicks in and throws a 401 status code (Unauthorized).

In the Spring Security Java configuration file, make sure that the configure method has this custom AuthenticationEntryPoint defined, as shown in the following code snippet:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(customAuthenticationEntryPoint);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.172.82