我在Xamarin.Form项目中使用Azure身份验证,收到的令牌用于进行API调用以进行身份验证。
在将应用程序保留在后台之后的一段时间之后,我再次尝试使API调用返回“未授权”。 令牌到期时间设置为30分钟。但是,一旦将应用程序保留在后台并且某些时候它正常工作,未经授权的错误就不会发生。
有没有人遇到同样的问题。
public async Task<Response> AuthenticatedGet(string uri, string accessToken, string content = null)
{
Uri restUri = new Uri(uri, UriKind.RelativeOrAbsolute);
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(60);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, restUri.ToString());
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Authorization",
string.Format("Bearer {0}", accessToken));
var result = await client.SendAsync(request);
//HttpClient client = new HttpClient();
//client.Timeout = TimeSpan.FromSeconds(60);
//var result = await client.SendAsync(request);
Response sr = new Response();
if (result.IsSuccessStatusCode)
{
string responseString = await result.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(responseString))
{
sr.ResponseData = responseString;
sr.IsSuccess = true;
sr.StatusCode = (int)result.StatusCode;
}
}
else if (result.StatusCode == HttpStatusCode.NotFound)
{
sr.ResponseData = $"Service not found at the specifed uri {uri}";
sr.IsSuccess = false;
sr.StatusCode = (int)result.StatusCode;
}
else
{
//var responseString = await result.Content.ReadAsStringAsync();
//JObject jObject = JObject.Parse(responseString);
//var messageProperty = jObject.Property("Message");
//if (messageProperty != null && result.StatusCode == HttpStatusCode.Unauthorized)
//{
// var message = messageProperty.Value?.ToString();
// sr.Message = !string.IsNullOrEmpty(message) ? message : result.ReasonPhrase;
// LogoutUnauthorisedUser?.Invoke(message);
// throw new UnauthorizedAccessException(message);
//}
//sr.Message = result.ReasonPhrase;
//sr.IsSuccess = false;
//sr.StatusCode = (int)result.StatusCode;
//TODO: Handle Unauthorized user
}
return sr;
}
public async Task<ObservableCollection<NIODetails>> GetABCServiceAsync()
{
var uri = string.Format(_hostConfiguration.ABCHostName + _hostConfiguration.ABC, Configuration.ABC);
var resonse = await _httpService.AuthenticatedGet(uri, Constant.ADToken, null);
if (resonse.IsSuccess)
{
var list = JsonConvert.DeserializeObject<ObservableCollection<ABCDetails>>(resonse.ResponseData);
return list;
}
else
{
return null;
}
}