C# 无法从ADFS4-OAuth2 OpenID中的WebAPI获取用户名

C# 无法从ADFS4-OAuth2 OpenID中的WebAPI获取用户名,c#,oauth,adfs,C#,Oauth,Adfs,我正在尝试使用OAuth的ADFS身份验证在我的webapp和webapi之间进行通信。我正在使用ADFS4,并相应地使用服务器应用程序和Webapi配置了应用程序组。我试图从webapi控制器接收userdetails,特别是用户名。是否可以在传递给webapi的访问令牌中传递用户名详细信息。以下是我在Webapp方面所做的: 在adfs身份验证后的webapp控制器中 authContext = new AuthenticationContext(Startup.authority, fal

我正在尝试使用OAuth的ADFS身份验证在我的webapp和webapi之间进行通信。我正在使用ADFS4,并相应地使用服务器应用程序和Webapi配置了应用程序组。我试图从webapi控制器接收userdetails,特别是用户名。是否可以在传递给webapi的访问令牌中传递用户名详细信息。以下是我在Webapp方面所做的:

在adfs身份验证后的webapp控制器中

authContext = new AuthenticationContext(Startup.authority, false);
ClientCredential credential = new ClientCredential(Startup.clientId, Startup.appKey);
string accessToken = null; 
bool isAuthenticated = User.Identity.IsAuthenticated; //return true
string username = User.Identity.Name; // returns username
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value; // returns username

HttpClient httpClient = new HttpClient();
try
{
     result = authContext.AcquireTokenAsync(Startup.apiResourceId, credential).Result;
     accessToken = result.AccessToken;

}
catch (AdalException ex)
{
}

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

HttpResponseMessage response = httpClient.GetAsync(Startup.apiResourceId + "/api/ConfApi").Result;
从Webapi的末尾,在Startup.Auth.cs中,我添加了以下代码

public void ConfigureAuth(IAppBuilder app)
{
    JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
    app.UseActiveDirectoryFederationServicesBearerAuthentication(
        new ActiveDirectoryFederationServicesBearerAuthenticationOptions
        {
            MetadataEndpoint = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"],
            TokenValidationParameters = new TokenValidationParameters() {
                SaveSigninToken = true,
                ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
            }
        });
    }
但是,在ConfApi控制器中,我找不到任何包含用户详细信息的声明

如何在Webapi控制器中接收用户详细信息


谢谢你的帮助。

你真的收到索赔了吗

您是否在ADFS端为web API配置了索赔规则

您使用了什么名称-给定名称、显示名称等

使用类似Fiddler的工具来监控交通。在OIDC身份验证之后,您应该看到访问令牌、id令牌等

获取令牌并复制到jwt.io中

这将显示您实际收到的内容


但是,OWIN类将简单的OAuth属性(例如“aud”)转换为索赔类型URI(例如so断点),并查看索赔集合中的内容以及为每个索赔集合分配的类型。

对这一问题的回答与对以下问题的回答相同:

您必须使用授权代码流(而不是客户端凭据授予流)来让服务器应用程序(在本例中为web应用程序)使用用户上下文与web API对话。授权代码流将在JWT令牌中传递声明。只需确保在web API的RPT声明发布转换规则中传递web API所需的任何声明即可

为了使用授权代码流,您需要通过Startup.ConfigureAuth(IAppBuilder应用程序)中OpenIdConnectAuthenticationOptions上的通知来处理AuthorizationCodeReceived事件

app.UseOpenIdConnectAuthentication(
新的OpenIdConnectAuthenticationOptions{
...
通知=新的OpenIdConnectAuthenticationNotifications{
AuthorizationCodeReceived=异步代码=>{
ClientCredential=新的ClientCredential(Startup.clientId,Startup.appKey);
AuthenticationContext authContext=新的AuthenticationContext(Startup.authority,false);
AuthenticationResult=等待authContext.AcquireTokenByAuthorizationCodeAsync(
代码,代码,
新Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
资质
Startup.apiResourceId);
}
}
当您准备好拨打电话时,您将以静默方式获取令牌

var authContext=新的AuthenticationContext(Startup.authority,false);
var-credential=new-ClientCredential(Startup.clientId,Startup.appKey);
var claim=ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userId=新的UserIdentifier(声明,UserIdentifierType.UniqueId);
结果=等待authContext.AcquireTokenSilentAsync(
Startup.apiResourceId,
资质
用户ID);
HttpClient HttpClient=新HttpClient();
httpClient.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue(
“持票人”,
结果:AccessToken);