Google登录Azure移动服务(.NET后端)后立即保存信息

问题描述:

我基本上想要做的是对Azure移动服务进行身份验证(使用Google或其他提供商),然后立即在服务器上保存一些用户信息(即电子邮件地址).

What I basically want to be able to do is authenticate to azure mobile services (using google or some other provider), and immediately save some of the user information (i.e. email address) on the server.

我知道我可以在身份验证后从应用程序调用自定义方法,但是我希望在服务器端通过google登录后可以直接使用此方法.

I know I could call a custom method from the app after authentication, but I was hoping to have some hook to do this straight after the google login on the server side.

这可能吗?我该怎么做?!

Is this possible? How do I do it?!

当前仅在.NET运行时中可行.如果使用Node运行时,则将无法执行此操作.

This is currently only possible in the .NET runtime. If using the Node runtime, you will not be able to do this.

对于.NET运行时,您需要创建一个继承自GoogleLoginProvider的类(我将其命名为CustomGoogleLoginProvider),然后您需要覆盖CreateCredentials方法:

For the .NET runtime, you would want to create a class which inherits from GoogleLoginProvider (I'll call mine CustomGoogleLoginProvider), and then you'll need to override the CreateCredentials method:

public override ProviderCredentials CreateCredentials(ClaimsIdentity claimsIdentity)
{
    // grab any information from claimsIdentity which you would like to store

    // If you need the access token for use with the graph APIs, you can use the following
    string providerAccessToken = claimsIdentity.GetClaimValueOrNull(ServiceClaimTypes.ProviderAccessToken);

    // use the access token with HttpClient to get graph information to store

    return base.CreateCredentials(claimsIdentity);
}

然后在创建options对象后立即在WebApiConfig.cs中将以下内容添加到Register()方法:

Then in your WebApiConfig.cs, add the following to the Register() method, immediately after the options object is created:

options.LoginProviders.Remove(typeof(GoogleLoginProvider));
options.LoginProviders.Add(typeof(CustomGoogleLoginProvider));

在创建移动服务令牌之前,将立即调用CreateCredentials()方法.至此,Google令牌已经过验证,并且Google寄回的任何邮件都填充了ClaimsIdentity.

The CreateCredentials() method gets called immediately before a Mobile Services token is created. At this point, the Google token has been validated, and the claimsIdentity has been populated with whatever Google sent back.

默认情况下,某些信息将在ClaimsIdentity中可用,但是您可能还会有一些信息,要求您致电给Google.仅当您设置正确的

Some information will be available in the claimsIdentity by default, but you may also have information which requires you to call through to Google. You can only do this if you set the proper scopes configured.

如果您确实想走自定义API路线,则只需要从控制器中进行调用即可:

If you did want to go the custom API route, you would just need to make a call from your controller:

ServiceUser user = (ServiceUser)this.User;
GoogleCredentials creds = (await user.GetIdentitiesAsync()).OfType<GoogleCredentials>().FirstOrDefault();
string accessToken = creds.AccessToken;

此处记录了getIdentities()的节点版本.

The Node version of getIdentities() is documented here.