【问题标题】:ASP.NET MVC5 custom authenticationASP.NET MVC5 自定义身份验证
【发布时间】:2019-10-15 04:18:22
【问题描述】:

我正在为我的 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 未经授权。

【问题讨论】:

  • Authorize 会一直检查 Authorization 是否存在。 BTW 服务检查后需要执行什么类型的操作,检查结束后是否需要进行任何基于角色的授权?
  • 不,不需要角色。
  • 我能以某种方式覆盖 Authorize 属性以满足我的需要吗?
  • 我只想让它以这种方式工作,如果外部服务发送给我的话,那么我希望看到该用户被授权。假的情况下对应未授权。
  • 现在发生了什么?它在调试器没有进入“UploadFile”的意义上不起作用?

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


【解决方案1】:

您需要在客户端机器上设置身份验证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);
        }
    }
}

配置表单身份验证

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

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

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

[CustomeAuthorize]
public class uploadFileController  : Controller
{

}

【讨论】:

  • 该逻辑应该写在 [Authorize] 属性中,换句话说,我应该扩展 Authorize 类还是不扩展?
  • 我还有一个问题。如果我们将属性放在控制器类的头部,您认为最佳解决方案是什么?我有很多行动结果,每次我都必须调用外部api?如果我将属性赋予特定的动作结果,会不会效率更高?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多