![](/img/trans.png)
[英]Android HttpURLConnection always unauthorized 401 response (Spring Boot REST API)
[英]Spring Boot REST force response type / 401 custom page not working?
我正在使用 Spring Boot 2.2.0.RELEASE 来构建我的 REST api。
我已经设法使用 thymeleaf 自定义 500/400/404 错误页面(如果有人使用浏览器导航)并将文件放入:
src/main/resources/templates/error.html
src/main/resources/templates/errors/400.html
src/main/resources/templates/errors/404.html
这一切都很好。
但是我注意到,当有人在浏览器中导航到说 /myrestapi 时,他们会收到 401 错误。 默认情况下,在 Spring 中,它们会收到 403 错误,但我已覆盖该行为以使其全部为 401:
@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;
}
所以我补充说:
src/main/resources/templates/errors/401.html
这似乎没有被接受,当我 go 到浏览器时,它显示 XML:
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
当我通过 Fiddler go 到那个 URL 时,它给了我 Json,但我希望人们得到我的自定义 401 页面。 我找到了一些我需要这样做的文档:
WebSecurityConfig.java:
http.exceptionHandling().accessDeniedPage("/resources/templates/errors/401.html")
.authenticationEntryPoint(authenticationEntryPoint());
我的 ResourceServerConfig.java 看起来像这样:
@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();
}
但这也行不通。
我错过了什么吗?
注意:我通过 permitAll() 让所有请求通过,然后使用 @PreAuthorize 在方法级别控制 OAuth 访问。 但我也尝试删除 permitAll() 并且它仍然没有命中。
还尝试了 accessDeniedHandler ,但这也不起作用。
看起来你的路径是错误的。 它应该是 /resources/templates/errors/401.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.