First, chat at the beginning

This article is the last article of the ASP.NET Core 3.0 gRPC research study . Later, in actual use, some experience may be sent. This article focuses on ASP.NET Core’s own authentication and authorization and gRPC access. The authentication method uses the current mainstream JWT combined with IdentityServer4.

Second, the server configuration

We first need to configure authentication and authorization on the server side.

Configuration

1. Start the IdentityServer4 address first:
http://localhost:5000

2. Install the Jwt component for the gRPC project:Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.0.0

3. Configure authentication and authorization services for the gRPC project

In the ConfigureServices method of the Startup class, configure the following code

services.AddAuthorization(options =>
{
    options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy =>
    {
        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
        policy.RequireClaim("sub");
    });
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;
        options.Audience = "grpc1";
    });

4. Enable authentication and authorization middleware

In the Configure method of the Startup class, configure the following code

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

Please pay attention to the middleware order

5. Enable authorization for the gRPC service

Us on SuckingCat method LuCatService, plus [Authorize]characteristics, just as in MVC.

ASP.NET_Core_3.0_gRPC_authentication_and_authorization_0.png

test

The running client invokes the server to test, and finds that the server returns the authorization failure, and the client also obtains an error. This proves that our server configuration is no problem.

ASP.NET_Core_3.0_gRPC_authentication_and_authorization_1.png

Three. Client configuration

Configuration

The client first needs to request a token from IdentityServer and then pass it in when the gRPC service is called, just like the HTTP Api call.

1. The client project mounting assembly IdentityModelobtained based packages and IdentityServer interaction of HttpClient.

2. Get Token

// discover endpoints from metadata
var client = new HttpClient();

var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
if (disco.IsError)
{
    Console.WriteLine(disco.Error);
    return;
}

// request token
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
    Address = disco.TokenEndpoint,
    ClientId = "ro.client",
    ClientSecret = "secret",

    UserName = "alice",
    Password = "password",
    Scope = "grpc1"
});

if (tokenResponse.IsError)
{
    Console.WriteLine(tokenResponse.Error);
    return;
}

Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");

3. Set the Token for the gRPC client request

Like the HTTP Api call, gRPC is also placed on the head.

var headers = new Metadata {{"Authorization", $"Bearer {tokenResponse.Json["access_token"]}"}};

var catClient = new LuCat.LuCatClient(channel);
var catReply = await catClient.SuckingCatAsync(new Empty(), headers);

Mainly in the call SuckingCatAsyncwhen the method, passing in the header.

test

ASP.NET_Core_3.0_gRPC_authentication_and_authorization_2.png

You can see that the call was made successfully.

End

The code address used in this article:
Demo

gRPC in Asp.Net Core :
Official Documentation


.NET Core Official Tutorial

Orignal link:https://www.cnblogs.com/stulzq/p/11897628.html