[英]ASP.NET MVC5 custom authentication
我正在為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,則表示未經授權。
您需要在客戶端計算機上設置身份驗證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
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.