我正在实施JWT身份验证,但我在标题中设置了授权问题。
看起来似乎未在请求中设置“授权”标题。
我收到了客户端发送的2个请求,第一个是请求中的Authorization标头传递:
// GET PROJECTS NAME
projects.getName = () => { // === projects.getName = function() { ... }
return $http.get(Global.url_api+'action=GETINFO&table=Projects');
}
浏览器中的请求:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....
Host: *******-tpinst.fr
Origin: http://localhost:2000
Proxy-Connection: keep-alive
Referer: http://localhost:2000/
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
但我的第二个请求与第一个请求的实现方式相同,但未通过此授权标头:
users.get = function(project){
return $http.get(Global.url_api+'action=GET&table='+project+'_users');
}
在浏览器中:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Host: bouygues-tpinst.fr
Origin: http://localhost:2000
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
授权在主程序中设置:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = 'Bearer
'+localStorage.getItem('tokenAPI');
}])
我在服务器端使用以下行设置Allow origin:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE,
OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
我是这些安全概念的初学者,请指导我一个好方法
编辑:
我刚刚发现了一个提示,在我的api.php中我得到了这一行,向客户发送错误401:
$Authorization = $_SERVER['HTTP_AUTHORIZATION'];
//Looking for authorization headers
if($Authorization){ ... }
else {
header('HTTP/1.0 401 Unauthorized'); //Give error code 401
echo 'Token not found in the header';
}
当我删除
标题('HTTP / 1.0 401 Unauthorized');
标题中的授权传递
答案 0 :(得分:0)
删除$httpProvider.defaults.headers.common
而是实现一个http拦截器
试试这个
app.factory("authInterceptor", authInterceptor);
authInterceptor.$inject = ["$q"];
function authInterceptor($q) {
return {
// Add an interceptor for requests.
'request': function (config) {
// Default to an empty object if no headers are set.
config.headers = config.headers || {};
// Set the token
var token = localStorage.getItem('tokenAPI');
config.headers.Authorization = "Bearer " + token;
return config;
},
// Add an interceptor for any responses that error.
'responseError': function (response) {
// Check if the error is auth-related.
if (response.status === 401 || response.status === 403) {
}
return $q.reject(response);
}
};
}
app.config(["$httpProvider",
function ($httpProvider) {
//Registers the interceptor
$httpProvider.interceptors.push("authInterceptor");
}]);
我认为重新安排脚本会导致问题,将控制器脚本放在底部
类似这样的事情
在 main.js 中删除
var app = angular.module('App', ['ngMaterial', 'ngMessages'])
因为我们将其放在index.html