美文网首页Spring Cloud
七、API安全机制-业务层安全策略

七、API安全机制-业务层安全策略

作者: 紫荆秋雪_文 | 来源:发表于2020-05-12 21:50 被阅读0次

源码下载

一、API安全机制-业务逻辑API API安全机制.png

  • 业务逻辑验证
@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IRavenUserService userService;

    @PostMapping("/save")
    public RavenUserInfo create(@RequestBody @Validated RavenUserInfo userInfo) {
        RavenUserInfo user = this.userService.create(userInfo);
        return user;
    }
}
  • RavenUserInfo
/**
 * 是RavenUser 对外的封装
 * 负责外界服务
 */
@Data
public class RavenUserInfo {
    private Long id;
    private String name;
    @NotBlank
    private String username;
    @NotBlank
    private String password;
}
  • 在RavenUserInfo类中指定了username和password不能为空,在请求中RavenUserInfo参数前指定@Validated,表示RavenUserInfo类中的@NotBlank注解生效
  • JSON中username字段为空
{
    "name":"zl",
    "username":"",
    "password":"123456"
}
  • 结果
{
    "timestamp": "2020-05-12T13:29:11.982+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "NotBlank.ravenUserInfo.username",
                "NotBlank.username",
                "NotBlank.java.lang.String",
                "NotBlank"
            ],
            "arguments": [
                {
                    "codes": [
                        "ravenUserInfo.username",
                        "username"
                    ],
                    "arguments": null,
                    "defaultMessage": "username",
                    "code": "username"
                }
            ],
            "defaultMessage": "不能为空",
            "objectName": "ravenUserInfo",
            "field": "username",
            "rejectedValue": "",
            "bindingFailure": false,
            "code": "NotBlank"
        }
    ],
    "message": "Validation failed for object='ravenUserInfo'. Error count: 1",
    "path": "/users/save"
}

相关文章

网友评论

    本文标题:七、API安全机制-业务层安全策略

    本文链接:https://www.haomeiwen.com/subject/jeninhtx.html