Separating Auth and Resource Servers with AspNet.Security.OpenIdConnect - the Audience?

风流意气都作罢 提交于 2019-11-30 20:43:05

Does AspNet.Security.OpenIdConnect.Server require the auth and resource to be in the same server?

No, you can of course separate the two roles.

As you've already figured out, if you don't explicitly specify it, the authorization server has no way to determine the destination/audience of an access token, which is issued without the aud claim required by default by the OAuth2 bearer middleware.

Solving this issue is easy: just call ticket.SetResources(resources) when creating the authentication ticket and the authorization server will know exactly which value(s) (i.e resource servers/API) it should add in the aud claim(s).

app.UseOpenIdConnectServer(options =>
{
    // Force the OpenID Connect server middleware to use JWT tokens
    // instead of the default opaque/encrypted token format used by default.
    options.AccessTokenHandler = new JwtSecurityTokenHandler();
});

public override Task HandleTokenRequest(HandleTokenRequestContext context)
{
    if (context.Request.IsPasswordGrantType())
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
        identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "unique identifier");

        var ticket = new AuthenticationTicket(
            new ClaimsPrincipal(identity),
            new AuthenticationProperties(),
            context.Options.AuthenticationScheme);

        // Call SetResources with the list of resource servers
        // the access token should be issued for.
        ticket.SetResources("resource_server_1");

        // Call SetScopes with the list of scopes you want to grant.
        ticket.SetScopes("profile", "offline_access");

        context.Validate(ticket);
    }

    return Task.FromResult(0);
}     

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    Audience = "resource_server_1",
    Authority = "http://localhost:61854"
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!