Get user info like name, email Id etc from authentication token in .NET Backend Azure Mobile Service

回眸只為那壹抹淺笑 提交于 2019-12-09 00:49:57

问题


I am using Azure Mobile Service to add authentication to my Windows Store app. Following this article from Mobile Services documentation I am able to get the UserId as well as MobileServiceAuthenticationToken (both for Google as well as Microsoft Account)

My question is how do I get user info like name, email Id etc. using MobileServiceAuthenticationToken in a .NET backend mobile service. I have gone through various articles explaining how this is done in Javascript Backend mobile service but couldn't find anything properly implemented in C# + .NET backend mobile service.

Any pointers appreciated.

Thanks


回答1:


Facebook, Google doesn't return you user profile name, e-mail when authorizing. They are giving you access token that can be used for future requests.

You need to request for example to Facebook Graph API for name, email with your MobileServiceAuthenticationToken.

You can use this library for accessing to Facebook API: https://facebookgraphapi.codeplex.com/

// MobileServiceAuthenticationToken <- your token
var facebook = new FacebookGraphAPI(MobileServiceAuthenticationToken);

// Get user profile data 
var user = facebook.GetObject("me", null);
Console.WriteLine(user["name"]);



回答2:


For getting user info using authentication token from .Net Backend Azure Mobile Service:

  1. Setup your mobile service with authentication for different providers by visiting this link - I did this for Microsoft, Google and Facebook.
  2. Add a new controller to the mobile service and add the following code:

public class UserInfoController : ApiController { public ApiServices Services { get; set; }

    [AuthorizeLevel(AuthorizationLevel.User)]
    public async Task<JObject> GetUserInfo()
    {
        //Get the current logged in user
        ServiceUser user = this.User as ServiceUser;
        if (user == null)
        {
            throw new InvalidOperationException("This can only be called by authenticated clients");
        }

        //Get Identity Information for the current logged in user
        var identities = await user.GetIdentitiesAsync();
        var result = new JObject();

        //Check if the user has logged in using Facebook as Identity provider
        var fb = identities.OfType<FacebookCredentials>().FirstOrDefault();
        if (fb != null)
        {
            var accessToken = fb.AccessToken;
            result.Add("facebook", await GetProviderInfo("https://graph.facebook.com/me?access_token=" + accessToken));
        }

        //Check if the user has logged in using Microsoft Identity provider
        var ms = identities.OfType<MicrosoftAccountCredentials>().FirstOrDefault();
        if (ms != null)
        {
            var accessToken = ms.AccessToken;
            result.Add("microsoft", await GetProviderInfo("https://apis.live.net/v5.0/me/?method=GET&access_token=" + accessToken));
        }

        //Check if the user has logged in using Google as Identity provider
        var google = identities.OfType<GoogleCredentials>().FirstOrDefault();
        if (google != null)
        {
            var accessToken = google.AccessToken;
            result.Add("google", await GetProviderInfo("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken));
        }

        return result;
    }

    private async Task<JToken> GetProviderInfo(string url)
    {
        var c = new HttpClient();
        var resp = await c.GetAsync(url);
        resp.EnsureSuccessStatusCode();
        return JToken.Parse(await resp.Content.ReadAsStringAsync());
    }
}

Once done publish the mobile service. The above code gets the identity information for the current logged in user and then depending upon which authentication provider user has chosen (Microsoft, Facebook or Google) it makes a call to that identity provider's user profile API and gets the user information.

  1. Add the following code in the client application to make a call to GetUserInfo method in mobile service:
var user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);                  
var userInfo = await App.MobileService.InvokeApiAsync("userInfo", HttpMethod.Get, null);

However this will bring only some basic user information like name, gender etc. if your application requires more than that you can request additional scopes during the login, by setting the MS_FacebookScope and MS_MicrosoftScope app settings in mobile service Configure Tab in azure portal.

You can get more detailed information on this from this excellent article



来源:https://stackoverflow.com/questions/32390377/get-user-info-like-name-email-id-etc-from-authentication-token-in-net-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!