ASP.NET自定义身份验证/授权

时间:2019-05-29 14:37:36

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

我需要通过外部服务授权我的用户,无需身份,无需密码,无需武士刀。仅基于布尔值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
      }
    }

1 个答案:

答案 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)
{
    //...
}