【问题标题】:ASP.NET Web API social authentication for Web and Mobile适用于 Web 和移动设备的 ASP.NET Web API 社交身份验证
【发布时间】:2015-08-07 06:38:27
【问题描述】:

我的问题有点复杂,所以请耐心等待,因为我会尝试很好地阐述我正在努力解决的问题。

目标

拥有一个允许用户通过用户名/密码或社交(Facebook、Twitter、谷歌等)注册和登录的 ASP.NET 网站,该网站也有一个 API。此 API 需要使用 [Authorize] 锁定。 API 需要能够被可通过用户名/密码或社交(Facebook、Twitter、Google 等)登录的移动客户端(Android、iOS 等)访问。

背景

因此,我创建的网站可以完成我的目标中的一两件事,但不能同时完成。网上有很多很好的示例,并且在 VS 项目中内置了示例,展示了如何让用户通过社交应用注册和登录,但它们仅适用于网站,不适用于移动设备。我做了一个网站,Android 应用程序使用用户名/密码通过该 API 进行身份验证,但没有使用 OAuth 或社交凭据。

我开始使用此 page 作为参考,但我不知道如何将其用于我的网站登录和我的移动应用登录。

This guy 听起来很简单,但没有显示任何代码。

问题

是否有可以让我实现目标的教程或 GitHub 示例?我基本上想要一个网站,人们可以在其中注册用户名/密码或使用他们的社交帐户,并让用户通过移动设备执行相同操作(注册和登录)。移动设备基本上只使用 API 来推送/拉取数据,但我不确定如何将社交登录与我的 API 结合起来。我假设我需要使用 OAuth 并走这条路,但我找不到任何好的例子来展示如何为网络和移动设备做到这一点。

或者也许正确的解决方案是让网页全部是 cookie 身份验证,API 是一个单独的“网站”并且都是令牌身份验证,并且它们都绑定到同一个数据库?

【问题讨论】:

  • 如果可能的话,请您使用工作项目创建一个 github 项目。提前致谢。

标签: c# android asp.net asp.net-web-api oauth


【解决方案1】:

我已经使用 ASP.NET Identity 在我自己的 ASP.NET MVC 应用程序中成功完成了这项任务,但随后遇到了您提到的问题:我还需要使用 Web API 来工作,以便我的移动应用程序可以交互本机。

我不熟悉您链接的文章,但在阅读之后,我注意到其中的许多工作和代码是不必要的,并且使 ASP.NET Identity 中已经存在的功能变得复杂。

这是我的建议,我假设您使用的是 ASP.NET Identity V2,它相当于 MVC5 周围的包(不是新的 MVC6 vNext)。这将允许您的网站和移动应用程序通过 API 使用本地登录名(用户名/密码)和外部 OAuth 提供程序从您网站上的 MVC Web 视图和通过移动应用程序的 Web API 调用进行身份验证:

第 1 步。创建项目时,请确保包含 MVC 和 Web API 所需的包。在 ASP.NET 项目选择对话框中,您可以选择复选框,确保 MVC 和 Web API 都被选中。如果您在创建项目时还没有这样做,我建议您创建一个新项目并迁移现有代码,而不是搜索并手动添加依赖项和模板代码。

第 2 步。在您的 Startup.Auth.cs 文件中,您将需要代码告诉 OWIN 使用 cookie 身份验证、允许外部登录 cookie 并支持 OAuth 不记名令牌(这是 Web API 调用将进行身份验证的方式)。这些是我工作项目代码库的相关摘录:

Startup.Auth.cs

// 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
        {
            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>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        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(14),
            //AllowInsecureHttp = false
        };

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

 app.UseTwitterAuthentication(
            consumerKey: "Twitter API Key",
            consumerSecret: "Twitter API Secret");

        app.UseFacebookAuthentication(
            appId: "Facebook AppId",
            appSecret: "Facebook AppSecret");

在上述代码中,我目前支持 Twitter 和 Facebook 作为外部身份验证提供程序;但是,您可以使用 app.UserXYZProvider 调用和其他库添加其他外部提供程序,它们将使用我在此处提供的代码即插即用。

