Search code examples
abp-framework

How to pass bearer access_token in URL for Get request to ABP API


I'm using ABP vNext v3.3, and had no problem to call the Api when passing Bearer access_code in request Header.

However, I want to put the the access_code within URL directly as a link, then user can perform the same action by just clicking the link. Does anybody know whether it's possible and how to pass the query string? I tried:

https://endpoint?access_code=[my access code]

https://endpoint?Authorization=Bearer+[my access code]

Unfortunately there's no joy. Thanks


Solution

  • As per the info. I got from https://stackoverflow.com/a/21496536/10350621, below is my implementation which works fine.

    In MyProjectNameHttpApiHostModule.cs, add JwtBearerEvents for getting token from either header or QueryString:

    private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
    {
        context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority = configuration["AuthServer:Authority"];
                options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]);
                options.Audience = "MySystemName";
                options.Events = new JwtBearerEvents()
                {                        
                    OnMessageReceived = c =>
                    {
                        string authorization = c.Request.Headers["Authorization"];
    
                        if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                        {
                            c.Token = authorization.Substring("Bearer ".Length).Trim();
                        }
                        // If no authorization header found, then check access_token from QueryString
                        else
                        {
                            var accessToken = c.Request.Query["access_token"];
                            if (!string.IsNullOrEmpty(accessToken))
                            {
                                c.Token = accessToken;
                            }
                        }
    
                        // If no token found, no further work possible
                        if (!string.IsNullOrEmpty(c.Token))
                        {
                            return Task.CompletedTask;
                        }
    
                        c.NoResult();
                        return Task.CompletedTask;
                    }
                };
            });
        }
    }