ASP.NET MVC使用Jquery登录:验证凭据是否有效

时间:2017-02-22 02:47:39

标签: jquery ajax asp.net-mvc identityserver4

这可能是一个奇怪的问题,但我只是想检查一下是否可行或我错过了什么。

我正在使用身份服务器并在我的帐户控制器中执行此登录操作:

public async Task<IActionResult> Login(LoginInputModel model)
{
    if (ModelState.IsValid)
    {
        // validate username/password against in-memory store
        var user = new SecurityCore.Models.User();

        var compasLoginReponse = UserLogin(model.UserName, model.Password);

        if (compasLoginReponse.IsSuccess)
        {
            //set the user logged in 
            user = compasLoginReponse.Entity;

            // issue authentication cookie with subject ID and username             
            await HttpContext.Authentication.SignInAsync(user.Subject, user.UserName);

            // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint
            if (_interaction.IsValidReturnUrl(model.ReturnUrl))
            {
                return Redirect(model.ReturnUrl);
            }
            return Redirect("~/");
        }
    }         

    //this is bad practice , but just for the purpose if testing
    return Ok("false");
}

我正在尝试使用jquery帖子,以防止页面刷新或回复如果凭据错误(当用户有效时,他将redirectecd重定向到包含令牌的其他网址)

这是我的表格,这是我的ajax功能:

登录按钮的点击事件处理程序

&#13;
&#13;
 $("#login_button").click(function () {
     $.ajax({
         type: "POST",
         url: "/Account/Login",
         data: { 'username': $("#username").val(), 
             'password': $("#password").val() },
         datatype: "json",
         success: function (result) {
             if (result === "false") {
                 //then alert the user for wrong    credentials
             }
         }
    });

    //if if omit this line then the return url will be pouplated otherwise, it will be null
    return false;
});
&#13;
&#13;
&#13;

&#13;
&#13;
@model IdentityServer4.Quickstart.UI.Models.LoginViewModel

  
<form asp-route="Login">
    <input type="hidden" asp-for="ReturnUrl" />
    <div  id="form-group-username">
        <label for="username">Username</label>
        <input type="text" asp-for="Username" id="username">
    </div>
    <div  id="form-group-password">
        <label for="pwd">Password</label>
        <input type="password" asp-for="Password" id="password">
    </div>
     
    <button type="button" id="login_button">Login</button>
</form>
&#13;
&#13;
&#13;

我的问题:在Login Action中从此函数返回的返回URL始终为null。

if (_interaction.IsValidReturnUrl(model.ReturnUrl))

如果我省略最后一行&#34;返回false&#34;来自jquery函数,然后它可以工作,但Action执行两次,第一次返回url为null,下次获取url。

除非提交了网页,否则似乎无法正常工作。

我如何实现我打算做的事情?如果凭据错误,是否有任何解决方法可以阻止页面进行回发。

0 个答案:

没有答案