![](/img/trans.png)
[英]Using OWIN Identity v2 Claims to track custom properties in WebAPI2 app
[英]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.