简体   繁体   English

具有ASP.NET身份的Azure移动应用

[英]Azure Mobile App with ASP.NET Identity

My cenario is: I already have implemented an ASP.NET WebAPI app with Identity and Register/Login actions. 我的情况是:我已经实现了带有Identity和Register / Login操作的ASP.NET WebAPI应用程序。 This is My ApiAccountController: 这是我的ApiAccountController:

    [Authorize]
    [RoutePrefix("api/Account")]
    public class ApiAccountController : ApiController
    {
        private const string LocalLoginProvider = "Local";
        private ApplicationUserManager _userManager;

        public ApiAccountController()
        {
        }

        public ApiAccountController(ApplicationUserManager userManager,
            ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
        {
            UserManager = userManager;
            AccessTokenFormat = accessTokenFormat;
        }

        public ApplicationUserManager UserManager
        {
            get { return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
            private set { _userManager = value; }
        }

        public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; }

        // POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid) return BadRequest(ModelState);
            var user = new ApplicationUser
            {
                Name = model.Nome,
                UserName = model.Email,
                Email = model.Email,
                CidadeId = model.CidadeId
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            //return !result.Succeeded ? GetErrorResult(result) : Ok();
            if (result.Succeeded)
            {
                var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code }));
                await
                    UserManager.SendEmailAsync(user.Id, "Confirme Sua Conta",
                        "Para confirmar sua conta, clique <a href=\"" + callbackUrl + "\">Aqui!</a>");
                // Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));
                return Ok();
            }
            return GetErrorResult(result);
        }

        [HttpGet]
        [AllowAnonymous]
        [Route("ConfirmEmail", Name = "ConfirmEmailRoute")]
        public async Task<IHttpActionResult> ConfirmEmail(Guid userId, string code)
        {
            if (string.IsNullOrEmpty(userId.ToString()) || string.IsNullOrWhiteSpace(code))
            {
                ModelState.AddModelError("", "Códigos necessários");
                return BadRequest(ModelState);
            }

            var result = await UserManager.ConfirmEmailAsync(userId, code);

            if (result.Succeeded)
                return Ok("Conta confirmada! Obrigado pela preferência, agora você pode utilizar nosso novo app");
            return GetErrorResult(result);
        }

        [HttpPost]
        [AllowAnonymous]
        [Route("Login")]
        public async Task<IHttpActionResult> Login(LoginUserViewModel model)
        {
            var request = HttpContext.Current.Request;
            var tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "/Token";
            using (var client = new HttpClient())
            {
                var requestParams = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("grant_type", "password"),
                    new KeyValuePair<string, string>("username", model.Username),
                    new KeyValuePair<string, string>("password", model.Password)
                };
                var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
                var tokenServiceResponse = await client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded);
                var responseString = await tokenServiceResponse.Content.ReadAsStringAsync();
                if (tokenServiceResponse.StatusCode != HttpStatusCode.OK) return BadRequest();
                using (var tx = new TransactionScope(TransactionScopeOption.Required,
                    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },
                    TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var user = UserManager.FindByName(model.Username);
                        if (user == null) return NotFound();
                        if (!user.EmailConfirmed) return BadRequest();
                        var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString);
                        user.AccessToken = json["access_token"];
                        UserManager.Update(user);
                        tx.Complete();
                        var vm = user.Adapt<UserLoggedViewModel>();
                        return Ok(vm);
                    }
                    catch
                    {
                        tx.Dispose();
                        throw;
                    }
                }
            }
        }


        // POST api/Account/Logout
        [Route("Logout")]
        public IHttpActionResult Logout()
        {
            Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
            return Ok();
        }

// Some actions was removed
        #region Helpers

        private IAuthenticationManager Authentication
        {
            get { return Request.GetOwinContext().Authentication; }
        }

        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
                return InternalServerError();

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                    foreach (var error in result.Errors)
                        ModelState.AddModelError("", error);

                if (ModelState.IsValid)
                    return BadRequest();

                return BadRequest(ModelState);
            }

            return null;
        }

        #endregion
    }

