Search code examples
c#asp.net-coreasp.net-web-apiauthorizationcustom-attributes

How to develop a custom AuthorizeAttribute that accepts a token passed as URL parameter


I have created a web API (ASP.Net core 6) and there is one endpoint to view resources(opens in new tab). Since it (resource) opens in new tab I can not implement authorization functionality on that endpoint. So I want to implement a custom authorization attribute that accepts the users token which can be passed as URL parameter (http://{website}/{action}?token={token}) and validate the token.

I have followed similar questions and posts. Few of them are post 1 and post 2.

Still No success. Could someone please show how I can achieve this. Since I am a beginner with .Net I expects your support. Thank you!


Solution

  • The posts in your question are all for asp.net not for asp.net core ,Authentication/Authorization would be executed in middleware now ,you could check this document related to learn Authentication\Authorization in .net core

    And if you try with JwtAuthentication,you could specific where to read the token,here's a related case(In this case,i tried to read jwt token from cookie and read claim from token)

    If you insist on creating an Attribute to accept token,validate and assign claims to httpcontext,you could try with AuthorizationFilter:

    public class MyAuthorizeFilterAttribute : Attribute,IAuthorizationFilter
        {
            public void OnAuthorization(AuthorizationFilterContext context)
            {
                var token = context.HttpContext.Request.Query["token"].ToString();
                if (!String.IsNullOrEmpty(token))
                {
                   //read claims from token and assign to HttpContext.User
                }
                else
                {
                    context.Result = new UnauthorizedResult();
                }
                
            }
        }