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

后端 未结 2 462
执笔经年
执笔经年 2021-01-06 11:56

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

相关标签:
2条回答
  • 2021-01-06 12:43

    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

    0 讨论(0)
  • 2021-01-06 12:48

    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"]);
    
    0 讨论(0)
提交回复
热议问题