【发布时间】:2021-04-17 20:11:49
【问题描述】:
我有一台运行 asp.net 的服务器。我遵循网络上的教程,使我的服务器能够向请求它的客户端发出令牌 Auth0 2 并创建 web api,以便我的 android 模拟器能够从服务器检索一些数据。我将令牌过期日期设置为 365 天。我尝试通过提供 grant_type、用户名和密码来向 Postman 请求令牌,并且正如预期的那样,服务器返回给我一个令牌,我使用 Postman 的 Get 方法从 API 端点获取一些数据并在标头中提交令牌,正如预期的那样服务器成功地将数据返回给我,没有任何问题。邮递员能够使用昨天的令牌问题从服务器获取数据,所以我认为令牌实现是正确的。
服务器:
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(365),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
app.UseOAuthBearerTokens(OAuthServerOptions);
Android 原生反应: 登录以从服务器获取访问令牌
var formBody="grant_type=password&username="+userEmail+"&password="+userPassword;
fetch('http://aaa.aaaa.com/token', {
method: 'POST',
body: formBody,
headers: {
//Header Defination
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
})
.then((response) => response.json())
.then((responseJson) => {
//Hide Loader
setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
//if (responseJson.status == 1)
if (responseJson.access_token)
{
global.token=responseJson.access_token;
AsyncStorage.setItem('access_token', responseJson.access_token);
//console.log(responseJson.data[0].user_id);
//navigation.replace('DrawerNavigationRoutes');
navigation.navigate('NavigatorHome');
} else {
//AsyncStorage.setItem('user_id', 'test1');
//navigation.navigate('NavigatorHome');
//setErrortext('Please check your email id or password');
console.log('Please check your email id or password');
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
从 API 端点获取数据
var accessToken=global.token;
var formBody="";
formBody = JSON.stringify({
'module': 'order',
'action': 'get',
'value':route.params.orderID
})
fetch('http://aaa.aaaa.com/api/Orders?ID='+formBody, {
method: 'Get',
headers: {
//Header Defination
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
},
})
.then((response) => response.json())
.then((responseJson) => {
//Hide Loader
//setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
//if (responseJson.status == 1)
})
.catch((error) => {
//Hide Loader
//setLoading(false);
console.error(error);
});
之后我尝试使用 android 模拟器运行。首先,我通过提供 grant_type、用户名和密码来使用 fetch 方法,正如预期的那样,服务器向我返回了一个令牌,我将它存储在 AsyncStorage 中。然后我尝试通过提供我之前请求的令牌来获取一些数据,并且服务器能够毫无问题地向我返回数据。但是如果我离开我的模拟器 15 分钟或 30 分钟,现在当我尝试从服务器获取数据时它会失败。我所做的是尝试通过再次发送grant_type、用户名和密码来请求新令牌,并且新令牌按预期工作。
这很奇怪!我在服务器上仔细检查了我的访问令牌设置,即 365 天,邮递员能够通过使用昨天发布的令牌毫无问题地获取数据,为什么颁发给我的模拟器的令牌在 15 或 30 分钟内过期?希望有人能指出我的问题。提前致谢!
【问题讨论】:
标签: android react-native oauth-2.0 bearer-token