简体   繁体   中英

How can I authorize my web api controller in my web site with Bearer token?

I have an Asp.Net MVC core application with standard login functionality. I have added a web api controller to my project. I want to authorize the web api controller with bearer token. But only this controller. The rest of my website must work the way it is now. If I have it set in my startup.cs, I mean Bearer token functionality, that works but it destroy my website. I then get error 401. Is it possible to authorize only a controller with bearer token?

Rex's comment is accurate. I'm including a code sample that will get you what you want (assuming JWT).

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
     services
          .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddJwtBearer(options =>
           {
            options.TokenValidationParameters = new TokenValidationParameters
           {
            // omitted
           };
     });

Your controller

[Authorize(ADD OPTIONAL USER SCOPES/POLICIES)]

Add this attribute and pass-in optional scopes to limit access to specific users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM