C# aspnet核心jwt令牌作为get参数

C# aspnet核心jwt令牌作为get参数,c#,asp.net-core,jwt,asp.net-core-2.0,C#,Asp.net Core,Jwt,Asp.net Core 2.0,我正在从事一个aspnet core 2 web api项目,该项目的主要消费者是vue web应用程序 Api使用jwt令牌作为身份验证方法,一切正常 现在,我已经编写了所有代码来管理图像存储和从数据库检索,但我在从数据库中获取图像时遇到了一个问题 所有路由(除了登录)都在身份验证之后,所以要检索我在请求头中拥有的pass令牌(通常是这样)的映像 这会阻止我使用图像源标记实际显示图像,如中所示 <img src="/api/images/27" /> 这是可行的,但不知何故这是一

我正在从事一个aspnet core 2 web api项目,该项目的主要消费者是vue web应用程序

Api使用jwt令牌作为身份验证方法,一切正常

现在,我已经编写了所有代码来管理图像存储和从数据库检索,但我在从数据库中获取图像时遇到了一个问题

所有路由(除了登录)都在身份验证之后,所以要检索我在请求头中拥有的pass令牌(通常是这样)的映像

这会阻止我使用图像源标记实际显示图像,如中所示

<img src="/api/images/27" />
这是可行的,但不知何故这是一个不必要的复杂问题

我在AspNet核心身份中看到

或者,您可以从其他地方获取令牌,例如不同的头,甚至cookie。在这种情况下,处理程序将使用提供的令牌进行所有进一步的处理

(摘自安德烈·洛克博客的文章) 正如你也可以看到的,检查,它说

让应用程序有机会从其他位置查找、调整或拒绝令牌

但我找不到任何关于如何使用此功能和传递自定义令牌的示例

所以,我的问题是:是否有人知道如何将自定义令牌(可能从get参数读取)传递给标识提供者(甚至可能只针对某些已定义的路由)


谢谢你的正确回答

如果有人感兴趣,从url参数读取令牌并将其传递给验证的完整代码如下

service.AddAuthentication(...)
    .AddJwtBearer(options =>
        // ...
        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = ctx =>
            {
                // replace "token" with whatever your param name is
                if (ctx.Request.Method.Equals("GET") && ctx.Request.Query.ContainsKey("token"))
                    ctx.Token = ctx.Request.Query["token"];
                return Task.CompletedTask;
            }
        };
    });

您的应用程序可以提供此功能,例如使用正确的凭据登录。(前端->登录正确->后端发回JWT令牌。)

然后,您可以将后端提供给您的令牌存储在cookie/localstorage中

每次将请求发送回API时,只需从cookie/localstorage中检索令牌并将其添加到请求头

我将向您展示一个如何添加中间件来处理令牌生成和验证的示例

appsettings.conf

{
  "Secret": {
    "Key": "abcdefghijklmnop123456789"
  }
}
密钥用于生成唯一的JWT令牌,应单独存储在机器上,这只是出于示例目的

TokenProviderOptions.cs

public class TokenProviderOptions
{
    public string Path { get; set; } = "/token";
    public string Issuer { get; set; }
    public string Audience { get; set; }
    public TimeSpan Expiration { get; set; } = TimeSpan.FromHours(1);
    public SigningCredentials SigningCredentials { get; set; }
}
该类将为我们提供令牌生成的基本信息。 “路径”可以更改为要检索令牌的任何路径

TokenProviderMiddleware.cs

public class TokenProviderMiddleware
{
    private readonly RequestDelegate _next;
    private readonly TokenProviderOptions _options;
    private readonly IAccountService _accountService;

    public TokenProviderMiddleware(RequestDelegate next, IOptions<TokenProviderOptions> options, IAccountService accounteService)
    {
        _next = next;
        _options = options.Value;
        _accountService = accounteService;
    }

