繁体   English   中英

使用 Spring Boot 对 REST 服务进行基本身份验证

[英]Basic Authentication on REST service with Spring Boot

使用 Spring boot(最新版本)开发了一个简单的 REST 端点。 用过的:

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

并在 applicaion.properties 文件中更改了用户名和密码。

spring.security.user.name=user
spring.security.user.password=password

就这些。 能够与返回简单“hello”字符串的 GET 端点通信。我收到了预期的结果。

 @GetMapping (value = "/all")
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    ResponseEntity<String> all() {
    return  ResponseEntity.ok("customer") ;
    }

我使用 POSTMAN 拨打电话,在设置中添加了(基本身份验证,并根据我的应用程序设置添加了用户名和密码。这是邮递员的示例:


curl --location --request GET 'http://localhost:8080/all' \
--header 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \
--header 'Cookie: JSESSIONID=F6311C2062385978CE173C4A11E0D74D'

回复:好的,200。

现在我正在调用一个 post 方法:

    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    ResponseEntity<Customer> addCustomer(@Valid @RequestBody CustomerDTO customerDTO) {
        Customer customer = mapper.toCustomer(customerDTO);
        customerRepository.save(customer);
        return ResponseEntity.ok(customer);
    }

所以调用post方法失败,附上postman的调用:

curl --location --request POST 'http://localhost:8080/addAccount' \
--header 'If-None-Match: "version1"' \
--header 'Content-Type: application/json' \
--header 'Cookie: JSESSIONID=9AE7806055797DF85021C70951AD826B' \
--data-raw '{
    "accountNumber":1,
    "customer":
     {
    "id": 1,
    "forename": "mynam",
    "surname": "surname",
    "dateOfBirth": "2011-11-11T00:00:00.000+00:00",
    "accounts": null
}
}'

收到 401 错误。

如果我删除 Basic Authentication 并简单调用 POST 方法,一切正常。 我做错了什么? 我应该从哪里开始挖掘?

--

问题是,当您使用 spring spring-boot-starter-security 时,它默认启用 crsf 保护。 要临时解决问题,您可以使用此配置。 请注意,已为 POST 启用 csrf。

如果您想了解有关 csrf 的更多信息,可以查看https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html

public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity request) throws Exception{
         request.csrf().disable();
                 return request.build();
    }
}

暂无
暂无

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

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