简体   繁体   English

如何使用 Bearer 令牌在 Z2567A5EC9705EB7AC2C984033E 站点中授权我的 web api controller?

[英]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.我有一个具有标准登录功能的 Asp.Net MVC 核心应用程序。 I have added a web api controller to my project.我在我的项目中添加了 web api controller。 I want to authorize the web api controller with bearer token.我想用不记名令牌授权 web api controller。 But only this controller.但只有这个 controller。 The rest of my website must work the way it is now.我网站的 rest 必须按照现在的方式工作。 If I have it set in my startup.cs, I mean Bearer token functionality, that works but it destroy my website.如果我在我的 startup.cs 中设置了它,我的意思是不记名令牌功能,它可以工作,但它会破坏我的网站。 I then get error 401. Is it possible to authorize only a controller with bearer token?然后我收到错误 401。是否可以只授权带有不记名令牌的 controller?

Rex's comment is accurate.雷克斯的评论是准确的。 I'm including a code sample that will get you what you want (assuming JWT).我包含一个代码示例,它将为您提供所需的内容(假设 JWT)。

Startup.cs启动.cs

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

Your controller你的 controller

[Authorize(ADD OPTIONAL USER SCOPES/POLICIES)]

Add this attribute and pass-in optional scopes to limit access to specific users.添加此属性并传入可选范围以限制对特定用户的访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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