【问题标题】:Adding basic auth headers to all the requests in spring boot将基本身份验证标头添加到 Spring Boot 中的所有请求
【发布时间】:2021-11-19 19:33:02
【问题描述】:

我是 Spring Boot 应用程序开发的新手。 我需要将基本身份验证标头添加到 Spring Boot 中的所有 api 请求中。 任何人都可以分享我如何进行的有效文件

【问题讨论】:

    标签: spring-boot spring-security


    【解决方案1】:

    这取决于你需要什么样的身份验证 对于自我身份验证令牌之类的东西,它看起来像

    public String controllerFunction(@RequestHeader("Auth-header") String authToken){
    
        if (authToken == null) {
            log.error("Self token authentication failed");
            throw new Exception(TOKEN_NOT_FOUND);
        }
    
        if (!"auth_password".equals(authToken)) {
            log.error("Self token authentication failed");
            throw new Exception(AUTH_FAILED);
        }
        log.info("Self token authentication successful");
    }
    

    如果它对单个用户来说是唯一的,你必须从你的数据库中为那个特定用户获取“auth_password”并验证它

    要在全局范围内使用它,您可以像这样构建注释

    @Before("@annotation(tokenValidation)")
    public void beforeAdvice(TokenValidation tokenValidation) {
       String authToken = request.getHeader("Auth-header");
       if (authToken == null) {
          log.error("Self token authentication failed");
          throw new Exception(TOKEN_NOT_FOUND);
       }
    
       if (!"auth_password".equals(authToken)) {
          log.error("Self token authentication failed");
          throw new Exception(AUTH_FAILED);
       }
       log.info("Self token authentication successful");
    }
    

    你可能需要查看如何在spring boot中实现注释,但这是一个基本概念。

    在控制器中,你只需要这样做

    @tokenValidation
    public String controllerFunction(String authToken){
       //your code;
    }
    

    【讨论】:

    • 感谢您的回答。有没有办法为全球少数请求添加此授权标头?这样我就可以避免冗余代码
    • 我已经编辑了原始答案,以便其他人更容易寻找答案。
    猜你喜欢
    • 2014-07-29
    • 2017-01-02
    • 1970-01-01
    • 2018-07-30
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多