有一个更容易的选择.只需将Http401AuthenticationEntryPoint添加到您的httpSecurity即可.
http.exceptionHandling() .authenticationEntryPoint(new Http401AuthenticationEntryPoint("FormBased"));