我需要通过外部服务授权我的用户,无需身份,无需密码,无需武士刀。仅基于布尔值true或false。由api发送。我该如何通过[Authorize]属性来满足我的需求?
public class LoginController {
public ActionResult LoginThroughExternalApp(authModel model)
{
bool isUserExist = externalApp.isUserExist(model.userName, model.Password);
if(isUserExist)
{
return RedirecToAction("DefaultActionName","DefaultController");
}
return RedirectToAction("Redirect to error login page.");
}
}
[Authorize]
public class DefaultController
{
public ActionResult DefaultAction()
{
//Do some stuff
}
}
答案 0 :(得分:0)
您可以定义CustomActionAttribute
以添加具有特定参数的任何方法。然后,您可以进行自定义操作以让用户使用。
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CustomActionAttribute : FilterAttribute, IActionFilter, IResultFilter
{
public string ParamName { get; set; }
public void OnActionExecuted(ActionExecutedContext filterContext)
{
throw new NotImplementedException();
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionParameters.ContainsKey(ParamName))
{
try
{
var model = filterContext.ActionParameters[ParamName] as authModel;
bool isUserExist = externalApp.isUserExist(model.userName, model.Password);
if (isUserExist)
// this code let you to go on without checking authorization.
return;
}
catch
{
}
}
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/UnAuthorizeAction.cshtml",
};
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
throw new NotImplementedException();
}
public void OnResultExecuting(ResultExecutingContext filterContext)
{
throw new NotImplementedException();
}
}
这是用法:
[CustomActionAttribute(IdParamName = model)]
public ActionResult DefaultAction(authModel model)
{
//...
}