繁体   English   中英

使用OIDC对SPA,WEBAPI和Identity Server 4进行自定义声明?

[英]Custom claims with SPA, WEBAPI and Identity Server 4 using oidc?

几天来一直在敲我的头。

因此,我使用Identity Server 4(即我的“身份验证即服务”)对所有应用程序进行集中登录,并使用ASP.NET Identity进行用户管理。

在我的客户端上,我将Angular与oidc-client.js ,到目前为止,一切工作都按预期进行,我可以获得用户身份令牌和访问令牌。

对于我的WebApi(不使用.NET Core),我尝试使用UseOpenIdConnectAuthentication因此我可以通过它添加应用程序特定的自定义声明OpenIdConnectAuthenticationNotifications但是从Angular调用我的API时会获得“ 401 Unauthorized

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
     ResponseType = "id_token token",
     Scope = "openid profile api1",
     Authority = "http://localhost:61294/",
     ClientId = "api",
     RedirectUri = "http://localhost:56105/sigin-oidc",
     Notifications = new OpenIdConnectAuthenticationNotifications
     {
         AuthorizationCodeReceived = async n =>
         {
             // Ignore, just testing 
             var tokenClient = new TokenClient("http://localhost:61294/connect/token", "mvc");
             var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);
         },
         SecurityTokenValidated = async n =>
         {
             var userInfoClient = new UserInfoClient(new Uri("http://localhost:61294/connect/userinfo"), n.ProtocolMessage.AccessToken);
             var userInfo = await userInfoClient.GetAsync();

             var nId = new ClaimsIdentity(
                               n.AuthenticationTicket.Identity.AuthenticationType,
                               ClaimTypes.GivenName,
                               ClaimTypes.Role);

             userInfo.Claims.ToList().ForEach(c => nId.AddClaim(new Claim(c.Item1, c.Item2)));

             nId.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

             nId.AddClaim(new Claim("Test", "test"));

             n.AuthenticationTicket = new AuthenticationTicket(nId, n.AuthenticationTicket.Properties);
             n.Request.Headers.SetValues("Authorization ", "Bearer ", n.ProtocolMessage.AccessToken);
         },
         SecurityTokenReceived = async n =>
         {
             Debug.WriteLine(n);
         }
     }
 });

我还使用了IdentityServer3.AccessTokenValidation包,并使用了工作正常的app.UseIdentityServerBearerTokenAuthentication ,我能够成功调用我的API,但是我看不到如何通过此方法应用自定义声明。

我是否使用针对Web API的app.UseOpenIdConnectAuthentication来解决此错误方法? 任何对此的指导将不胜感激。

好的,现在我明白了您的问题。 您发布的Startup.cs配置是客户端的启动,但是您试图在api资源中使用它。

api资源的启动看起来应该像这里的启动 (我正在为Identity server 3显示一个,因为我知道您的API是.Net Framework的)。 这就是为什么永远无法到达代码(您在注释中提到的原因)的原因。

老实说,我敢肯定,您无法实现目标-向api资源中的令牌添加自定义声明。 使api资源被消耗掉,并读取已经提供的声明(大多数时间基于声明对api进行授权)。

否则,您完成的所有其他操作都是正确的。 您应该对.Net Framework客户端和api使用IdentityServer3.AccessTokenValidation (没问题,令牌发行者是IDS4)。

这很可能是您收到401的原因。您没有正确设置api的权限。 我希望这个对你有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM