Home > Net >  How to check something before execute http request aspnet core web api 6
How to check something before execute http request aspnet core web api 6

Time:10-20

My customer want to validate token from query param like this

http://localhost/api/v1/users?token=xxxx

I can do like this:

[CustomAuthorize(Authorities = new[] { Constants.RoleGuest })]
[HTTPGet]
public async Task<IActionResult> Get(string token){
   //call validate token function with token provided
   //do something
}

Is there a way to implement automatic token authentication that does this for all requests except login and register? It sucks to have to call the authentication function on every http request. Is this implementable as a custom attribute ?

This question don't mention how to implement authen and authorization. Main popurse is check something when user request to any endpoint. In this situation, it is token. It isn't same access token and refresh token

Thanks for all the help!

CodePudding user response:

You can use action filter and custom attribute to implement it.

public class MyAuth : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        var actionInfo = context.ActionDescriptor as ControllerActionDescriptor;
        var token = context.HttpContext.Request.Query.ContainsKey("token")
            ? Convert.ToString(context.HttpContext.Request.Query["token"])
            : string.Empty;
        var shouldStop = !IsValidToken(token, actionInfo);
        if (shouldStop)
        {
            context.Result = new UnauthorizedResult();
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {

    }

    private bool IsValidToken(string token, ControllerActionDescriptor actionInfo)
    {
        var valid = false;

        var controllerName = actionInfo?.ControllerName;
        var actionName = actionInfo?.ActionName;
        var roles =
            (actionInfo?.MethodInfo.GetCustomAttributes(typeof(CustomAuthorize), true)?.FirstOrDefault() as
                CustomAuthorize).Roles;

        // your token validation logic goes here

        return valid;
    }
}


public class CustomAuthorize : Attribute
{
    public string[] Roles { get; }
    public CustomAuthorize(string[] roles)
    {
        Roles = roles;
    }
}

And in the program.cs you can register the Action filter as below

builder.Services.AddControllers(_ =>
{
    _.Filters.Add(typeof(MyAuth));
});

Finally, your action method would look like below -

[CustomAuthorize(new string[]{Constants.RoleGuest})]
[HTTPGet]
public async Task<IActionResult> Get(){
   // do actual work.
   // this method will be only called if your validation logic pass.
}
  • Related