我们有一个桌面应用程序,它使用adal来验证用户,使用以下代码:
AuthenticationResult result = null;
var context = new AuthenticationContext(aadTenantDomain);
result = await context.AcquireTokenAsync(resourceId, clientId, returnUrl, new PlatformParameters(PromptBehavior.Auto));
这很好用,返回的AuthenticationResult具有所有正确的用户信息。现在我们使用从AuthenticationResult获取的访问令牌调用在azure上托管的Web应用程序web api控制器:
var Client = new HttpClient();
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
其中也正确授权用户。现在在Web控制器中,我们使用User.Identity.Name来获取访问令牌授权的用户名。直到昨天很多个月才运行良好,但今天User.Identity.Name返回桌面应用程序的客户端ID而不是用户名。谁知道什么错了?
这是api身份验证配置:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
RoleClaimType = System.Security.Claims.ClaimTypes.Role,
}
});
}
这是一个示例控制器功能:
[Authorize]
public class dialplanController : ApiController
{
public async Task<IHttpActionResult> GetMe()
{
var Me = db.dialplan.FirstOrDefault(d => d.email == User.Identity.Name);
return Ok(Me);
}
}
答案 0 :(得分:1)
如果您希望Web应用程序同时支持OpenIdConnection和Windows Azure Active Directory承载令牌,则需要将代码app.UseWindowsAzureActiveDirectoryBearerAuthentication()
添加为juunas。
例如,以下是供您参考的代码:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = redirectUri,
RedirectUri = redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
//
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
//
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed,
RedirectToIdentityProvider= OnRedirectToIdentityProvider,
MessageReceived= OnMessageReceived,
SecurityTokenReceived= OnSecurityTokenReceived,
},
});
app.UseWindowsAzureActiveDirectoryBearerAuthentication(new Microsoft.Owin.Security.ActiveDirectory.WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = "",
Tenant = "",
});
}
之后,我们可以使用Azure AD中的令牌获取来调用Web API。 Azure Active Directory OWIN组件将根据access_token中的User.Identity.Name
声明从委托令牌转换unique_name
。
请从this site解码访问令牌,看看是否需要unique_name
。
答案 1 :(得分:0)
使用ClaimsPrincipal.Current?.FindFirst(ClaimTypes.Upn)?. Value返回当前用户的正确UPN,如果没有给出upn,则返回null。