C# 如何在登录Web API C后端时获取用户电子邮件、姓名?

C# 如何在登录Web API C后端时获取用户电子邮件、姓名?,c#,authentication,asp.net-web-api,C#,Authentication,Asp.net Web Api,我想在登录时获得用户的电子邮件和姓名。我注意到,如果我创建一个自定义提供者,我可以看到这些信息 // WebApiConfig.cs options.LoginProviders.Remove(typeof(GoogleLoginProvider)); options.LoginProviders.Add(typeof(CustomGoogleLoginProvider)); public class CustomGoogleLoginProvider : GoogleLoginProvid

我想在登录时获得用户的电子邮件和姓名。我注意到,如果我创建一个自定义提供者,我可以看到这些信息

// WebApiConfig.cs
options.LoginProviders.Remove(typeof(GoogleLoginProvider));
options.LoginProviders.Add(typeof(CustomGoogleLoginProvider));


public class CustomGoogleLoginProvider : GoogleLoginProvider
{
    public CustomGoogleLoginProvider(HttpConfiguration config, IServiceTokenHandler tokenHandler)
        : base(config, tokenHandler)
    {

    }

    public override LoginResult CreateLoginResult(ClaimsIdentity claimsIdentity, string secretKey)
    {
        // name and email are on the ClaimsIdentity
        var result = base.CreateLoginResult(claimsIdentity, secretKey);
        return result;
    }
}
我可以在索赔标识上看到我想要的信息。但是如何在API方法中访问它们呢?如果我试图从用户那里得到声明,它们是不同的。这些声明是否返回到CreateLoginResult并存储在某处?或者我可以把它保存起来供以后使用吗

我认为它可能储存在外部身份中,对吗?如何访问它

我试过了

var owin = HttpContext.Current.GetOwinContext();
var auth = owin.Authentication;

var user = auth.User;
var identity = auth.User.Identity;

var externalIdentity = auth.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

但是externaldenity.Result返回空值。

我遇到的问题似乎是因为我假设声明是持久的。然而,REST服务似乎没有保持任何类型的开放会话,因此来自一个会话的所有值都不会出现在其他请求中

我要做的是将登录时的信息存储到数据库中,并在需要时通过用户id进行访问

为了实现这一点,我可以使用Authenticated方法获取我想要的所有外部值,并将其保存到数据库中

public class CustomGoogleLoginProvider : GoogleLoginProvider
{
    public CustomGoogleLoginProvider(HttpConfiguration config, IServiceTokenHandler tokenHandler)
        : base(config, tokenHandler)
    {

    }

    public override void ConfigureMiddleware(IAppBuilder appBuilder, ServiceSettingsDictionary settings)
    {
        var options = new GoogleOAuth2AuthenticationOptions
        {
            ClientId = settings["MS_GoogleClientID"],
            ClientSecret = settings["MS_GoogleClientSecret"],
            AuthenticationType = this.Name,
            Provider = new CustomGoogleLoginAuthenticationProvider()
        };

        appBuilder.UseGoogleAuthentication(options);
    }
}

public class CustomGoogleLoginAuthenticationProvider : GoogleLoginAuthenticationProvider
{
    public override Task Authenticated(GoogleOAuth2AuthenticatedContext context)
    {
        var result = base.Authenticated(context);

        var owin = HttpContext.Current.GetOwinContext();
        var auth = owin.Authentication;

        var identity = auth.User.Identity as ClaimsIdentity;

        //
        // store things I want in the database
        //

        return result;
    }
}