【发布时间】:2021-04-21 17:43:51
【问题描述】:
我正在使用 Spring Boot 2.0.5 并具有以下依赖项,以实现 5.0.8 的 Spring Security
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
出于测试目的,我从其余控制器中抛出了一个异常,如下所示。
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
throw new org.springframework.security.authentication.BadCredentialsException("yoyo");
}
这是配置类的样子,
@Configuration
@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/error");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/error").permitAll();
}
}
自从 Spring Boot 文档说以来,我已经添加了 /error,
Spring Boot 2.0 与 Spring Security 的差别不大 默认值,因此绕过了一些端点 Spring Boot 1.5 中的 Spring Security 现在默认是安全的。这些 包括错误端点和静态资源的路径,例如 /css/、/js/、/images/、/webjars/、/**/favicon.ico。如果你想 要打开这些,您需要明确配置。
在 Spring Boot 应用程序类中添加以下内容
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
当我达到我得到的休息终点时,
{
"timestamp": "2021-01-17T03:52:50.069+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/greeting"
}
但我希望状态 401 带有 "message": "yoyo" 如下所示,
{
"timestamp": 2021-01-17T03:52:50.069+0000,
"status": 401,
"error": "Unauthorized",
"message": "yoyo",
"path": "/greeting"
}
我需要做哪些改变才能获得响应
【问题讨论】:
-
您介意分享您的 ExceptionHandler 和 BadCredentialsException 类吗?
-
我不使用任何异常处理程序。
-
激活 spring 安全包的
DEBUG级别,看看发生了什么。此外,您的配置并不详尽。在访问/greeting端点之前,您没有指定希望用户通过身份验证的任何位置。 -
为什么排除了 SecurityAutoConfiguration 类?您是否尝试禁用弹簧安全性以达到端点?
标签: java spring spring-boot rest spring-security