How to Use Sina Weibo account for application login verification (Integrated login verification based on Windows Azure Mobile Service), azuremobile

Source: Internet
Author: User

How to Use Sina Weibo account for application login verification (Integrated login verification based on Windows Azure Mobile Service), azuremobile

Using a third-party account to log on to the application is nothing new, but why do you need to talk about this topic here today, the reason is simple: Windows Azure Mobiles Service Authentication allows you to easily integrate this feature into your application.

I have previously introduced the Mobile Service push function. Its advantage is that it can easily push message notifications (Windows, IOS, and Android) to different platform devices without worrying about server overload. However, Authentication Based on Windows Azure Mobile Service still retains this advantage, which allows developers to configure third-party logon on clients of different platforms, after the efforts of Sina's colleagues, we finally integrated with Windows Azure Mobile Service and became the first provider in China to support Mobile Service third-party login authentication.

Today, I will introduce how to use Mobile Service for Logon verification. First, since we use Sina Weibo as the third-party login portal for applications, we must first register our applications on Sina Weibo.

Open Weibo Open Platform website http://open.weibo.com/, log on to your Weibo account, or register Weibo Open Platform account. Click "micro-link"-"create application"-"mobile application"

Micro Link

The App Key and App Secret strings are very important and need to be used to identify Applications When configuring Mobile Service.

. Net we can choose to create a database or load it to an existing database.

Note: At this time, it is possible that VS will automatically download and use the DLL for a while.

The App Key and App Secret are as follows:

    <!-- SinaWeibo App ClientID/ClientSecret-->    <add key="SinaWeiBoClientId" value="ClientID"/>    <add key="SinaWeiBoClientSecret" value="ClientSecret"/>

Next, we will add two classes SinaWeiboLoginAuthenticationProvider and SinaWeiboLoginProvider on the server:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using Owin;using Microsoft.Owin.Security.SinaWeibo;using Microsoft.Owin.Security.SinaWeibo.Provider;using System.Threading.Tasks;using System.Security.Claims;using Microsoft.WindowsAzure.Mobile.Service.Security;namespace WangBoAuthenticationSinaLoginService{    public class SinaWeiboLoginAuthenticationProvider : SinaWeiboAccountAuthenticationProvider //SinaWeiBoAuthenticationProvider    {        public override Task Authenticated(SinaWeiboAccountAuthenticatedContext context)        {            context.Identity.AddClaim(                new Claim(ServiceClaimTypes.ProviderAccessToken, context.AccessToken));            return base.Authenticated(context);        }    }}

SinaWeiboLoginProvider code

using System;using System.Collections.Generic;using System.Linq;using System.Web;using Owin;using Microsoft.Owin.Security.SinaWeibo;using Microsoft.Owin.Security.SinaWeibo.Provider;using System.Threading.Tasks;using System.Security.Claims;using Microsoft.WindowsAzure.Mobile.Service.Security;namespace WangBoAuthenticationSinaLoginService{    public class SinaWeiboLoginProvider : LoginProvider    {        internal const string ProviderName = "SinaWeibo";        public SinaWeiboLoginProvider(IServiceTokenHandler tokenHandler)            : base(tokenHandler)        {        }        public override void ConfigureMiddleware(IAppBuilder appBuilder,            Microsoft.WindowsAzure.Mobile.Service.ServiceSettingsDictionary settings)        {            SinaWeiboAccountAuthenticationOptions options = new SinaWeiboAccountAuthenticationOptions            {                AppId = settings["SinaWeiBoClientId"],                AppSecret = settings["SinaWeiBoClientSecret"],                AuthenticationType = this.Name,                Provider = new SinaWeiboAccountAuthenticationProvider()            };            appBuilder.UseSinaWeiboAuthentication(options);        }        public override ProviderCredentials CreateCredentials(ClaimsIdentity claimsIdentity)        {            Claim name = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);            Claim providerAccessToken = claimsIdentity                .FindFirst(ServiceClaimTypes.ProviderAccessToken);            SinaWeiboCredentials credentials = new SinaWeiboCredentials            {                UserId = this.TokenHandler.CreateUserId(this.Name, name != null ? name.Value : null),                AccessToken = providerAccessToken != null ? providerAccessToken.Value : null            };            return credentials;        }        public override string Name        {            get { return ProviderName; }        }        public override ProviderCredentials ParseCredentials(Newtonsoft.Json.Linq.JObject serialized)        {            return serialized.ToObject<SinaWeiboCredentials>();        }        public class SinaWeiboCredentials : ProviderCredentials        {            public SinaWeiboCredentials()                : base(SinaWeiboLoginProvider.ProviderName)            {            }            public string AccessToken { get; set; }        }    }}

