【问题标题】:How to enable third party client authentication Asp .Net MVC如何启用第三方客户端身份验证 Asp .Net MVC
【发布时间】:2023-03-22 10:45:01
【问题描述】:

我正在使用 Asp .Net MVC 5 开发一个 Web 应用程序,它具有正常的 ASP.NET 身份,但现在我开发了一个移动应用程序,我需要使用我的 ASP 应用程序对用户进行身份验证。

我尝试向我的登录方法发出 AJAX 请求,但服务器响应异常:“验证提供的防伪令牌失败。cookie“__RequestVerificationToken”和表单字段“ __RequestVerificationToken" 被交换了。" 因为我有 [ValidateAntiForgeryToken] 装饰器,而且我认为 ASP .NET Identity 有任何其他方式来进行身份验证,但我不知道。

这是我的登录方式:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModdel model, string ReturnUrl)
{
    if (ModelState.IsValid)
    {
        Employer user = await _employerService.GetByCredentialsAsync(model.Email.Trim(), model.Password);

        if (user != null)
        {
            await SignInAsync(user, model.RememberMe);
            Response.StatusCode = (int)HttpStatusCode.OK;
        }
        else
        {
            Employer existingEmail = await _employerService.GetByUsernameAsync(model.Email);
            if (existingEmail == null)
            {
                ModelState.AddModelError("", "El usuario no está registrado. Regístrate o intenta ingresar con un nuevo usuario");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { statusCode = 400, message = "El usuario no está registrado. Regístrate o intenta ingresar con un nuevo usuario", Success = "False" });
            }
            else
            {
                ModelState.AddModelError("", "Contraseña inválida. Intenta de nuevo");
                Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                return Json(new { statusCode = HttpStatusCode.Unauthorized, Success = "False" });
            }
        }
    }
    if (string.IsNullOrWhiteSpace(ReturnUrl))
        ReturnUrl = Url.Action("Index", "Home");

    return Json(new { statusCode = HttpStatusCode.OK, returnUrl = ReturnUrl });
}

这是我的 ConfigureAuth:

// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {

            //Custom provirder create to read language fomr URL
            CookieAuthenticationProvider provider = new CookieAuthenticationProvider();
            var originalHandler = provider.OnApplyRedirect;
            provider.OnApplyRedirect = context =>
            {

                var mvcContext = new HttpContextWrapper(HttpContext.Current);
                var routeData = RouteTable.Routes.GetRouteData(mvcContext);

                //Get the current language  
                RouteValueDictionary routeValues = new RouteValueDictionary();

                //Reuse the RetrunUrl
                Uri uri = new Uri(context.RedirectUri);
                string returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
                routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);
                routeValues.Add(Cross.Constants.ModalRouteValue, Cross.Constants.LoginModal);
                //Overwrite the redirection uri
                UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
                string NewURI = url.Action("Index", "Home", routeValues);

                //Overwrite the redirection uri
                context.RedirectUri = NewURI;
                originalHandler.Invoke(context);
            };

            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Home/Index?Modal=Login"),
                Provider = provider,
            });

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        }
    }

【问题讨论】:

  • 那么,你有什么代码?您是如何配置 ASP.Net 身份的?您如何提出登录请求,您希望得到什么?
  • @BrendanGreen 谢谢,我编辑了添加我的代码的问题

标签: asp.net asp.net-mvc oauth asp.net-identity identity


【解决方案1】:

一般来说,您的 MVC 应用程序只适合在浏览器中工作。如果您需要向第三方提供一些数据,而这不是通过浏览器实现的,则需要使用WebApi。您可以在那里为您的客户使用bearer token authentication

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2020-03-03
    • 1970-01-01
    相关资源
    最近更新 更多