简体   繁体   English

如何使用JWT令牌进行授权

[英]How to Authorize Using JWT token

I have a web api end point that give me JWT token. 我有一个Web API端点,可以给我JWT令牌。 It is not an fully authorization server. 它不是完全授权服务器。 It just can generate a JWT token. 它只是可以生成一个JWT令牌。

Now I have another web app written in aspnet core. 现在,我有另一个用aspnet核心编写的Web应用程序。 In which inside the startup.cs I have added the following lines so that I can authorize using the JWT token I receive 我在startup.cs中添加了以下几行,以便可以使用收到的JWT令牌进行授权

            services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(configureOptions =>
        {...});

I also have a login form (in the web app) where user enters username and password that I send to web api and get the token. 我也有一个登录表单(在Web应用程序中),用户在其中输入我发送到Web api并获取令牌的用户名和密码。 And to protect any controller in the web app I just use the [Authorize] attribute. 为了保护Web应用程序中的任何控制器,我只需使用[Authorize]属性。

Everything works fine until the token expires. 一切工作正常,直到令牌过期。 The token is very short lived but it does come with a refresh token. 该令牌寿命很短,但确实带有刷新令牌。

My question is that , how can I detect that the Token (from the web api) is now expired and I need to get a new one using the refresh token. 我的问题是,如何检测令牌(来自Web api)现在已过期,我需要使用刷新令牌来获取一个新令牌。 I know that in javascript world I can intercept the http request and renew the token with the refresh token. 我知道在javascript世界中,我可以截获http请求并使用刷新令牌续订令牌。

But how do I do this in an aspnet core client app?? 但是,如何在aspnet核心客户端应用程序中执行此操作?

(NOTE: I do not want to use any authentication server like IdentityServer4 etc) (注意:我不想使用任何身份验证服务器,例如IdentityServer4等)

Thank you in advance!! 先感谢您!!

You can totally achieve what you want: 您可以完全实现您想要的:

services
    .AddAuthentication()
    .AddJwtBearer("Firebase", options =>
    {
        options.Authority = "https://securetoken.google.com/my-firebase-project"
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "my-firebase-project"
            ValidateAudience = true,
            ValidAudience = "my-firebase-project"
            ValidateLifetime = true
        };
    })
    .AddJwtBearer("Custom", options =>
    {
        // Configuration for your custom
        // JWT tokens here
    });

services
    .AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase", "Custom")
            .Build();
    });

Let's go through the differences between your code and that one. 让我们看一下您的代码与该代码之间的区别。

AddAuthentication has no parameter If you set a default authentication scheme, then on every single request the authentication middleware will try to run the authentication handler associated with the default authentication scheme. AddAuthentication没有参数如果您设置了默认身份验证方案,则在每个单个请求中,身份验证中间件都会尝试运行与默认身份验证方案关联的身份验证处理程序。 Since we now have two opssible authentication schemes, there's no point in running one of them. 由于我们现在有两种可行的身份验证方案,因此运行其中一种是没有意义的。

Use another overload of AddJwtBearer Every single AddXXX method to add an authentication has several overloads: 使用AddJwtBearer的另一个重载每个添加身份验证的AddXXX方法都有几个重载:

One where the default authentication scheme associated with the authentication method is used, as you can see here for cookies authentication One where you pass, in addition to the configuration of the options, the name of the authentication scheme, as on this overload Now, because you use the same authentication method twice but authentication schemes must be unique, you need to use the second overload. 如其中所示,其中使用了与身份验证方法关联的默认身份验证方案,用于cookie身份验证。除了选项的配置之外,还通过了一个身份验证方案的名称,就像在此重载上一样。您两次使用相同的身份验证方法,但是身份验证方案必须唯一,您需要使用第二个重载。

Update the default policy Since the requests won't be authenticated automatically anymore, putting [Authorize] attributes on some actions will result in the requests being rejected and an HTTP 401 will be issued. 更新默认策略由于将不再自动验证请求,因此在某些操作上添加[Authorize]属性将导致请求被拒绝并发出HTTP 401。

Since that's not what we want because we want to give the authentication handlers a chance to authenticate the request, we change the default policy of the authorization system by indicating both the Firebase and Custom authentication schemes should be tried to authenticate the request. 由于这不是我们想要的,因为我们希望给身份验证处理程序一个机会来验证请求,因此我们通过指示应同时尝试Firebase和Custom身份验证方案来验证请求来更改授权系统的默认策略。

That doesn't prevent you from being more restrictive on some actions; 但这并不妨碍您对某些动作有更多的限制; the [Authorize] attribute has an AuthenticationSchemes property that allows you to override which authentication schemes are valid. [Authorize]属性具有AuthenticationSchemes属性,该属性使您可以覆盖哪些身份验证方案有效。

If you have more complex scenarios, you can make use of policy-based authorization. 如果您有更复杂的方案,则可以使用基于策略的授权。 I find the official documentation is great. 我发现官方文档很棒。

Let's imagine some actions are only available to JWT tokens issued by Firebase and must have a claim with a specific value; 假设某些操作仅适用于Firebase发行的JWT令牌,并且必须具有特定值的声明; you could do it this way: 您可以这样进行:

services
    .AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase", "Custom")
            .Build();

        options.AddPolicy("FirebaseAdministrators", new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase")
            .RequireClaim("role", "admin")
            .Build());
    });

You could then use [Authorize(Policy = "FirebaseAdministrators")] on some actions. 然后,您可以对某些操作使用[Authorize(Policy = "FirebaseAdministrators")]

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

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