I writing a .Net core API and my API itself does not have any authentication or authorization logic. The authentication and authorization are handled by a separate system so in order to secure my endpoints I need to forward each incoming request to the external system and decide if the user is authenticated depending upon the value being returned from the external system.
I want to know whats the best approach to implement something like this, as I think it can be done with a CustomAuthorize
attribute or middleware
or by adding a CustomAuthPolicy
. There are many bits and pieces in Auth with .Net core, I would really appreciate if someone can guide me in the right direction.
Here is my solution that I am currently using:
This solution works great, and if you have the following in a referenced project, it can easily be reused.
Create a Custom Attribute:
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class MyAuthAttr : ActionFilterAttribute
{
//Add Auth logic here using HttpClient or whatever you use to authenticate.
//You can access your headers through actionContext.HttpContext.Request.Headers
//When completed with your logic, you can continue your controller execution
base.OnActionExecuting(actionContext);
}
This attribute can be applied to your controllers like this:
[MyAuthAttr]
public class MySecureControllerController {...}
This can be applied to the Controller's class as global auth, or any of the endpoints within the controller as specific auth.
So this will work too:
[Route("Do")]
[MyAuthAttr]
public IActionResult DoThaThing(Foo foo) {...}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments