英文:
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);
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论