如何启用第三方客户端身份验证asp.net MVC



我正在开发一个Web应用程序与asp.net MVC 5,这有正常的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);
        }
    }

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

相关内容

  • 没有找到相关文章

最新更新