简体   繁体   English

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

[英]ASP.NET custom authentication/Authorization

I need to authorize my user through external service no identity no owin no katana is required. 我需要通过外部服务授权我的用户没有身份没有owin不需要武士刀。 Only based on Boolean value true or false. 仅基于布尔值true或false。 Which is send by api. 这是由api发送的。 How can i ovveride [Authorize] attribute to suite my needs? 我如何能够将[授权]属性用于满足我的需求?

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
      }
    }

You can define CustomActionAttribute to add any method with specific parameter(s). 您可以定义CustomActionAttribute以添加具有特定参数的任何方法。 Then you can do custom operation to let user. 然后你可以做自定义操作让用户。

[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();
    }
}

And here it's usage: 这是它的用法:


[CustomActionAttribute(IdParamName = model)]
public ActionResult DefaultAction(authModel model)
{
    //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM