Search code examples
c#.netasp.net-identitybearer-token.net-8.0

Can I set an IssuerSigningKey with Identity API Endpoints in a .NET 8 Web API using AddBearerToken?


I've developed a web API using the new Identity API endpoints feature.

In my Next.js frontend, I've implemented protected pages, accessible only to authenticated users. To enable user access to these protected pages, I've created a verifyAuth function that validates tokens using a secret key:

export const verifyAuth = async (token: string) => {
  console.log("Token: ", token);

  try {
    const verified = await jwtVerify(
      token,
      new TextEncoder().encode(getJwtSecretKey())
    );

    return verified.payload as UserJwtPayload;
  } catch (error: any) {
    throw new Error("Your token has expired. Please login again.");
  }
};

But to do this I have to sign the token with the secret key in my web api first. If you're not using Identity API Endpoints, the signing process is straightforward, as shown here in the Configure Identity and JWT section, where you can set an IssuerSigningKey.

For those using Identity API Endpoints, a different approach is required. Instead of calling AddJwtBearer in your program.cs, you need to use AddBearerToken:

// Authentication
builder.Services.AddAuthentication().AddBearerToken();

// Authorization with Identity endpoints
builder.Services.AddAuthorizationBuilder();
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<DatabaseContext>();

The AddBearerToken method can take options, and I stumbled upon the BearerTokenProtector option in the Microsoft documentation. However, I'm uncertain about how to set a signing key within this context.

So, my question is, where should I set the IssuerSigningKey in this scenario? If my approach is flawed, what's the correct way to address this issue? Any guidance or corrections would be greatly appreciated.


Solution

  • The token issued by the Identity API is not a JWT. It's a proprietary opaque token and you can't inspect it on the client side. This token is meant for a first-party authentication/authorization scenario (client, server, and authentication are under your control), so the security context is slightly different from the third-party scenario