外部のプログラマが作成したコードがあります。プロジェクトはWebApiです。私は認可がどのように起こるかを知らない。私のコントローラメソッドの上にある属性は、これが私の思うようになるのです。しかし、私は認可が実際どのように起こるのか理解していません。コントローラメソッドの例:c#WebApi属性認証
[HttpGet]
[Route("organizationunits/{entity}/{type}")]
[MDLAuthorize(Actions.Read)]
public async Task<IHttpActionResult> GetEntities(string entity, string type)
{//some code}
MDLAuthorize属性はメソッドを指定します。そして、どういうわけかIsAuthorizedメソッドが呼び出されたと思います。
public class MDLAuthorize : AuthorizeAttribute
{
private string _action;
public MDLAuthorize(string action)
: base()
{
_action = action;
}
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
try
{
if (String.IsNullOrEmpty(_action))
return false;
var baseAuthorized = base.IsAuthorized(actionContext);
string activity = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
if (actionContext.RequestContext.Principal == null ||
actionContext.RequestContext.Principal.Identity == null)
{
//no principal, no fun.
return false;
}
else
{
string username = actionContext.RequestContext.Principal.Identity.Name;
bool isAuthorized = Security.HasPermission(username, activity, _action);
return isAuthorized;
}
}
catch (Exception ex)
{
MDLApiLog.Error(ex);
return false;
}
}
}
私の質問のために必要であれば、私は知りませんが、これはAuthorizeAttributeクラス
//
// Summary:
// Specifies the authorization filter that verifies the request's System.Security.Principal.IPrincipal.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : AuthorizationFilterAttribute
{
//
// Summary:
// Initializes a new instance of the System.Web.Http.AuthorizeAttribute class.
public AuthorizeAttribute();
//
// Summary:
// Gets or sets the authorized roles.
//
// Returns:
// The roles string.
public string Roles { get; set; }
//
// Summary:
// Gets a unique identifier for this attribute.
//
// Returns:
// A unique identifier for this attribute.
public override object TypeId { get; }
//
// Summary:
// Gets or sets the authorized users.
//
// Returns:
// The users string.
public string Users { get; set; }
//
// Summary:
// Calls when an action is being authorized.
//
// Parameters:
// actionContext:
// The context.
//
// Exceptions:
// T:System.ArgumentNullException:
// The context parameter is null.
public override void OnAuthorization(HttpActionContext actionContext);
//
// Summary:
// Processes requests that fail authorization.
//
// Parameters:
// actionContext:
// The context.
protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext);
//
// Summary:
// Indicates whether the specified control is authorized.
//
// Parameters:
// actionContext:
// The context.
//
// Returns:
// true if the control is authorized; otherwise, false.
protected virtual bool IsAuthorized(HttpActionContext actionContext);
}
はい、Authorize属性により、メソッドが呼び出されます。ユーザが許可されている場合にのみ、webapiのメソッドへの呼び出しが実行されます。そうでないと、HTTP認証されていないコードがクライアントに返されます。 – bit