@Override
protected void configure(HttpSecurity httpSecurity) throws Exception
{
// @formatter:off
httpSecurity
.csrf()
.disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET).permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint());
// @formatter:on
}
private static AuthenticationEntryPoint authenticationEntryPoint()
{
return (request, response, authException) -> {
response.addHeader("WWW-Authenticate", "Basic realm=\"Realm\"");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpStatus.UNAUTHORIZED.value());
String message = authException.getMessage();
if (request.getHeaders("Authorization").hasMoreElements()) {
message += ". Wrong Authorization Key.";
} else {
message += ". Missing Authorization Key im Header.";
}
response.getWriter().format("""
{
"errors":[
{
"status": %d,
"title": "%s",
"detail": "%s"
}
]
}
""",
HttpStatus.UNAUTHORIZED.value(),
HttpStatus.UNAUTHORIZED.name(),
message
);
};
}
为什么我发送带有错误凭据的帖子请求,我得到:
{
"errors": [
{
"status": 401,
"title": "UNAUTHORIZED",
"detail": "Full authentication is required to access this resource. Wrong Authorization Key."
}
]
}
对于 get 方法,我没有收到格式错误:
{
"timestamp": "2023-04-18T17:07:35.663+00:00",
"status": 401,
"error": "Unauthorized",
"path": "/xxx/1111"
}
我也得到了像帖子一样的漂亮回复
spring security 中有一个已知的错误/功能,如果请求在 permitAll() 被命中之前很久就具有授权标头,则该请求将被“验证”。我相信这就是我们所观察到的。除非凭据有效,否则不要传递凭据。