    public Task Invoke(HttpContext context)
    {
        //Check path request
        if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal)) return _next(context);

        //METHOD: POST && Content-Type : x-www-form-urlencode
        if (context.Request.Method.Equals("POST") && context.Request.HasFormContentType)
            return GenerateToken(context);


        context.Response.StatusCode = 400;
        return context.Response.WriteAsync("Bad Request");
    }

    private async Task GenerateToken(HttpContext context)
    {
        var username = context.Request.Form["username"];
        var password = context.Request.Form["password"];

        var identity = await GetIdentity(username, password);

        if (identity == null)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Invalid username or password");
            return;
        }

        var now = DateTime.UtcNow;

        var claims = new Claim[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.Iat, now.Second.ToString(), ClaimValueTypes.Integer64)
        };

        var jwt = new JwtSecurityToken(
            issuer: _options.Issuer,
            audience: _options.Audience,
            claims: claims,
            notBefore: now,
            expires: now.Add(_options.Expiration),
            signingCredentials: _options.SigningCredentials);

        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

        var response = new
        {
            access_token = encodedJwt,
            expires_in = (int)_options.Expiration.TotalSeconds,
            username = username
        };

        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(JsonConvert.SerializeObject(response,
            new JsonSerializerSettings { Formatting = Formatting.Indented }));
    }

    private Task<ClaimsIdentity> GetIdentity(string username, string password)
    {
        //THIS STEP COULD BE DIFFERENT, I HAVE AN ACCOUNTSERVICE THAT QUERIES MY DB TO CHECK THE USER CREDENTIALS
        var auth = _accountService.Login(username, password).Result;
        return auth
            ? Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { }))
            : Task.FromResult<ClaimsIdentity>(null);
    }
}
我省略了多余的代码。这将添加自定义中间件,并将应用程序配置为使用JWT令牌

您所要做的就是更改上面提到的自定义参数,用“token”对您的请求进行签名:tokenValue,您就可以了

我在这里有一个可用的后端模板: 仔细检查一切


希望有帮助

可以使用连接到提供给
AddJwtBearer
jwtbeareOptions
实例的
jwtbeareEvents
来处理此问题。具体来说,有一个
OnMessageReceived
事件可以实现以提供令牌本身。下面是一个例子:

services.AddAuthentication(...)
    .AddJwtBearer(jwtBearerOptions =>
    {
        // ...

        jwtBearerOptions.Events = new JwtBearerEvents
        {
            OnMessageReceived = ctx =>
            {
                // Access ctx.Request here for the query-string, route, etc.
                ctx.Token = "";
                return Task.CompletedTask;
            }
        };
    })
您可以看到这是如何在中使用的:


想知道在image
src
属性中附加承载令牌是否是一个好主意。不确定,但我认为它可以用来劫持和查看未经授权的图片to@adeel41从理论上讲,是的:如果我能得到一个用户令牌,我就可以用它来模拟他并访问他的数据(图像和其他)但是,为了访问用户令牌,必须对用户的计算机进行PHI访问,或者在中间HTTPS中使用某种类型的人,并且非常短的令牌使用寿命(在这种情况下1小时)应该降低这两种风险。
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        //Mvc
        services.AddMvc();

        //...

        //Authentication
        services.AddAuthentication()
            .AddJwtBearer(jwt =>
            {
                var signingKey =
                    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("Secret:Key").Value));

                jwt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = signingKey,

                    ValidateIssuer = true,
                    ValidIssuer = "2CIssuer",

                    ValidateAudience = true,
                    ValidAudience = "2CAudience",

                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.Zero
                };
            });

        //Authorization
        services.AddAuthorization(auth =>
        {
            auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build());
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        //...

        //Authentication
        var signingKey =
            new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("Secret:Key").Value));

        var options = new TokenProviderOptions
        {
            Audience = "2CAudience",
            Issuer = "2CIssuer",
            SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
        };

        app.UseAuthentication();

        //JWT
        app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));

        //Mvc
        app.UseMvc();
    }
}
services.AddAuthentication(...)
    .AddJwtBearer(jwtBearerOptions =>
    {
        // ...

        jwtBearerOptions.Events = new JwtBearerEvents
        {
            OnMessageReceived = ctx =>
            {
                // Access ctx.Request here for the query-string, route, etc.
                ctx.Token = "";
                return Task.CompletedTask;
            }
        };
    })
// event can set the token
await Events.MessageReceived(messageReceivedContext);

// ...

// If application retrieved token from somewhere else, use that.
token = messageReceivedContext.Token;