1
以及我需要发送用户名和密码来为登录生成令牌,这个问题始终是我从客户端(角度)响应发送的错误,但是当我发送它时从邮递员工作很好。cakephp 3 + Jwt + angular-401(未经授权)
public function initialize()
{
parent::initialize();
$this->Auth->allow(['add', 'token', 'me']);
}
public function token()
{
$user = $this->Auth->identify();
if (!$user)
{
throw new UnauthorizedException('Invalid username or password');
}
$this->set([
'success' => true,
'data' => [
'user_id' => $user['id'],
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
我怎么把它
$scope.doLogin = function()
{
dataLogin = {
username: vm.username,
password: vm.password
};
console.log(dataLogin);
// call the Auth.login() function
//$scope.processing = true;
$scope.error = '';
Auth.login(dataLogin)
.then(function(data) {
if (data.success)
$state('home');
else
console.log(data);
$scope.error = data.message;
});
};
和
authFactory.login = function(dataLogin) {
return apiService.request('POST', '/api/users/token', dataLogin).then(function(data) {
AuthToken.setToken(data.token);
return data;
});
};
apiService的应用角度
(function(){
angular
.module('appDekma')
.factory('apiService', apiService);
apiService.$inject = ['$http'];
function apiService($http) {
return {
request: sendRequest
};
function sendRequest(method, endpoint, data) {
var API_HOST = 'http://localhost/dekma_backend';
var req = {
method: method || 'GET',
url: API_HOST + endpoint,
data: data || '',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Headers': 'Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token',
'Access-Control-Max-Age': '3600'
}
};
return $http(req)
.then(successCallback, errorCallback);
function successCallback(response)
{
return response.data;
}
function errorCallback(error) {
var message = 'Something terrible happened!';
if (error.data && error.data.code)
{
switch (error.data.code)
{
case 500:
break;
case 401:
break;
case 403:
break;
case 404:
message = 'Could not find content';
break;
default:
break;
}
}
return error.data;
}
}
}
})();
如果你进入了Chrome的网络选项卡,并检查请求头,并一切看起来是否正确?它和你的邮差请求之间有一些区别。 – mkaatman
我对你的AngularJS代码有点困惑,它看起来像你传递用户名和密码到你的工厂的登录方法,但你的工厂接受一个参数。 –
是的,我有所有的头正确 – CoolLife