第 3 步。在您的 WebApiConfig.cs 文件中,您必须配置 HttpConfiguration 以抑制默认主机身份验证并支持 OAuth 不记名令牌。解释一下,这告诉您的应用程序区分 MVC 和 Web API 之间的身份验证类型,这样您就可以使用网站的典型 cookie 流,同时您的应用程序将接受来自 Web API 的 OAuth 形式的不记名令牌,而不会抱怨或其他问题。

WebApiConfig.cs

// Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

第 4 步。您需要一个用于 MVC 和 Web API 的 AccountController(或同等用途的控制器)。在我的项目中,我有两个 AccountController 文件,一个是从基本 Controller 类继承的 MVC 控制器,另一个是从 Controllers.API 命名空间中的 ApiController 继承的 AccountController,以保持整洁。我正在使用来自 Web API 和 MVC 项目的标准模板 AccountController 代码。这是帐户控制器的 API 版本:

AccountController.cs(Controllers.API 命名空间)

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;

using Disco.Models.API;
using Disco.Providers;
using Disco.Results;

using Schloss.AspNet.Identity.Neo4j;
using Disco.Results.API;

namespace Disco.Controllers.API
{
    [Authorize]
    [RoutePrefix("api/account")]
    public class AccountController : ApiController
    {
        private const string LocalLoginProvider = "Local";
        private ApplicationUserManager _userManager;

        public AccountController()
        {            
        }

        public AccountController(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; private set; }

        // GET account/UserInfo
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("userinfo")]
        public UserInfoViewModel GetUserInfo()
        {
            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            return new UserInfoViewModel
            {
                Email = User.Identity.GetUserName(),
                HasRegistered = externalLogin == null,
                LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
            };
        }

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

