I'm using Spring Boot 2.2.0.RELEASE to build my REST api.
I've managed to customize the 500/400/404 error pages (if somebody navigates with a browser) with thymeleaf and putting the files in:
src/main/resources/templates/error.html
src/main/resources/templates/errors/400.html
src/main/resources/templates/errors/404.html
All this works fine.
I noticed however, when somebody navigates to say /myrestapi in a browser, they get a 401 error. By default in Spring they would get a 403 error, but I have overridden that behavior to make it all 401s:
@Override
protected void configure(HttpSecurity http) throws Exception {
// return HTTP 401 instead of HTTP 403 for unauthorized requests
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint());
}
private AuthenticationEntryPoint authenticationEntryPoint() {
BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
basicAuthenticationEntryPoint.setRealmName("Bearer realm=\"oauth2-resource\"");
return basicAuthenticationEntryPoint;
}
So I added:
src/main/resources/templates/errors/401.html
This doesn't seem to be getting picked up and when I go to the browser, it shows XML:
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
When I go to that URL through Fiddler, it gives me Json, but I want the human to get my custom 401 page. I found some documentation that I need to do this:
WebSecurityConfig.java:
http.exceptionHandling().accessDeniedPage("/resources/templates/errors/401.html")
.authenticationEntryPoint(authenticationEntryPoint());
My ResourceServerConfig.java looks like this:
@Override
public void configure(HttpSecurity http) throws Exception {
// default behavior is to allow anonymous access unless @PreAuthorize is specified
http.exceptionHandling().accessDeniedPage("/resources/templates/errors/401.html").and().authorizeRequests().anyRequest()
.permitAll();
}
But that doesn't work either.
Am I missing something?
NOTE: I am letting all requests through with permitAll() and then control OAuth access at the METHOD LEVEL using @PreAuthorize. But I also tried removing the permitAll() and its still not hitting.
Also tried the accessDeniedHandler and that doesn't work either.
Looks like your path is wrong. It should be /resources/templates/errors/401.html