如何在REST控制器的每个REST API中检查授权令牌,而无需重写方法。

huangapple go评论74阅读模式
英文:

How to check for Authorization Token in every Rest API in a rest controller without rewriting a method

问题

我正在使用Spring Boot(Maven)构建一个Rest Controller,我希望我的API能够使用Authorization Bearer令牌,如果令牌无效,我可以发送401响应,但我不想在我创建的每个API中手动进行检查。是否有一种方法可以在实际运行API之前运行检查令牌是否有效的方法。

如果令牌无效,我希望发送401响应,而不是API原本预期的行为。

英文:

I am building a Rest Controller in Spring Boot (Maven), and I want to be able to have my APIs have a Authorization Bearer token in which I can send a 401 response if the token is invalid but I do not want to manually check in every API that I create, Is there a way in which I can run a method that checks if the token is valid before actually running the API.

If the token is not valid I want to send a 401 instead of what the API was attended for.

答案1

得分: 1

你可以创建一个自定义过滤器(实现 javax.servlet.Filter 接口),它将拦截每个传入的请求,在这里你可以编写逻辑来检查请求是否有授权头。

@Component
public class AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (req.getHeader("Authorization") != null){ //or replace with a further fine grained condition
            chain.doFilter(request, response);
        } else {
            HttpServletResponse res = (HttpServletResponse) response;
            res.setStatus(401);
        }
    }
}
英文:

You can create a custom filter (implementing javax.servlet.Filter), which would intercept every incoming request, where you can have your logic of checking if the request has an Authorization header.

@Component
public class AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (req.getHeader("Authorization") != null){ //or replace with a further fine grained condition
            chain.doFilter(request, response);
        } else {
            HttpServletResponse res = (HttpServletResponse) response;
            res.setStatus(401);
        }
    }
}

huangapple
  • 本文由 发表于 2020年9月26日 12:20:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64073849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定