OpenIdConnect with .NET Core 2.2 MVC to IdentityServer3 usin



它似乎设置了从.NET Core 2.2到IdentityServer3的OpenIdConnect身份验证,我必须通过通用的AddOpenIdConnect()调用进行设置,为了使范围策略起作用,我已经覆盖了OnTokenValidated,在那里我解析收到的访问令牌,并将其中的范围添加到ClaimsPrincipal对象。

我没有发现其他方法可以让范围策略起作用。不过,这似乎有点黑客。有没有更好或更简单的方法,这样我就不需要覆盖事件,或者至少不需要解析访问令牌?无论如何,它是在框架中解析的,所以我怀疑还有其他功能可用于将范围放入声明主体。

将我们的代码从 .NET 4.5.2 移动到 .NET Core 2.2,我需要以非常不同的方式设置对IdentityServer3服务器的身份验证。

我希望后来的框架中的新功能允许对IdentityServer3进行身份验证的简单设置,但我没有找到合适的示例。

我看到有人说IdentityServer4.AccessTokenValidationNuGet 包可以面向IdentityServer3,但我发现的唯一示例是使用简单的 JWT 身份验证不允许隐式用户登录流。

因此,我最终使用标准 ASP.NET 核心库来设置 openidconnect,然后我需要调整代码以使其工作。

不确定下面的代码是否处理了它所需要的一切,但至少我已经到了可以登录并使用新网站并编写赛普拉斯测试的地方。关于如何做得更好或更简单的任何建议将不胜感激。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
// Without this, I get "Correlation failed." error from Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(o => {
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddCookie().AddOpenIdConnect(o =>
{
o.Authority = "https://myidentityserver3.myfirm.com";
o.ClientId = "myidentityserver3clientname";
o.SignedOutRedirectUri = "https://localhost:50011/signout";
o.ResponseType = "id_token token";
o.SaveTokens = true;
o.Scope.Add("openid");
o.Scope.Add("roles");
o.Scope.Add("profile");
o.Scope.Add("customrequiredscopeforapi");
o.GetClaimsFromUserInfoEndpoint = false;
{
var old = o.Events.OnTokenValidated;
o.Events.OnTokenValidated = async ctx =>
{
if (old != null) await old(ctx);
var token = MyCustomAuthUtils.ParseBearerToken(ctx.ProtocolMessage.AccessToken);
foreach (var scope in token.Scopes)
{
ctx.Principal.AddIdentity(new ClaimsIdentity(new[] { new Claim("Scope", scope) }));
}
// Our controllers need access token to call other web api's, so putting it here.
// Not sure if that is a good way to do it.
ctx.Principal.AddIdentity(new ClaimsIdentity(new[] { new Claim("access_token", ctx.ProtocolMessage.AccessToken) }));
};
}
});
var mvcBuilder = services.AddMvc(o =>
{
o.Filters.Add(new AuthorizeFilter(ScopePolicy.Create("customrequiredscopeforapi")));
});
services.AddAuthorization();
}

第一件事是你不需要对访问令牌进行人工解码,只需在事件中使用ctx.SecurityToken.Claims即可OnTokenValidated获取令牌中包含的所有声明。

我不确定为什么您需要使用scope来识别权限.符合 OIDC 标准的管道中的范围参数确定:

  • 授权应用程序对给定资源服务器应具有的权限
  • ID 令牌中应包含哪些标准配置文件声明(如果用户同意向应用程序提供此信息)

您可以使用role来标识当前登录用户是否可以访问受保护的资源。OpenID Connect中间件将有助于映射role权利要求原则。

最新更新