Another important step is to register the Sina login API in the WebApiConfig registration method.

public static class WebApiConfig    {        public static void Register()        {            // Use this class to set configuration options for your mobile service            ConfigOptions options = new ConfigOptions();            options.LoginProviders.Add(typeof(SinaWeiboLoginProvider));            // Use this class to set WebAPI configuration options            HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));            // To display errors in the browser during development, uncomment the following            // line. Comment it out again when you deploy your service for production use.            // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;                        Database.SetInitializer(new WangBoAuthenticationSinaLoginInitializer());        }    }

The next step is to deploy our Mobile Service code, right-click the project site to publish

Replace it with your own]

Https: // Protocol example:

Https://wangboauthenticationsinalogin.azure-mobile.net/signin-sinaWeibo [where wangboauthenticationsinalogin.azure-mobile.net is the name of my service, here you need to replace it with your own]

App. xaml. cs comment out local debugging code using remote server address

// This MobileServiceClient has been configured to communicate with your local // test project for debugging purposes. // public static MobileServiceClient MobileService = new MobileServiceClient (// "http: // localhost: 58974 "//); // This MobileServiceClient has been configured to communicate with your Mobile Service's url // and application key. you're all set to start working with your Mobile Servi Ce! Public static MobileServiceClient MobileService = new MobileServiceClient ("https://wangboauthenticationsinalogin.azure-mobile.net/", "password written here ");

Then open MainPage and add a verification function AuthenticateAsync.

        private async Task AuthenticateAsync()        {            Microsoft.WindowsAzure.MobileServices.MobileServiceUser user = null;            string message;            try            {                user = await App.MobileService.LoginAsync("sinaweibo");                message = string.Format("You are now logged in - {0}", user.UserId + user.MobileServiceAuthenticationToken);            }            catch (InvalidOperationException ex)            {                string exm = ex.Message;                message = "You must log in. Login Required";            }            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>           {               var dialog = new MessageDialog(message);               dialog.Commands.Add(new UICommand("OK"));               dialog.ShowAsync();           });        }

Then we need to add a login button on the client UI, open the Windows8.1 project, find MainPage. xaml add Registration button (add login directly under the refresh button)

<Button Margin="72,0,0,0" Name="ButtonRefresh" Click="ButtonRefresh_Click">Refresh</Button><Button Margin="72,0,0,0" x:Name="ButtonLogin" Click="ButtonLogin_Click" Content="Login"/>

Add the event processing function to the MainPage. xaml. cs code file in the share project.

private async void ButtonLogin_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)        {            await AuthenticateAsync();        }

Finally, because the application will automatically switch to the background during WindowsPhone verification, we need to handle the OnActivated event.

protected override void OnActivated(IActivatedEventArgs args)        {            base.OnActivated(args);#if WINDOWS_PHONE_APP            if (args.Kind == ActivationKind.WebAuthenticationBrokerContinuation)            {                App.MobileService.LoginComplete(args as WebAuthenticationBrokerContinuationEventArgs);            }#endif        }

Run the debugging program directly with F5. The following shows the running effect.

Windows 8.1 Certification Process

The Token is obtained after logon.

 

WindowsPhone 8.1 Certification Process

The Token is obtained after logon.

I hope that the summary will help you, and you are welcome to communicate with me or @ Wang Bo _ Nick on Sina Weibo.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.