This is my Start.Auth configuration 这是我的Start.Auth配置

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static string PublicClientId { get; private set; }

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity =
                    SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, Guid>(
                        TimeSpan.FromMinutes(30),
                        (manager, user) =>
                            user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie),
                        id => Guid.Parse(id.GetUserId()))
            }
        });

        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
            RefreshTokenProvider = new RefreshTokenProvider(),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);

        //var options = new AppServiceAuthenticationOptions()
        //{
        //    SigningKey = ConfigurationManager.AppSettings["SigningKey"],
        //    ValidAudiences = new[] {ConfigurationManager.AppSettings["ValidAudience"]},
        //    ValidIssuers = new[] {ConfigurationManager.AppSettings["ValidIssuer"]},
        //    TokenHandler = WebApiConfig.Configuration.GetAppServiceTokenHandler()
        //};

        //app.UseAppServiceAuthentication(options);

    }
}

The WebAPIConfig WebAPIConfig

  public static class WebApiConfig
{
    //public static HttpConfiguration Configuration { get; private set; }
    public static void Register(HttpConfiguration config)
    {
        //Configuration = config;
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            new {id = RouteParameter.Optional}
        );

        var container = LightInjectContainer.Register();
        container.RegisterApiControllers();
        container.EnableWebApi(config);

        MapsterConfig.RegisterMappings();

       // Database.SetInitializer<SolumDbContext>(null);

       // new MobileAppConfiguration()
       //     .UseDefaultConfiguration()
       //     .ApplyTo(config);

    }
}

This is totally functional and I use this with my mobile app. 这完全可以正常工作,我可以在移动应用程序中使用它。 But, I want to use the azure offline sync with per-user data sync. 但是,我想将天蓝色的脱机同步与每个用户的数据同步一起使用。 Reading some articles on Google, no one say exactly how to use Identity on Mobile Apps. 在Google上阅读了一些文章,没有人确切说明如何在移动应用上使用身份。 All articles says to read the Microsoft Documentation of how to configure custom login provider, but neither they explain how to configure this exactly. 所有文章都说要阅读Microsoft文档中有关如何配置自定义登录提供程序的内容,但都没有解释如何完全配置此内容。 I already read some posts here. 我已经在这里阅读了一些帖子。 Some people have the same problem I have and no one has the solution, a real example of how to use this or I not found this. 有些人有我遇到的相同问题,没有人有解决方案,这是如何使用此解决方案的真实示例,或者我找不到。

For clear, I want to use my Identity configuration with Azure Mobile App and sync per-user data with the azure offline sync funcionalities. 为了明确起见,我想将我的身份配置与Azure移动应用程序一起使用,并使用天蓝色的离线同步功能同步每个用户的数据。

Someone can help me about this? 有人可以帮我吗?

I really thank! 我真的很感谢!

您需要阅读我的书的第2章-http://aka.ms/zumobook

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure移动服务和Asp.net身份体系结构 - Azure Mobile Services and Asp.net Identity Architecture 在 Azure Functions 中使用 ASP.NET 标识 - Using ASP.NET Identity in Azure Functions 将ASP.NET身份连接到SQL Azure - Connecting asp.net Identity to SQL Azure 如何将 Blazor Web 程序集与 ASP.NET 核心托管和身份验证应用程序发布到 ZCF04A02E37B774FC3917A 服务? - How to publish Blazor Web assembly with ASP.NET core hosting and identity auth app to azure App Service? Azure移动服务自定义身份验证与ASP网络网站身份集成在一起 - Azure mobile services custom authentication intergated with asp net website identity 如何将Asp.Net身份与Azure AD授权结合在一起 - How to combine Asp.Net Identity with Azure AD Authorization 使用 ASP.NET 标识和 JWT 令牌的 Azure 函数身份验证 - Azure functions authentication with ASP.NET Identity and JWT token Asp.net Identity使用密码和Azure Active Directory身份验证 - Asp.net Identity using password and Azure Active Directory authentication 如何将ASP.NET身份连接到SQL Azure - How to connect asp.net Identity to SQL Azure 使用 asp.net Identity 进行 Azure AD 身份验证以进行授权 - Azure AD authentication with asp.net Identity for authorisation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM