使用 Reactjs 前端在 Yii2 应用程序中提供身份验证 [英] Provide Authentication in a Yii2 Application using Reactjs frontend
问题描述
我正在使用 Yii2 API 和 reactjs 前端.我想在我的 api 中实现身份验证,以便只有使用 Bear 身份验证类的经过身份验证的用户才能访问我的 API 函数.我已按如下方式实施了我之前的操作:
I am working with a Yii2 API and a reactjs fronted. I want to implement authentication in my api such that only authenticated users using the Bear authentication class can access my API functions. I have implemented my Before actions as follows :
//Yii::$app->response->format = Response::FORMAT_JSON;
/*directly include pagination info in the request body to simplify client development*/
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
public static function allowedDomains()
{
return [
// '*' // star allows all domains
'http://localhost:3000',
'http://localhost:4200',
'http://192.168.8.101:3000',
];
}
public function behaviors()
{
return array_merge(parent::behaviors(), [
// For cross-domain AJAX request
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
// restrict access to domains:
'Origin'=> static::allowedDomains(),
'Access-Control-Request-Method' => ['POST','GET','PUT','OPTIONS', 'PATCH','DELETE'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,// Cache (seconds)
'Access-Control-Request-Headers' => ['Origin', 'X-Requested-With', 'Content-Type', 'accept', 'Authorization'],
//'Access-Control-Allow-Credentials' => true,
'Access-Control-Allow-Origin' => false,
],
],
//authenticate the user before execute the actions
'authenticator'=>[
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
//QueryParamAuth::className(),
],
'except' => ['search'],
],
]);
}
在我的 reactjs 前端,我使用函数调用 getposts 进行 API 调用以从 api 获取数据
In my reactjs frontend, I make an API call to get data from the api using a function call getposts which is
function getposts(userId) {
const requestOptions = {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + user.auth_key,
'Content-Type': 'application/json'
},
body: JSON.stringify(userId)
};
//console.log('we are about to login');
return fetch(apiConstants.API_POST_URL, requestOptions)
.then(handleResponse)
.then(json => {
console.log(json);
return json;
});
}
其中 auth_key 是用于验证的授权密钥.当我使用 chrome 浏览器进行调试时,出现 401 错误(未经授权).从 { my URL } 获取的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头.
where auth_key is the authorization key to be used for verification. When I use the chrome browser for debug, I get a 401 error ( Unauthorized). With Access to fetch from { my URL } has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
注意,我在邮递员中使用该密钥来获取我需要的数据,并且运行良好.我更改了多个用户密钥(甚至传递了默认值),但它们不起作用.
Note, I use that key in postman to get the data I need and it works well. I have changed multiple user keys ( and even pass default values) and they don't work.
对此问题的任何帮助或帮助将不胜感激.谢谢
Any heads on or help on this issue will be greatly appreciated. thanks
推荐答案
Yii2 Bearer 身份验证类不适用于 Reactjs 和 Angular JS 等 JavaScript 前端.我通过将身份验证方法更改为 QueryParmas 解决了这个问题,因此我的提取看起来像
Yii2 Bearer authentication class does not work with JavaScript frontends such as Reactjs and Angular JS. I solved this problem by changing the authentication method to QueryParmas so My fetch looks like
return fetch(apiConstants.API_POST_URL+'?access-token='+user.auth_key, requestOptions)
.then(handleResponse)
.then(json => {
console.log(json);
return json;
});
然后在我的 Yii2 行为中,我必须激活查询身份验证
then in my Yii2 behaviors, I had to activated Query authentication
'authenticator'=>[
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
],
这篇关于使用 Reactjs 前端在 Yii2 应用程序中提供身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!