我需要从用户索赔中获得一些信息。 我的控制器方法中有这个
var MyClaimsPrincipal = (ClaimsPrincipal)System.Web.HttpContext.Current.User;
但它总是返回空
这是我的Startup.Auth
班
奇怪的是,此代码之前曾被使用过,声明已由令牌声明填充,突然间这不起作用。
任何建议都值得赞赏
我已经重新检查,并且应用程序ID是正确的,自定义策略名称是正确的。
这是Startup.Auth class
public partial class Startup
{
// These values are pulled from web.config
public static string AadInstance = ConfigurationManager.AppSettings["ida:AadInstance"];
public static string Tenant = ConfigurationManager.AppSettings["ida:Tenant"];
public static string ClientId = ConfigurationManager.AppSettings["ida:ClientId"];
public static string SignUpSignInPolicy = ConfigurationManager.AppSettings["ida:SignUpSignInPolicyId"];
public static string DefaultPolicy = SignUpSignInPolicy;
/*
* Configure the authorization OWIN middleware
*/
public void ConfigureAuth(IAppBuilder app)
{
TokenValidationParameters tvps = new TokenValidationParameters
{
// Accept only those tokens where the audience of the token is equal to the client ID of this app
ValidAudience = ClientId,
AuthenticationType = Startup.DefaultPolicy,
NameClaimType = "http://schemas.microsoft.com/identity/claims/objectidentifier",
ValidIssuer = "http://schemas.microsoft.com/identity/claims/iss"
};
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
// This SecurityTokenProvider fetches the Azure AD B2C metadata & signing keys from the OpenIDConnect metadata endpoint
AccessTokenFormat = new JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider(String.Format(AadInstance, Tenant, DefaultPolicy)))
});
}
}
我在前端部分使用此配置:
clientID: 'id',
authority: "https://login.microsoftonline.com/tfp/tenantname.onmicrosoft.com/B2C_1A_SignUpOrSignInWithAAD/v2.0/",
scopes: ["openid"],
这在API中
<add key="ida:AadInstance" value="https://login.microsoftonline.com/{0}/v2.0/.well-known/openid-configuration?p={1}" />
<add key="ida:Tenant" value="tenantname.onmicrosoft.com" />
<add key="ida:ClientId" value="id" />
<add key="ida:SignUpSignInPolicyId" value="B2C_1A_SignUpOrSignInWithAAD" />
答案 0 :(得分:0)
尝试替换此代码
var MyClaimsPrincipal = (ClaimsPrincipal)System.Web.HttpContext.Current.User;
带有这样的内容
var currentClaimsPrincipal = ClaimsPrincipal.Current;
if( currentClaimsPrincipal != null && currentClaimsPrincipal.Claims != null)
{
var myClaimsPrincipal = new ClaimsIdentity(currentClaimsPrincipal.Claims);
}
或者,如果您不想实例化新的ClaimsIdentity,只需使用ClaimsPrincipal.Current
var MyClaimsPrincipal = ClaimsPrincipal.Current;
在GitHub上有很好的参考:
Home Controller for Azure Active Directory Sample
ClaimsIdentity claimsId = ClaimsPrincipal.Current.Identity as ClaimsIdentity;