Azure App Service Owin Instagram和其他Auth提供商

时间:2016-10-18 10:44:29

标签: .net azure oauth owin azure-app-service-envrmnt

我刚刚升级了我的旧Azure移动服务应用程序,该应用程序除了facebook,google,twitter等之外还有各种其他身份验证方法。

我认为它欠2.01。

他们看起来像这样:

所以实现了Microsoft.WindowsAzure.Mobile.Service.Security.LoginProvider:

 public static class WebApiConfig
{
    public static void Register()
    {
        // Use this class to set configuration options for your mobile service
        ConfigOptions options = new ConfigOptions();
        options.PushAuthorization = AuthorizationLevel.User;
        options.LoginProviders.Add(typeof(FacebookLoginProvider));
        options.LoginProviders.Add(typeof(InstaLoginProvider));
        options.LoginProviders.Add(typeof(TwitterLoginProvider));

        // Use this class to set WebAPI configuration options
        HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));

        // Set default and null value handling to "Include" for Json Serializer
        config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
        config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Include;

        Database.SetInitializer(new app_name_mobile_appInitializer());
    }

}

提供商实施:

using System;
using System.Security.Claims;
using System.Threading.Tasks;
using app_name_mobile_appService.DataObjects;
using app_name_mobile_appService.Models;
using Microsoft.WindowsAzure.Mobile.Service;
using Microsoft.WindowsAzure.Mobile.Service.Security;
using Newtonsoft.Json.Linq;
using Owin;
using Owin.Security.Providers.Instagram;
using System.Linq;

namespace app_name_mobile_appService.Auth.ExtraLogins.Instagram
{
    public class InstaLoginProvider : LoginProvider
    {
        internal const string ProviderName = "Instagram";

        public InstaLoginProvider(IServiceTokenHandler tokenHandler)
            : base(tokenHandler)
        {
        }

        public override string Name
        {
            get { return ProviderName; }
        }

        public override void ConfigureMiddleware(IAppBuilder appBuilder,
            ServiceSettingsDictionary settings)
        {
            InstagramAuthenticationOptions options = new InstagramAuthenticationOptions()
            {
                ClientId = settings["InstagramClientId"],
                ClientSecret = settings["InstagramClientSecret"],
                AuthenticationType = this.Name,
                Provider = new InstaLoginAuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        ben_coomber_mobile_appContext mainContext = new app_name_mobile_appContext();

                        Account account = mainContext.Accounts.SingleOrDefault(a => a.UserIdWithProvider == context.Id);

                        if (account == null)
                        {
                            Account newAccount = new Account
                            {
                                Id = Guid.NewGuid().ToString(),
                                Username = context.UserName,
                                InstagramToken = context.AccessToken,
                                UserIdWithProvider = context.Id,
                                ProviderType = "instagram"
                            };
                            mainContext.Accounts.Add(newAccount);
                            mainContext.SaveChanges();
                        }
                        return Task.FromResult(0);
                    }
                }
            };
            options.Scope.Add("likes");
            options.Scope.Add("comments");
            appBuilder.UseInstagramInAuthentication(options);
        }

        public override ProviderCredentials CreateCredentials(
            ClaimsIdentity claimsIdentity)
        {
            Claim name = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
            Claim providerAccessToken = claimsIdentity
                .FindFirst(ServiceClaimTypes.ProviderAccessToken);

            InstaCredentials credentials = new InstaCredentials()
            {
                UserId = this.TokenHandler.CreateUserId(this.Name, name != null ?
                    name.Value : null),
                AccessToken = providerAccessToken != null ?
                    providerAccessToken.Value : null
            };

            return credentials;
        }

        public override ProviderCredentials ParseCredentials(JObject serialized)
        {
            return serialized.ToObject<InstaCredentials>();
        }
    }
}

InstagramAuthenticationProvider实施:

 using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Mobile.Service.Security;
using Owin.Security.Providers.Instagram.Provider;

namespace app_name_mobile_appService.Auth.ExtraLogins.Instagram
{
    public class InstaLoginAuthenticationProvider :InstagramAuthenticationProvider
    {
        public override Task Authenticated(InstagramAuthenticatedContext context)
        {
            context.Identity.AddClaim(
                new Claim(ServiceClaimTypes.ProviderAccessToken, context.AccessToken));
            return base.Authenticated(context);
        }
    }
}

ProviderCredentials实施:

using Microsoft.WindowsAzure.Mobile.Service.Security;

namespace app_name_mobile_appService.Auth.ExtraLogins.Instagram
{
    public class InstaCredentials : ProviderCredentials
    {
        public InstaCredentials()
            : base(InstaLoginProvider.ProviderName)
        {
        }

        public string AccessToken { get; set; }
    }
}

那么使用Azure App Service中较新的东西来做到这一点的正确方法是什么?

我在这里添加了一些libs和额外的东西,但我无法找到任何文档(如果知道文档在哪里会有帮助):

using System.Web.Http;
using Microsoft.Azure.Mobile.Server.Authentication;
using Microsoft.Azure.Mobile.Server.Config;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(ben_coomber_mobile_appService.OwinStartUp))]

namespace app_name_mobile_appService
{
    public class OwinStartUp
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            HttpConfiguration config = new HttpConfiguration();
            new MobileAppConfiguration()
                .UseDefaultConfiguration()
            .ApplyTo(config);

            app.UseWebApi(config);

            AppServiceAuthenticationOptions options = new AppServiceAuthenticationOptions();

            app.UseAppServiceAuthentication(options);
        }
    }
}

任何帮助表示感谢谢谢:)

1 个答案:

答案 0 :(得分:0)

如果我理解正确,我假设您提供三种方法(Facebook,Instagram,Twitter)进行身份验证。您已经在旧的Azure移动服务应用程序中自己实现了LoginProvider for Instagram。

Authentication and authorization in Azure App Service,我们可以找到:

  

App Service支持五个开箱即用的身份提供商:Azure Active Directory,Facebook,Google,Microsoft帐户和Twitter。要扩展内置支持,您可以集成另一个身份提供者或your own custom identity solution

要使用IAppBuilder.UseAppServiceAuthentication,您可以尝试关注此官方tutorial和此示例azure-mobile-apps-net-server