#.net #azure #oauth #owin #azure-app-service-envrmnt
#.net #azure #oauth #owin #azure-app-service-envrmnt
Вопрос:
Я только что обновил свое старое приложение Azure mobile services, в котором были другие методы аутентификации, отличные от facebook, Google, Twitter и т. Д..
Я думаю, что это owin 2.01.
Они выглядели так :
Так реализовала Microsoft.WindowsAzure.Мобильный.Обслуживание.Безопасность.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?
Я использую некоторые библиотеки и дополнительные вещи, добавленные здесь, но я не могу найти никаких документов где угодно (было бы полезно просто узнать, где находятся документы):
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:
Если я вас правильно понял, я предполагаю, что вы предоставляете три метода (Facebook, Instagram, Twitter) для аутентификации. И вы самостоятельно внедрили LoginProvider для Instagram в своем старом приложении Azure mobile services.
Из проверки подлинности и авторизации в службе приложений Azure мы можем обнаружить, что:
Служба приложений поддерживает пять поставщиков удостоверений из коробки: Azure Active Directory, Facebook, Google, учетная запись Microsoft и Twitter. Чтобы расширить встроенную поддержку, вы можете интегрировать другого поставщика удостоверений или собственное пользовательское решение для идентификации.
Для использования IAppBuilder.UseAppServiceAuthentication
вы можете попробовать следовать этому официальному руководству и этому образцу azure-mobile-apps-net-server.
Комментарии:
1. Да, вы правильно поняли, созданное мной приложение собирает каналы из Twitter, facebook, Instagram и некоторых других. из этих каналов ранее пользователь мог входить в систему (и сохранять токены), чтобы пользователь мог взаимодействовать с каждым каналом, используя их различные API. Я следовал предложенному вами руководству по внедрению пользовательской аутентификации для самостоятельного входа в приложение, но не могу заставить instagram работать вообще, используя библиотеки owin.security.instgram, как и раньше: (