czioutas
czioutas

Reputation: 1068

How to use Token and Identity Authorization on resource?

I have a WEB Api that uses User accounts for registration etc and also Tokens. Now I want all the end points to be secured using both Token (JWT bearer) and Identity. So a user cant only have a valid Token but he must also be logged in. When I use [Authorize(Policy = "Bearer")] I get Token authorisation and when I used [Authorize] I get identity authorisation, how can I combine both? I would I assume I can do [Authorize(Policy = "Bearer, Identity")] (Based on the Roles logic) but I get an error ofcourse that the policy doesnt exist. Is there a way to implement this?

Repo: https://github.com/drakoumel/DatacircleAPI

Upvotes: 1

Views: 759

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141492

When I use [Authorize(Policy = "Bearer")] I get Token authorisation and when I used [Authorize] I get identity authorisation, how can I combine both? [sic]

Set the ActiveAuthenticationSchemes property. It takes a comma separated list of scheme names. Here is an example that activates the cookie middleware that Identity uses and the bearer (token) middleware.

[Authorize(ActiveAuthenticationSchemes = "Bearer, Identity.Application")]

Both the bearer and the cookie middleware will run and have a chance to create and append an identity for the current user.

Remarks:

You can activate whatever authentication schemes you need. The default scheme names are in the Identity and Authentication namespaces. E.g.

Microsoft.AspNetCore.Authentication.JwtBearer
    .JwtBearerDefaults.AuthenticationScheme // "Bearer"

Microsoft.AspNetCore.Identity
    .IdentityCookieOptions.ApplicationCookie // "Identity.Application"

...

See also:

Upvotes: 2

Related Questions