0

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!

3
  • Is this token JWT or some custom token? Commented Oct 19, 2022 at 8:15
  • If token is JWT the you can follow this link to do JWT auth. devblog.pekspro.com/posts/… Commented Oct 19, 2022 at 9:06
  • Hi @MataPrasadChauhan . My question don't mention JWT. Actually it is another JWT token generation from user info. When user login , they will receive access token, refresh token and another token generate from user info. I can implement authen and authorization with JWT token. My client want to validate 2 times per request. one from app with access token and one from token in query param. Commented Oct 19, 2022 at 9:27

1 Answer 1

2

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.
}
Sign up to request clarification or add additional context in comments.

2 Comments

tks for your suggest. I will be try it and reply soon!
Hi @Mata Prasad Chauhan , It worked for me. Tks for your help !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.