Shu*_*han 25 oauth openid-connect asp.net-core identityserver4 asp.net-core-3.0
我正在尝试重定向到 IdentityServer 进行授权,并在重定向 URL 中获取“需要代码质询”。
错误消息显示invalid_request需要代码质询,还有我的重定向 URL http://localhost:44367/signin-oidc#error=invalid_request&error_description=code%20challenge%20required&state=CfDJ8Cq6lLUEMhZLqMhFVN
这是我的客户端配置:
namespace TestClient
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddControllersWithViews();
ConfigureIdentityServer(services);
services.AddCors();
}
private void ConfigureIdentityServer(IServiceCollection services)
{
var builder = services.AddAuthentication(options => SetAuthenticationOptions(options));
services.AddMvcCore()
.AddAuthorization();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
builder.AddCookie();
builder.AddOpenIdConnect(options => SetOpenIdConnectOptions(options));
}
private void SetAuthenticationOptions(AuthenticationOptions options)
{
options.DefaultScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectDefaults.AuthenticationScheme;
}
private void SetOpenIdConnectOptions(OpenIdConnectOptions options)
{
options.Authority = "https://localhost:44346";
options.ClientId = "TestIdentityServer";
options.RequireHttpsMetadata = false;
options.Scope.Add("profile");
options.Scope.Add("openid");
options.Scope.Add("TestIdentityServer");
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.ClientSecret = "0b4168e4-2832-48ea-8fc8-7e4686b3620b";
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
}
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
);
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 IdentityService4 配置
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
IdentityModelEventSource.ShowPII = true;
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);
services.Configure<IISOptions>(iis =>
{
iis.AuthenticationDisplayName = "Windows";
iis.AutomaticAuthentication = false;
});
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
});
// this adds the config data from DB (clients, resources)
builder.AddInMemoryIdentityResources(Configuration.GetSection("IdentityResources"));
builder.AddInMemoryApiResources(Configuration.GetSection("ApiResources"));
builder.AddInMemoryClients(Configuration.GetSection("clients"));
services.AddAuthentication();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
}
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
Run Code Online (Sandbox Code Playgroud)
和 appsettings.json
"IdentityResources": [
{
"Name": "openid",
"DisplayName": "Your user identifier",
"Required": true,
"UserClaims": [
"sub"
]
},
{
"Name": "profile",
"DisplayName": "User profile",
"Description": "Your user profile information (first name, last name, etc.)",
"Emphasize": true,
"UserClaims": [
"name",
"family_name",
"given_name",
"middle_name",
"preferred_username",
"profile",
"picture",
"website",
"gender",
"birthdate",
"zoneinfo",
"locale",
"updated_at"
]
}
],
"ApiResources": [
{
"Name": "TestIdentityServer",
"DisplayName": "TestIdentityServer API Services",
"Scopes": [
{
"Name": "TestIdentityServer",
"DisplayName": "TestIdentityServer API Services"
}
]
}
],
"Clients": [
{
"ClientId": "TestIdentityServer",
"ClientName": "TestIdentityServer Credentials Client",
// 511536EF-F270-4058-80CA-1C89C192F69A
"ClientSecrets": [ { "Value": "entAuCGhsOQWRYBVx26BCgZxeMt/TqeVZzzpNJ9Ub1M=" } ],
"AllowedGrantTypes": [ "hybrid" ],
"AllowedScopes": [ "openid", "profile", "TestIdentityServer" ],
"RedirectUris": [ "http://localhost:44367/signin-oidc" ],
//"FrontChannelLogoutUris": [ "http://localhost:44367/Home/Privacy" ],
//"PostLogoutRedirectUris": [ "http://localhost:44367/Home/Privacy" ],
"redirect_uri": "http://localhost:44367/signin-oidc"
}
Run Code Online (Sandbox Code Playgroud)
小智 38
我非常确定您使用的是版本4.0或更高版本。让我知道我是否正确?
在版本4.0及以上版本中,code flow + PKCE默认使用 ,因为这比Hybrid flow根据文档更安全。
这是链接https://identityserver4.readthedocs.io/en/latest/topics/grant_types.html和 github 上相关问题的链接https://github.com/IdentityServer/IdentityServer4/issues/3728将其描述为一个破坏改变。
当我在我的一个项目中将 IdentityServer4 包升级到最新版本时,我也挣扎了大约 2 个小时。
如果您想在客户端配置中使用Hybrid flowset RequirePkceto false。
"Clients": {
/* Code removed for brevity */
RequirePkce : "false"
}
Run Code Online (Sandbox Code Playgroud)
Sér*_*edo 10
今天遇到了这个错误并通过从以下切换解决了它:
options.ResponseType = "code id_token";
Run Code Online (Sandbox Code Playgroud)
到
options.ResponseType = "code";
options.UsePkce = true;
Run Code Online (Sandbox Code Playgroud)
这是我完整的客户端选项:
options.Authority = "http://localhost:8000";
options.RequireHttpsMetadata = false; // dev only
options.ClientId = "testAPI";
options.ClientSecret = secret;
// code flow + PKCE (PKCE is turned on by default)
options.ResponseType = "code";
options.UsePkce = true;
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
options.Scope.Add("testAPI");
options.ClaimActions.MapJsonKey("website", "website");
//options.ResponseMode = "form_post";
//options.CallbackPath = "/signin-oidc";
// keeps id_token smaller
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
Run Code Online (Sandbox Code Playgroud)
另外,当我在 docker 上使用 IdentityServer 并在主机上测试客户端时,我必须配置一个额外的重定向 Uri 才能进行测试:
RedirectUris =
{
"http://localhost:5001/signin-oidc",
"http://host.docker.internal:5001/signin-oidc",
"http://notused"
},
Run Code Online (Sandbox Code Playgroud)
我的实现基于GitHub上的 Dominic Baier 示例。
编辑:我现在已经明白,对于我的情况,响应类型只能是“代码”,因为我的客户端配置用于授权代码 + PKCE(OAuth2 流)。您配置了支持“code id_token”的“混合”(OIDC 流),因此尽管我们收到了相同的错误消息,但问题有所不同。
| 归档时间: |
|
| 查看次数: |
13631 次 |
| 最近记录: |