ASP.NET MVC5自定义身份验证

时间:2019-05-29 14:06:23

标签: c# .net authentication asp.net-mvc-5 authorization

我正在为ASP.NET应用程序编写自定义身份验证逻辑。我需要通过我们的另一个API对我们的用户进行身份验证。我需要将用户登录名和密码发送到外部API,如果用户存在,该服务将向我发送true,否则为false。

这是我的Logincontroller actionresult代码,最终应重新诱使经过身份验证的用户执行uploadFileController操作:

[HttpPost]
public ActionResult AccountLogin(AuthenticationViewModel authModel)
{
    //exists in database
    bool isExistUser = _service.isUserExist(authModel.UserName);

    if (!isExistUser)
    {
        TempData["UserIsNotExist"] = "User does not exist.";
        return RedirectToAction("AccountLogin");
    }

    ServiceExternalApi.srvEmployeeSoapClient client = new ServiceExternalApi.srvEmployeeSoapClient();

    bool isUserExistInHrm = hrmclient.f_EmployeeCheckLogin(authModel.UserName, authModel.Password);

    if (!isUserExistInHrm)
    {
        TempData["UserisNotExistInInExternalApi"] = "Wrong credentials.";
        return RedirectToAction("AccountLogin");
    }

    return RedirectToAction("GetAlreadyScannedFileList","UploadFile");
}

如果我将授权属性添加到“ UploadFile”控制器,则此代码根本不起作用。任何建议表示赞赏。

换句话说,我如何在此逻辑中使用[Authorize]属性?如果外部服务向我发送了true,则表示我想被授权,如果是false,则未经授权。

1 个答案:

答案 0 :(得分:0)

您需要在客户端计算机上设置身份验证cookie,以便在成功登录后允许后续请求。

public class CustomeAuthorizeAttribute : AuthorizeAttribute
{

     public override void OnAuthorization(AuthorizationContextfilterContext)          
    {
         if (!isUserExistInHrm)
        {
            TempData["UserisNotExistInInExternalApi"] = "Wrong credentials.";
            return RedirectToAction("AccountLogin");
        }
        else
        {
            FormsAuthentication.SetAuthCookie(authModel.UserName, false);
        }
    }
}

配置表单身份验证

配置应用程序以使用Forms身份验证。这可以在web.config文件中完成。

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

现在将[CustomeAuthorize]上的uploadFileController属性添加到

[CustomeAuthorize]
public class uploadFileController  : Controller
{

}