我正在嘗試使用Spring Boot
來編寫身份驗證過濾器;其中我檢查了一些cookie,如果它出現在請求中,我希望將該請求標記爲已授權,如果不是,我想返回401
標題以響應客戶端調用我的服務。無法發送來自Spring Boot過濾器http頭中的「Unauthorized」
下面是我用我的春天引導過濾器行:
((HttpServletResponse) res).sendError(HttpServletResponse.SC_UNAUTHORIZED, "User is not authenticated, so can not access IPT service.");
雖然這條線被我驗證過濾器執行時cookie是在請求不存在;在我的客戶端代碼,我沒有看到頭401
一套使用response.headers
我甚至嘗試使用檢查時:
((HttpServletResponse) res).addHeader("401", "Unauthorized!");
return;
但是,沒有運氣!
我做錯了什麼?
EDIT#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!");
});
EDIT#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.");
}
}
感謝
顯示您的過濾器代碼和過濾器配置。 – StanislavL