gpt4 book ai didi

c# - ASP.NET 核心 2.0 : Authorization failed for user: (null)

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:59 25 4
gpt4 key购买 nike

我正在构建一个应用程序,其中 Web API 和 IdentityServer4 位于同一个 .Net Core 2.0 项目中。此 API 由 Aurelia SPA 网络应用程序使用。 IdentityServer4 设置为使用 JWT 和 ImplicitFlow。一切正常(客户端应用程序被重定向到登录、获取 token 、将其发送回 header 等)直到用户需要在 API Controller 中获得授权,然后它就无法授权用户,因为它是空的。

存在许多类似的问题,但我尝试了所有建议的解决方案,但没有一个对我有用。我已经在这个问题上花了 2 天时间,开始失去希望和耐心。我可能遗漏了一些明显的东西,但就是找不到。我在这里发布我的配置 - 它们有什么问题?将不胜感激。

我的 Startup 类(我省略了一些额外的东西,比如日志记录、本地化等):

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.AddCors(options =>
{
options.AddPolicy("default", policy =>
{
policy.WithOrigins(Config.APP1_URL)
.AllowAnyHeader()
.AllowAnyMethod();
});
});

services.AddMvc();

services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = false;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 4;

// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;

// User settings
options.User.RequireUniqueEmail = true;
});

services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>();

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = Config.HOST_URL + "/";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseIdentityServer();

app.UseAuthentication();

app.UseCors("default");

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}

这是我的配置类:

public class Config
{
public static string HOST_URL = "http://dev.example.com:5000";
public static string APP1_URL = "http://dev.example.com:9000";

public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
}

public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}

public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "reporter",
ClientName = "ReporterApp Client",
AccessTokenType = AccessTokenType.Jwt,
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = false,
AllowAccessTokensViaBrowser = true,
RedirectUris =
{
$"{APP1_URL}/signin-oidc"
},
PostLogoutRedirectUris = {
$"{APP1_URL}/signout-oidc"
},
AllowedCorsOrigins = {
APP1_URL
},

AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
}
}
};
}
}

Aurelia 应用程序从 IdentityServer 获取 token :

{
"alg": "RS256",
"kid": "52155e28d23ddbab6154ce0c34511c9a",
"typ": "JWT"
},
{
"nbf": 1521195164,
"exp": 1521198764,
"iss": "http://dev.example.com:5000",
"aud": ["http://dev.example.com:5000/resources", "api1"],
"client_id": "reporter",
"sub": "767381df-446a-4c34-af27-7bdf9e4563f3",
"auth_time": 1521195163,
"idp": "local",
"scope": ["openid", "profile", "api1"],
"amr": ["pwd"]
}

最佳答案

首先,交换您的订单 UseAuthencation 而不是写一些东西。

app.UseAuthentication();
app.UseIdentityServer();

其次更改 cookie 方案。 Identityserver4 有自己的,所以你的用户是空的,因为它没有读取 cookie。

services.AddAuthentication(IdentityServerConstants.DefaultCookieAuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
// base-address of your identityserver
options.Authority = Configuration.GetSection("Settings").GetValue<string>("Authority");
// name of the API resource
options.ApiName = "testapi";
options.RequireHttpsMetadata = false;
});

想法三:

我必须将类型添加到 api 调用中,以便它读取不记名 token 。

[HttpPost("changefiscal")]
[Authorize(AuthenticationSchemes = "Bearer")]
public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
{
// STuff here
}

关于c# - ASP.NET 核心 2.0 : Authorization failed for user: (null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49319369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com