WebAPI [授权]登录时返回错误 [英] WebAPI [Authorize] returning error when logged in
问题描述
我正在尝试使用 MVC5
/ Web Api 2
设置 WebAPI
,它目前正在使用默认配置,并且现在使用其他默认设置.当我在浏览器中使用帐户登录时,可以使用 [Authorize]
属性正常执行常规的 MVC
控制器操作,例如主页所示应该在授权时使用,但是如果我转到/api/Me
(默认内置api控制器操作)或我使用默认MVC Web Api 2脚手架构建的任何自定义api控制器操作,需要授权,我会收到类似这样的错误:
I'm trying to set up a WebAPI
with MVC5
/ Web Api 2
, it's currently using default configurations and other defaults right now. When I log in with an account in the browser, I can go to regular MVC
controller actions with the [Authorize]
attribute just fine, such as the Home page shows as it should when authorized, but then if I go to /api/Me
(a default built-in api controller action) or any custom api controller action I've built with the default MVC Web Api 2 scaffolding that requires authorization, I get an error like so:
{"message":"Authorization has been denied for this request."}
这是当我在Microsoft Edge中尝试时,还没有在我正在构建的实际客户端代码(这是一个 UWP
应用程序)上尝试过.我认为我会先在浏览器中进行测试,以确保一切正常.
This is when I'm trying it in Microsoft Edge, I haven't tried it on my actual client code I'm building yet, which is a UWP
app. I figured I would test in the browser first to ensure things are working properly.
我开始看这篇文章: https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/security/individual-accounts-in-web-api 似乎更适合但是, Ajax
请求和 SPAs
.我的目标是使事情在网络上以及通过 UWP
都能正常工作.与使用ajax开发健壮的Web应用程序相比,我可能会把更多的时间放在 UWP
方面,因为该应用程序将在Intranet中运行并访问运行Web api的Intranet IIS服务器.在UWP中构建一个桌面客户端,最后在Xamarin中构建一个通过Web Api访问数据的客户端.
I started looking at this article: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api It seems to be more geared towards Ajax
requests and SPAs
though. My goal is having things working through both the web and through UWP
. I will probably focus more time on the UWP
side than developing a robust web app with ajax, since the app will run in an intranet and access an intranet IIS server running the web api, I'd like to build a desktop client in UWP and eventually Xamarin that access data through Web Api.
对于我来说,可以安全地假设,如果您使用的是Edge之类的常规Web浏览器,则当通过 [Authorize]
属性保护Web Api控制器操作时,它们将无法访问,因为它不会不是在标头中发送访问令牌?
Is it safe for me to assume that if you're using a regular web browser like Edge you cannot access Web Api controller actions when they are secured through the [Authorize]
attribute, since it doesn't send an access token in the header?
推荐答案
因此,在您的UWP应用中,您可以创建以下几种方法,也可以将它们包装在可通过DI注入的类中(您可以选择).
So from your UWP app you could create a couple of methods such as below, or may be wrap them up in a class that you can inject through DI (your choice).
public async Task<TResult> GetAsync<TResult>(string uriString) where TResult : class
{
var uri = new Uri(uriString);
using (var client = GetHttpClient())
{
HttpResponseMessage response = await client.GetAsync(uri);
if (response.StatusCode != HttpStatusCode.OK)
{
//Log.Error(response.ReasonPhrase);
return default(TResult);
}
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResult>(json, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
}
}
public async Task<TResult> PostAsync<TResult, TInput>(string uriString, TInput payload = null) where TInput : class
{
var uri = new Uri(uriString);
using (var client = GetHttpClient())
{
var jsonContent = JsonConvert.SerializeObject(payload, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
HttpResponseMessage response = await client.PostAsync(uri, new StringContent(jsonContent, Encoding.UTF8, "application/json"));
if (response.StatusCode != HttpStatusCode.OK)
{
//Log.Error(response.ReasonPhrase);
return default(TResult);
}
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResult>(json);
}
}
如果您使用的是基本的(用户名和密码身份验证),那么您的GetHttpClient方法将类似于:
And if you are using basic (username and password authentication) then your GetHttpClient method will be something like:
private HttpClient GetHttpClient()
{
var client = new HttpClient();
var username = // get username;
var password = // get password;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
或者如果您正在使用不记名令牌,则可以执行以下操作:
or if you are using bearer token then you could do:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer ", "string token goes here...");
这篇关于WebAPI [授权]登录时返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!