简体   繁体   English

Spring boot 2.x 中的身份验证处理与 WebSecurityConfigurerAdapter

[英]Authentication handling in Spring boot 2.x with WebSecurityConfigurerAdapter

I am using spring boot 2.0.5 with below dependency for spring security of 5.0.8我正在使用 spring 启动 2.0.5 对 spring 安全性为 5.0.8

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
 </dependency>

I throwing a exception from the rest controller as below for test purpose.为了测试目的,我从 rest controller 抛出异常,如下所示。

@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        throw new org.springframework.security.authentication.BadCredentialsException("yoyo");
}

This is how the config class looks like,这就是配置 class 的样子,

    @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();
        }
    }

I have added /error since spring boot documentation it says,自从 spring 启动文档说,我添加了 /error,

Spring Boot 2.0 doesn't deviate too much from Spring Security's defaults, as a result of which some of the endpoints that bypassed Spring Security in Spring Boot 1.5 are now secure by default. Spring Boot 2.0 doesn't deviate too much from Spring Security's defaults, as a result of which some of the endpoints that bypassed Spring Security in Spring Boot 1.5 are now secure by default. These include the error endpoint and paths to static resources such as /css/ , /js/ , /images/ , /webjars/ , /**/favicon.ico.其中包括错误端点和 static 资源的路径,例如 /css/ 、 /js/ 、 /images/ 、 /webjars/ 、 /**/favicon.ico 。 If you want to open these up, you need to explicitly configure that.如果你想打开这些,你需要明确地配置它。

Add below in spring boot application class as well在 spring 引导应用程序 class 中添加以下内容

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })

When i hit the rest end point I get,当我到达 rest 端点时,我得到了,

{
    "timestamp": "2021-01-17T03:52:50.069+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/greeting"
}

But I expect status 401 with "message": "yoyo" like below,但我希望状态 401 带有 "message": "yoyo" 如下所示,

{
    "timestamp": 2021-01-17T03:52:50.069+0000,
    "status": 401,
    "error": "Unauthorized",
    "message": "yoyo",
    "path": "/greeting"
}

What changes I need to do for get that response我需要做哪些改变才能获得响应

Add http.exceptionHandling().authenticationEntryPoint(..) to get Unauthorized instead of Forbidden for error field.添加http.exceptionHandling().authenticationEntryPoint(..)以获得Unauthorized而不是Forbidden error字段。

@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();

        http.exceptionHandling().authenticationEntryPoint((request, response, ex) -> {
            // You can add more logic to return different error codes
            response.sendError(401, "Unauthorized");
        });
    }
}

Define a new class that returns ex.getMessage() instead of Access Denied for message field.定义一个新的 class 返回ex.getMessage()而不是Access Denied for message字段。

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
    @Override
    protected String getMessage(WebRequest webRequest, Throwable error) {
        return error.getMessage();
    }
}

Output: Output:

{
    "timestamp": "2021-01-20T15:06:33.122+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "yoyo",
    "path": "/greeting"
}

I guess you don't see the exception you have thrown because the "greeting" endpoint is secured and spring security handle it itself.我猜你看不到你抛出的异常,因为“问候”端点是安全的,并且 spring 安全处理它自己。

Set "/greeting" not secured so you can access it and get the custom error将“/greeting”设置为不安全,以便您可以访问它并获取自定义错误

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.csrf().disable().authorizeRequests().antMatchers("/**").permitAll();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM