首页 > 解决方案 > 仅 xamarin 表单应用程序的 Asp.net Core 授权失败

问题描述

我开发了一个简单的应用程序来练习。该组合是带有 JWT 令牌的 ASP.NET CORE。

在我的 asp.net core 3.1 服务器上,我有这个 DI 代码:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = configuration["jwt:Issuer"],
                        ValidAudience = configuration["jwt:Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["jwt:Key"]))
                    };
                });

我可以轻松地与 Postman 或我的 BlazorApp 连接以生成令牌并使用令牌使用其他端点。在 Blazor 上,我只需要插入一个 DefaultHeader:

_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);

现在,我正在尝试对 Xamarin Forms 应用程序做同样的事情。我尝试在默认标头上使用生成的令牌,但我得到了未经授权的响应。

要调试 Xamarin Forms 应用程序,我必须将我的 localhost 端点名称更改为 127.0.0.1(以便模拟器可以访问我机器上的 asp.net API)。

我试图将我的 JWT 令牌的颁发者更改为 127.0.0.1 而不是 localhost 但没有成功。

有人可以帮忙吗?

提前致谢。

标签: xamarin.formsjwtasp.net-core-webapidotnet-httpclientblazor-webassembly

解决方案


2天后我收到了。

我的 asp.net 核心 api 使用的是 HttpsRedirect,而我的 Xamarin Mobile 没有指向 HTTPS 端口。

我不知道为什么,因为 postman 和 blazor 可以同时使用两个端点(HTTP 和 https 端口),但是 Xamarin 自从我使用 https 端点后就开始工作了。

现在好了。不管怎么说,还是要谢谢你


推荐阅读