【发布时间】:2017-12-25 15:21:44
【问题描述】:
我正在尝试使用Spring Boot 编写身份验证过滤器;其中我检查了一些 cookie,如果它存在于请求中,我想将请求标记为已授权,否则我想返回 401 标头以响应客户端调用我的服务。
下面是我在 Spring Boot 过滤器中使用的行:
((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "User is not authenticated, so can not access IPT service.");
虽然当请求中没有 cookie 时,此行会在我的 Auth 过滤器中执行;在我的客户端代码中,当使用 response.headers 检查时,我没有看到标题 401 设置
我什至尝试过使用:
((HttpServletResponse) res).addHeader("401", "Unauthorized!");
return;
但是,没有运气!
我做错了吗?
编辑#1:
添加处理请求/响应的客户端代码:
fetch(FETCH_URL, {
method: 'GET',
dataType: 'json',
credentials: 'include'
}).then(
function(response) {
if(response.status == 401) {
console.log("----->", response);
alert(response + " Redirect to login page!");
}
},
function() {
alert("Error!");
});
编辑#2:
当我尝试收到 Finnbar O'G 建议的错误消息时:
response.text().then((text) => { console.log("----->", text); });
我得到了整个 HTML:
<!doctype html>
<html lang="en">
<head><title>HTTP Status 401 – Unauthorized</title>
<style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}
</style>
</head>
<body>
<h1>HTTP Status 401 – Unauthorized</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> User is not authenticated, so can not access IPT service.</p><p><b>Description</b> The request has not been applied because it lacks valid authentication credentials for the target resource.</p><hr class="line" /><h3>Apache Tomcat/9.0.0.M22</h3>
</body>
</html>
我怎样才能只从服务器获取我作为sendError 方法的第二个参数添加的消息?
好吧,这是我的过滤器代码:
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
LOGGER.info("****************** Inside Auth Filter ******************");
boolean success = process(req); // Checks if auth cookie is set in request
if (success) {
filterChain.doFilter(req, res);
} else {
// ((HttpServletResponse) res).addHeader("401", "Unauthorized!");
((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "User is not authenticated, so can not access IPT service.");
}
}
谢谢
【问题讨论】:
-
显示您的过滤器代码和过滤器配置。
标签: javascript spring reactjs servlets spring-boot