        // GET account/ManageInfo?returnUrl=%2F&generateState=true
        [Route("manageinfo")]
        public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false)
        {
            IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user == null)
            {
                return null;
            }

            List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>();

            foreach (UserLoginInfo linkedAccount in await UserManager.GetLoginsAsync(User.Identity.GetUserId()))
            {
                logins.Add(new UserLoginInfoViewModel
                {
                    LoginProvider = linkedAccount.LoginProvider,
                    ProviderKey = linkedAccount.ProviderKey
                });
            }

            if (user.PasswordHash != null)
            {
                logins.Add(new UserLoginInfoViewModel
                {
                    LoginProvider = LocalLoginProvider,
                    ProviderKey = user.UserName,
                });
            }

            return new ManageInfoViewModel
            {
                LocalLoginProvider = LocalLoginProvider,
                Email = user.UserName,
                Logins = logins,
                ExternalLoginProviders = GetExternalLogins(returnUrl, generateState)
            };
        }

        // POST account/ChangePassword
        [Route("changepassword")]
        public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
                model.NewPassword);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // POST account/SetPassword
        [Route("setpassword")]
        public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // POST account/AddExternalLogin
        [Route("addexternallogin")]
        public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);

            if (ticket == null || ticket.Identity == null || (ticket.Properties != null
                && ticket.Properties.ExpiresUtc.HasValue
                && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
            {
                return BadRequest("External login failure.");
            }

            ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);

            if (externalData == null)
            {
                return BadRequest("The external login is already associated with an account.");
            }

            IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
                new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // POST account/RemoveLogin
        [Route("removelogin")]
        public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result;

            if (model.LoginProvider == LocalLoginProvider)
            {
                result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
            }
            else
            {
                result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
                    new UserLoginInfo(model.LoginProvider, model.ProviderKey));
            }

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // GET account/ExternalLogin
        [OverrideAuthentication]
        [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
        [AllowAnonymous]
        [Route("externallogin", Name = "ExternalLoginAPI")]
        public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return new ChallengeResult(provider, this);
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return InternalServerError();
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return new ChallengeResult(provider, this);
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                 ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                    OAuthDefaults.AuthenticationType);
                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                    CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return Ok();
        }

        // GET account/ExternalLogins?returnUrl=%2F&generateState=true
        [AllowAnonymous]
        [Route("externallogins")]
        public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
        {
            IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
            List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();

            string state;

            if (generateState)
            {
                const int strengthInBits = 256;
                state = RandomOAuthStateGenerator.Generate(strengthInBits);
            }
            else
            {
                state = null;
            }

            foreach (AuthenticationDescription description in descriptions)
            {
                ExternalLoginViewModel login = new ExternalLoginViewModel
                {
                    Name = description.Caption,
                    Url = Url.Route("ExternalLogin", new
                    {
                        provider = description.AuthenticationType,
                        response_type = "token",
                        client_id = Startup.PublicClientId,
                        redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
                        state = state
                    }),
                    State = state
                };
                logins.Add(login);
            }

            return logins;
        }

        // POST account/Register
        [AllowAnonymous]
        [Route("register")]
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

        // POST account/RegisterExternal
        [OverrideAuthentication]
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("registerexternal")]
        public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var info = await Authentication.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return InternalServerError();
            }

            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user);
            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            result = await UserManager.AddLoginAsync(user.Id, info.Login);
            if (!result.Succeeded)
            {
                return GetErrorResult(result); 
            }
            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && _userManager != null)
            {
                _userManager.Dispose();
                _userManager = null;
            }

            base.Dispose(disposing);
        }

        #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 (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }

                if (ModelState.IsValid)
                {
                    // No ModelState errors are available to send, so just return an empty BadRequest.
                    return BadRequest();
                }

                return BadRequest(ModelState);
            }

            return null;
        }

        private class ExternalLoginData
        {
            public string LoginProvider { get; set; }
            public string ProviderKey { get; set; }
            public string UserName { get; set; }

            public IList<Claim> GetClaims()
            {
                IList<Claim> claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider));

                if (UserName != null)
                {
                    claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider));
                }

                return claims;
            }

            public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
            {
                if (identity == null)
                {
                    return null;
                }

                Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);

                if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)
                    || String.IsNullOrEmpty(providerKeyClaim.Value))
                {
                    return null;
                }

                if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
                {
                    return null;
                }

                return new ExternalLoginData
                {
                    LoginProvider = providerKeyClaim.Issuer,
                    ProviderKey = providerKeyClaim.Value,
                    UserName = identity.FindFirstValue(ClaimTypes.Name)
                };
            }
        }

        private static class RandomOAuthStateGenerator
        {
            private static RandomNumberGenerator _random = new RNGCryptoServiceProvider();

            public static string Generate(int strengthInBits)
            {
                const int bitsPerByte = 8;

                if (strengthInBits % bitsPerByte != 0)
                {
                    throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits");
                }

                int strengthInBytes = strengthInBits / bitsPerByte;

                byte[] data = new byte[strengthInBytes];
                _random.GetBytes(data);
                return HttpServerUtility.UrlTokenEncode(data);
            }
        }

        #endregion
    }
}

第 5 步。您还需要创建一个 ApplicationOAuthProvider,以便服务器可以生成和验证 OAuth 令牌。这在 WebAPI 示例项目中提供。这是我的文件版本:

ApplicationOAuthProvider.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Butler.Models;

using Schloss.AspNet.Identity.Neo4j;

namespace Butler.Providers
{
    public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
    {
        private readonly string _publicClientId;

        public ApplicationOAuthProvider(string publicClientId)
        {
            if (publicClientId == null)
            {
                throw new ArgumentNullException("publicClientId");
            }

            _publicClientId = publicClientId;
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }

        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return Task.FromResult<object>(null);
        }

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Resource owner password credentials does not provide a client ID.
            if (context.ClientId == null)
            {
                context.Validated();
            }

            return Task.FromResult<object>(null);
        }

        public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        {
            if (context.ClientId == _publicClientId)
            {
                //Uri expectedRootUri = new Uri(context.Request.Uri, "/");

                //if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                //{
                    context.Validated();
                //}
            }

            return Task.FromResult<object>(null);
        }

        public static AuthenticationProperties CreateProperties(string userName)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                { "userName", userName }
            };
            return new AuthenticationProperties(data);
        }
    }
}

还包括 ChallengeResult,您的应用程序的 Web API 分支将使用它来处理外部登录提供程序提供的挑战,以验证您的用户:

ChallengeResult.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace Butler.Results
{
    public class ChallengeResult : IHttpActionResult
    {
        public ChallengeResult(string loginProvider, ApiController controller)
        {
            LoginProvider = loginProvider;
            Request = controller.Request;
        }

        public string LoginProvider { get; set; }
        public HttpRequestMessage Request { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            Request.GetOwinContext().Authentication.Challenge(LoginProvider);

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            response.RequestMessage = Request;
            return Task.FromResult(response);
        }
    }
}

