![](/img/trans.png)
[英]ASP.NET Core Access User.Identity in Controller Constructor
[英]ASP.NET WebApi User.Identity returns null
因此,我一直在尝试在ASP.NET WebApi 2应用程序中实现使用Facebook登录的功能。
但是由于某种原因,当我尝试验证匿名请求时:
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
User
为空。
我已经在web.config
上将身份验证模式设置为None
。
Web.config文件:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<customErrors mode="Off" />
</system.web>
另外,这是我在Startup.cs类中为OAuth配置管道的方式:
public void ConfigureOAuth(IAppBuilder app) {
app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
facebookAuthOptions = new FacebookAuthenticationOptions() {
AppId = "xxxxx",
AppSecret = "xxxxxxxxxxx",
Provider = new FacebookAuthProvider()
};
app.UseFacebookAuthentication(facebookAuthOptions);
}
这就是我得到控制器的方式:
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
[HttpGet]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null) {
string redirectUri = string.Empty;
// HERE: User is always null.
if (!User.Identity.IsAuthenticated) {
return new ChallengeResult(provider, this);
}
// Rest of the code removed for brevity...
}
据我所知, User.Identity
应该在cookie中包含登录提供程序返回的数据/声明,但是User返回null; 因此,挑战不会触发。
您需要为用户设置ClaimsPrinicpal并在控制器中使用“ AuthorizeToken”。 这基本上是在您获得令牌后设置的。 完整的机制由Owin Pipeline控制。
您需要获取Owin上下文并取消保护令牌并将其分配给“ AuthenticationTicket”。 (AuthenticationTicket是“ Microsoft.Owin.Security”中的类)
public class AuthorizeTokenAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
SetUserContext(actionContext.Request.GetOwinContext()
}
private bool SetUserIdentity(IOwinContext context)
{
AuthenticationTicket authenticationTicket =
Startup.OAuthBearerAuthenticationOptions.AccessTokenFormat.Unprotect(token);
context.Authentication.User = new System.Security.Claims.ClaimsPrincipal();
context.Authentication.User.AddIdentity(authenticationTicket.Identity);
}
}
通过上述方式为“用户”分配值后,您将不会获得“用户”为空值,并且在分配了身份后也可以获取身份。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.