首页 > 解决方案 > How to add an 'aud' claim to access_token

问题描述

I'm new to IdentityServer 4 and OpenIdConnect, trying to get my Asp.NET Core + Angular 9 SPA app to work with JwtBearer tokens, and the problem is what I cannot set my access_token's 'aud' claim properly, I'm getting 401 with message:

Bearer error="invalid_token", error_description="The audience 'empty' is invalid

The audience 'empty' is invalid

found in WWW-Authenticate header.

If however, instead of this I will use an id_token constantly (which should be used only once to log user into the app as I suppose), I will get access to my protected resources, because it has this 'aud' claim.

I suppose it is not a proper behaviour (or is it?)

Is there any way, how I may explicitly set the access_token's 'aud' claim? I've looked already in many places, stackOverflow, OpenId.net docs and the others, and still I cannot find an answer. May some1 help me with that?

Here's my AddAuthentication method in my API & app.UseAuthentication/app.UseAuthorization: https://pastebin.com/YdE3WQ7b

and my client config: https://pastebin.com/AdAjntjc

PrintScreen of jwt.io:

access_token_at_jwt_io_img

标签: access-tokenjwt-authoidc-client-js

解决方案


IdentityServer4 版本 v4 发生了重大变化,默认情况下它们不再设置 aud 声明。

可能您关注了一篇旧文章,例如:

https://medium.com/@marcodesanctis2/securing-blazor-webassembly-with-identity-server-4-ee44aa1687ef

哪个使用 IS4 v3

在此处输入图像描述

但是,如果您检查官方文档的配置部分,它会说您需要禁用 aud 声明:

https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html#configuration

{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority = "https://localhost:5001";

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false
                };
            });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

推荐阅读