使用这组代码,您将能够在 AccountController 的 API 版本上通过 HTTP GET 和 HTTP POST 路由来注册用户,使用用户名和密码登录以接收 Bearer 令牌,添加/删除外部登录,管理外部登录,对于您的问题,最重要的是,通过传入外部登录令牌以换取您的应用程序的 OAuth 持有者令牌来进行身份验证。

【讨论】:

  • 我希望这会有所帮助,并且我将继续更新和改进此答案,以便在必要时提供清晰的说明或替代方法。 Disco/Butler 是具有不同命名空间的同一个项目,我为造成的混乱道歉。此外,各种文件中包含的 Schloss 库是因为我的 ApplicationUser 和 UserStore for ASP.NET Identity 使用 Neo4j 而不是 EntityFramework。这对文件中的代码绝对没有影响,只要您的项目中有 MVC 和 Web API 依赖项,这些文件中的代码应该可以与任何 OWIN/ASP.NET 应用程序即插即用。
  • 哇,这太棒了!我发现与我目前的项目有很多相似之处。我很快会在这里找到一些时间并尝试您的示例,看看我是否可以让它工作。我会报告我的发现!
  • 是的,不记名令牌就是答案。现在客户端应用程序持有它的不记名令牌并将其包含在每个请求的标头中。回答得很好。
  • 我还有一个使用 Knockout 的客户端 Javascript,它显示了一个调用 API 的示例,将不记名令牌存储在本地会话存储中,如果您希望我添加,可以将其作为授权标头包含在内。我不确定您的移动应用是使用 JavaScript 还是原生应用,所以我将其省略了。
  • @TylerJamesHarden 你还会拥有 Knockout 应用程序吗?看一个调用 API 的例子真的很有帮助
【解决方案2】:

我将此作为对您问题第二部分的单独回答说 YES 您可以将两个单独的项目绑定到同一个数据库,并且只需拥有 MVC/Web Forms 网站项目使用所有 cookie 身份验证,然后有一个单独的 Web API 项目,即所有令牌身份验证。

在我对源代码示例的较长回答中,我基本上所做的是将两个独立的项目合并为一个项目,以避免冗余的模型代码和控制器代码。就我而言,这对我来说更有意义。但是,我倾向于说,是维护两个独立的项目,一个网站和一个 Web API 端点,还是将它们结合起来,这取决于个人喜好和项目的需要。

ASP.NET 被设计为非常灵活并且作为中间件即插即用,我可以证明我的项目已经存在并且完全按照预期在两个单独的项目中运行,现在作为一个组合项目。

【讨论】:

  • 谢谢。我确实发现你可以做到这一点。我不是它的粉丝,但我想我会走这条路,因为我无法让它同时适用于两者。我在上面看到您的示例将其作为一个站点进行,并将对其进行测试并报告我的发现。再次感谢!
  • 以后不要添加第二个答案,除非它是不同的答案。请结合两个答案。我明白答案变得太大,但答案的使用不是部分。请结合两个答案并删除这个。
  • 我认为一个项目与多个项目实际上是分开的,但我理解你的推理。
【解决方案3】:

您可能想看看这一系列文章,看看它是否涵盖了您的目标:

Token Based Authentication using ASP.NET Web API 2, Owin, and Identity Taiseer Joudeh(他也经常回答关于 SO 的问题)

这些文章是关于使用 OWIN 创建基于令牌的身份验证服务的,其中一部分涉及使用外部登录(例如 Facebook 和 Google+)。这些示例主要围绕作为 Web 服务使用者的 Web 应用程序,但它也应该适用于移动应用程序。这些文章有一个相关的 GitHub 项目和一个非常活跃的评论部分,几乎没有任何问题没有得到解答。

希望这可以引导您实现目标。

【讨论】:

    猜你喜欢
    • 2013-10-05
    • 2017-06-15
    • 2019-03-18
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 2013-10-16
    • 2017-10-22
    • 2015-04-05
    相关资源
    最近更新 更多