8.NET中GRPC如何做权限校验

 

服务端

新建一个项目GrpcToken

安装包:

Grpc.AspNetCore

Microsoft.AspNetCore.Authentication.JwtBearer

Microsoft.AspNetCore.Grpc.JsonTranscoding

Microsoft.AspNetCore.Grpc.Swagger

Microsoft.AspNetCore.OpenApi

Swashbuckle.AspNetCore

 

JWT配置类:

/// <summary>
/// JWT配置类
/// </summary>
public class JwtTokenOption
{
    /// <summary>
    /// Token 过期时间,默认为60分钟
    /// </summary>
    public int TokenExpireTime { get; set; } = 60;
    /// <summary>
    /// 接收人
    /// </summary>
    public string Audience { get; set; }
    /// <summary>
    /// 秘钥
    /// </summary>
    public string SecurityKey { get; set; }
    /// <summary>
    /// 签发人
    /// </summary>
    public string Issuer { get; set; }
    
}

 

添加一个类,用于生成Token

/// <summary>
/// Jwt token 服务
/// </summary>
public class GenerateTokenService
{
    private readonly JwtTokenOption _jwtTokenOption;
    
    /// <summary>
    /// 注入服务
    /// </summary>
    /// <param name="monitor"></param>
    public GenerateTokenService(IOptionsMonitor<JwtTokenOption> monitor)
    {
        _jwtTokenOption = monitor.CurrentValue;
    }

    /// <summary>
    /// 生成Token
    /// </summary>
    /// <param name="dto">当前登录人的用户</param>
    /// <returns></returns>
    public string GenerateToken(UserDto? dto)
    {
        // 保存用户个人信息(不要放用户非常私密的信息)
        var claims = new[]
        {
            new Claim("NickName", dto.Nickname),
            new Claim("UserName",dto.Username),
            new Claim("RoleName",dto.RoleName),
            new Claim("RoleId",dto.RoleId.ToString()),
            new Claim("UserId",dto.Id.ToString())
        };

       
        var rsa = RSA.Create();
        rsa.ImportRSAPrivateKey(Convert.FromBase64String(_jwtTokenOption.SecurityKey),out _);
        var credential = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256);
        
        
        // payload 中的信息声明
        var jwtSecurityToken = new JwtSecurityToken(
            issuer:_jwtTokenOption.Issuer,
            audience:_jwtTokenOption.Audience,
            claims:claims,
            expires:DateTime.Now.AddMinutes(_jwtTokenOption.TokenExpireTime),
            signingCredentials:credential
        );

        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        return token;
    }
}

appsettings.Development.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "JwtTokenOption": {
    "TokenExpireTime": 60000,
    "Audience": "任我行",
    "Issuer": "任我行",
    // 如果RSA加密算法,则下面存放的是RSA的私钥(我这里用的RSA的私钥)
    "SecurityKey": "MIIEpAIBAAKCAQEA4cNvbucBVhIAzJMv/3aYYHlaojwdnGXdvEW3Qg8VhRgwJZyfRqEpJoRozwUluOHi7ayyerjiKm3DAm6nJ/qA1teq+jSAtspcyrliL2msCgqgCISpsY35hlKWXfNRQHqEjc6dL7QEmKsLqo4RclDZI5LHWYDWDprCDDFbHRGuY8vCgFYd4Y1wpEGzJ3JIL2VrBszIAB/Yn8LAFXJMZWmFlxRmDnWS9SuRc3XU9eMPK0L3rFeAVwMG/hqdo5KyrgseNCB3xUdxN44A1HMcTDB9DEPeTu8tCQoSki6gB22rxBO4ucvcJXKAtjJTQBY6QF52te5FLBMnhejxfhq6hhcq9QIDAQABAoIBAQDI61p/s5yv0ePeLNvZmd0wdq/flGqx5sJ4rP7UDoKTaZxnzMS/YewyeEKigy04JegEp95Lc8DsC7Uys/GVlc4V5egnNpSamOwOCwBDu+K9KQmVqyMufnDkRxnFUSctoBvZ7FhdvPMeP5NpXXhPaX5lt1os4IkghEBQA5jX/QVbj65UJEiG1x5/aMUeyhuEpKfxRvz1ZzeSSJsRMcThLd4hsY7TRwlGbPW8UVpTfPfAW89vKSGgvbBZ03NFofpU7b/HgZ7qrDa707IGRxLfejaFRxW1ua69pl+O86bu5dKFHi8OJwrjSAj2pQxdyV26ThW6xvNYdUya+Ri7iqzvD5hdAoGBAPfvDbcpVpycoU4HB54sNzz6W/1RIgnDL5KcGtBCUh8AKr/yE8QGbdKQheyfJWGlObQWXSAeQAHp5AYy+zookw4nkngpKUFAO/Uxfkkf1UB3QdGC/gsbB4b5vhWmwQtqN6d90TlwucvNplpoSe5HqjUcf86DctoMhw0gi7rr5zhLAoGBAOkbu6ZfBveJPQev2auDvl8KhvcFgrMuXwlsB68/4HtSVTQy33f55KM7udEQSML+faqdFycCU1hV3QVQcs/2oGaUulGZSUvZugR296WAUSZ4tUvPDnjnlWpt48nJNWM38PNLScOMhExvBwFwD30eaZ0G5kZhTsKD7BL3mIDcZ6G/AoGBALx5gZenWSwc9ZJ3TZc0TZmRSLS9JH7/Xf65pLiEciEW42ifAd+Wc44KR4SlRqmADOmVxp1P4aCSyMDdqJWBmqi79GBcCfyMdAfk4/d6t4YWIna+eZi/p204FQQoi7+9sykkQBTGWLdRUhCQDwOQfxd43r+CtaCEvXWBNDeYdWEZAoGAEqRGIGrvCrKt78RvWtkBS2ZzHqQRLLUjooRCJRCtqg8Og0siNd0FHMy08nQj7XwenptLc7Iq6iCLuVYSqHDnqOxx7f6dLvStfJfq/BBD7RiwHuzjEmYqu8Un90Yg/9tEaKB3uKyvE9G5NLM6ed4JwiYAGlbDzqhwI6ArUPrPSs8CgYBOOmAe3r9+xLrLNnvlCdhDchw5gn8dknNcjguy3czhL4lOlMzEetod3l45ngA7dAeuOz6Tvz/+7ljVvIyFG1fzbsz7PQ0JYQqPWFaROGq3Umg2R/ba3uggya6MgJOvP2Vko0i0nuw2fmLp6vqfnVDyFYhF864iWg567NeywjHoOQ=="
  }
}

 

 

在文件夹google/api里面添加两个文件:http.proto 、annotations.proto 

http.proto 是一个用于定义 HTTP 协议的 Protocol Buffers 文件。

// Copyright 2019 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

syntax = "proto3";

package google.api;

option cc_enable_arenas = true;
option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations";
option java_multiple_files = true;
option java_outer_classname = "HttpProto";
option java_package = "com.google.api";
option objc_class_prefix = "GAPI";

// Defines the HTTP configuration for an API service. It contains a list of
// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
// to one or more HTTP REST API methods.
message Http {
  // A list of HTTP configuration rules that apply to individual API methods.
  //
  // **NOTE:** All service configuration rules follow "last one wins" order.
  repeated HttpRule rules = 1;

  // When set to true, URL path parameters will be fully URI-decoded except in
  // cases of single segment matches in reserved expansion, where "%2F" will be
  // left encoded.
  //
  // The default behavior is to not decode RFC 6570 reserved characters in multi
  // segment matches.
  bool fully_decode_reserved_expansion = 2;
}

// # gRPC Transcoding
//
// gRPC Transcoding is a feature for mapping between a gRPC method and one or
// more HTTP REST endpoints. It allows developers to build a single API service
// that supports both gRPC APIs and REST APIs. Many systems, including [Google
// APIs](https://github.com/googleapis/googleapis),
// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC
// Gateway](https://github.com/grpc-ecosystem/grpc-gateway),
// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature
// and use it for large scale production services.
//
// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies
// how different portions of the gRPC request message are mapped to the URL
// path, URL query parameters, and HTTP request body. It also controls how the
// gRPC response message is mapped to the HTTP response body. `HttpRule` is
// typically specified as an `google.api.http` annotation on the gRPC method.
//
// Each mapping specifies a URL path template and an HTTP method. The path
// template may refer to one or more fields in the gRPC request message, as long
// as each field is a non-repeated field with a primitive (non-message) type.
// The path template controls how fields of the request message are mapped to
// the URL path.
//
// Example:
//
//     service Messaging {
//       rpc GetMessage(GetMessageRequest) returns (Message) {
//         option (google.api.http) = {
//             get: "/v1/{name=messages/*}"
//         };
//       }
//     }
//     message GetMessageRequest {
//       string name = 1; // Mapped to URL path.
//     }
//     message Message {
//       string text = 1; // The resource content.
//     }
//
// This enables an HTTP REST to gRPC mapping as below:
//
// HTTP | gRPC
// -----|-----
// `GET /v1/messages/123456`  | `GetMessage(name: "messages/123456")`
//
// Any fields in the request message which are not bound by the path template
// automatically become HTTP query parameters if there is no HTTP request body.
// For example:
//
//     service Messaging {
//       rpc GetMessage(GetMessageRequest) returns (Message) {
//         option (google.api.http) = {
//             get:"/v1/messages/{message_id}"
//         };
//       }
//     }
//     message GetMessageRequest {
//       message SubMessage {
//         string subfield = 1;
//       }
//       string message_id = 1; // Mapped to URL path.
//       int64 revision = 2;    // Mapped to URL query parameter `revision`.
//       SubMessage sub = 3;    // Mapped to URL query parameter `sub.subfield`.
//     }
//
// This enables a HTTP JSON to RPC mapping as below:
//
// HTTP | gRPC
// -----|-----
// `GET /v1/messages/123456?revision=2&sub.subfield=foo` |
// `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield:
// "foo"))`
//
// Note that fields which are mapped to URL query parameters must have a
// primitive type or a repeated primitive type or a non-repeated message type.
// In the case of a repeated type, the parameter can be repeated in the URL
// as `...?param=A&param=B`. In the case of a message type, each field of the
// message is mapped to a separate parameter, such as
// `...?foo.a=A&foo.b=B&foo.c=C`.
//
// For HTTP methods that allow a request body, the `body` field
// specifies the mapping. Consider a REST update method on the
// message resource collection:
//
//     service Messaging {
//       rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
//         option (google.api.http) = {
//           patch: "/v1/messages/{message_id}"
//           body: "message"
//         };
//       }
//     }
//     message UpdateMessageRequest {
//       string message_id = 1; // mapped to the URL
//       Message message = 2;   // mapped to the body
//     }
//
// The following HTTP JSON to RPC mapping is enabled, where the
// representation of the JSON in the request body is determined by
// protos JSON encoding:
//
// HTTP | gRPC
// -----|-----
// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id:
// "123456" message { text: "Hi!" })`
//
// The special name `*` can be used in the body mapping to define that
// every field not bound by the path template should be mapped to the
// request body.  This enables the following alternative definition of
// the update method:
//
//     service Messaging {
//       rpc UpdateMessage(Message) returns (Message) {
//         option (google.api.http) = {
//           patch: "/v1/messages/{message_id}"
//           body: "*"
//         };
//       }
//     }
//     message Message {
//       string message_id = 1;
//       string text = 2;
//     }
//
//
// The following HTTP JSON to RPC mapping is enabled:
//
// HTTP | gRPC
// -----|-----
// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id:
// "123456" text: "Hi!")`
//
// Note that when using `*` in the body mapping, it is not possible to
// have HTTP parameters, as all fields not bound by the path end in
// the body. This makes this option more rarely used in practice when
// defining REST APIs. The common usage of `*` is in custom methods
// which don't use the URL at all for transferring data.
//
// It is possible to define multiple HTTP methods for one RPC by using
// the `additional_bindings` option. Example:
//
//     service Messaging {
//       rpc GetMessage(GetMessageRequest) returns (Message) {
//         option (google.api.http) = {
//           get: "/v1/messages/{message_id}"
//           additional_bindings {
//             get: "/v1/users/{user_id}/messages/{message_id}"
//           }
//         };
//       }
//     }
//     message GetMessageRequest {
//       string message_id = 1;
//       string user_id = 2;
//     }
//
// This enables the following two alternative HTTP JSON to RPC mappings:
//
// HTTP | gRPC
// -----|-----
// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id:
// "123456")`
//
// ## Rules for HTTP mapping
//
// 1. Leaf request fields (recursive expansion nested messages in the request
//    message) are classified into three categories:
//    - Fields referred by the path template. They are passed via the URL path.
//    - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They are passed via the HTTP
//      request body.
//    - All other fields are passed via the URL query parameters, and the
//      parameter name is the field path in the request message. A repeated
//      field can be represented as multiple query parameters under the same
//      name.
//  2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL query parameter, all fields
//     are passed via URL path and HTTP request body.
//  3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP request body, all
//     fields are passed via URL path and URL query parameters.
//
// ### Path template syntax
//
//     Template = "/" Segments [ Verb ] ;
//     Segments = Segment { "/" Segment } ;
//     Segment  = "*" | "**" | LITERAL | Variable ;
//     Variable = "{" FieldPath [ "=" Segments ] "}" ;
//     FieldPath = IDENT { "." IDENT } ;
//     Verb     = ":" LITERAL ;
//
// The syntax `*` matches a single URL path segment. The syntax `**` matches
// zero or more URL path segments, which must be the last part of the URL path
// except the `Verb`.
//
// The syntax `Variable` matches part of the URL path as specified by its
// template. A variable template must not contain other variables. If a variable
// matches a single path segment, its template may be omitted, e.g. `{var}`
// is equivalent to `{var=*}`.
//
// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL`
// contains any reserved character, such characters should be percent-encoded
// before the matching.
//
// If a variable contains exactly one path segment, such as `"{var}"` or
// `"{var=*}"`, when such a variable is expanded into a URL path on the client
// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The
// server side does the reverse decoding. Such variables show up in the
// [Discovery
// Document](https://developers.google.com/discovery/v1/reference/apis) as
// `{var}`.
//
// If a variable contains multiple path segments, such as `"{var=foo/*}"`
// or `"{var=**}"`, when such a variable is expanded into a URL path on the
// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded.
// The server side does the reverse decoding, except "%2F" and "%2f" are left
// unchanged. Such variables show up in the
// [Discovery
// Document](https://developers.google.com/discovery/v1/reference/apis) as
// `{+var}`.
//
// ## Using gRPC API Service Configuration
//
// gRPC API Service Configuration (service config) is a configuration language
// for configuring a gRPC service to become a user-facing product. The
// service config is simply the YAML representation of the `google.api.Service`
// proto message.
//
// As an alternative to annotating your proto file, you can configure gRPC
// transcoding in your service config YAML files. You do this by specifying a
// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same
// effect as the proto annotation. This can be particularly useful if you
// have a proto that is reused in multiple services. Note that any transcoding
// specified in the service config will override any matching transcoding
// configuration in the proto.
//
// Example:
//
//     http:
//       rules:
//         # Selects a gRPC method and applies HttpRule to it.
//         - selector: example.v1.Messaging.GetMessage
//           get: /v1/messages/{message_id}/{sub.subfield}
//
// ## Special notes
//
// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the
// proto to JSON conversion must follow the [proto3
// specification](https://developers.google.com/protocol-buffers/docs/proto3#json).
//
// While the single segment variable follows the semantics of
// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String
// Expansion, the multi segment variable **does not** follow RFC 6570 Section
// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion
// does not expand special characters like `?` and `#`, which would lead
// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding
// for multi segment variables.
//
// The path variables **must not** refer to any repeated or mapped field,
// because client libraries are not capable of handling such variable expansion.
//
// The path variables **must not** capture the leading "/" character. The reason
// is that the most common use case "{var}" does not capture the leading "/"
// character. For consistency, all path variables must share the same behavior.
//
// Repeated message fields must not be mapped to URL query parameters, because
// no client library can support such complicated mapping.
//
// If an API needs to use a JSON array for request or response body, it can map
// the request or response body to a repeated field. However, some gRPC
// Transcoding implementations may not support this feature.
message HttpRule {
  // Selects a method to which this rule applies.
  //
  // Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
  string selector = 1;

  // Determines the URL pattern is matched by this rules. This pattern can be
  // used with any of the {get|put|post|delete|patch} methods. A custom method
  // can be defined using the 'custom' field.
  oneof pattern {
    // Maps to HTTP GET. Used for listing and getting information about
    // resources.
    string get = 2;

    // Maps to HTTP PUT. Used for replacing a resource.
    string put = 3;

    // Maps to HTTP POST. Used for creating a resource or performing an action.
    string post = 4;

    // Maps to HTTP DELETE. Used for deleting a resource.
    string delete = 5;

    // Maps to HTTP PATCH. Used for updating a resource.
    string patch = 6;

    // The custom pattern is used for specifying an HTTP method that is not
    // included in the `pattern` field, such as HEAD, or "*" to leave the
    // HTTP method unspecified for this rule. The wild-card rule is useful
    // for services that provide content to Web (HTML) clients.
    CustomHttpPattern custom = 8;
  }

  // The name of the request field whose value is mapped to the HTTP request
  // body, or `*` for mapping all request fields not captured by the path
  // pattern to the HTTP body, or omitted for not having any HTTP request body.
  //
  // NOTE: the referred field must be present at the top-level of the request
  // message type.
  string body = 7;

  // Optional. The name of the response field whose value is mapped to the HTTP
  // response body. When omitted, the entire response message will be used
  // as the HTTP response body.
  //
  // NOTE: The referred field must be present at the top-level of the response
  // message type.
  string response_body = 12;

  // Additional HTTP bindings for the selector. Nested bindings must
  // not contain an `additional_bindings` field themselves (that is,
  // the nesting may only be one level deep).
  repeated HttpRule additional_bindings = 11;
}

// A custom pattern is used for defining custom HTTP verb.
message CustomHttpPattern {
  // The name of this custom HTTP verb.
  string kind = 1;

  // The path matched by this custom verb.
  string path = 2;
}
View Code

 

annotations.proto 是一个用于定义注解的 Protocol Buffers 文件。

// Copyright (c) 2015, Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

syntax = "proto3";

package google.api;

import "google/api/http.proto";
import "google/protobuf/descriptor.proto";

option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations";
option java_multiple_files = true;
option java_outer_classname = "AnnotationsProto";
option java_package = "com.google.api";
option objc_class_prefix = "GAPI";

extend google.protobuf.MethodOptions {
  // See `HttpRule`.
  HttpRule http = 72295728;
}
View Code

 

在文件夹Protos中添加auth.proto、hello.proto

syntax = "proto3";
option csharp_namespace = "GrpcToken";
package auth;
import "google/protobuf/empty.proto";
import "google/api/annotations.proto";


// 获取Token请求参数
message TokenRequest{
    // 用户名
    string user_name=1;
    // 密码
    string pwd=2;
}

// Token 响应
message TokenResponse{
    // JWT 令牌
    string access_token=1;
}

// Token服务
service TokenService{
    // 获取Token
    rpc GetToken(TokenRequest) returns (TokenResponse){
        option(google.api.http)={ 
            get: '/token/GetToken/{user_name}'
            // http://localhost:5015/token/gettoken/admin&pwd=123
        };
    };
}
syntax = "proto3";
option csharp_namespace = "GrpcToken";
package hello;
import "google/protobuf/empty.proto";
import "google/api/annotations.proto";

// 查询用户响应
message HelloResponse{
    string msg = 1;
}

// 请求用户实体
message PostUserDto{
    // 用户名
    string user_name=1;
    // 密码
    string pwd=2;
}

// Hello 服务
service HelloService{
    // 查询用户方法
    rpc HelloUser(google.protobuf.Empty) returns (HelloResponse){
        option(google.api.http)={
            post:'/hello/user'
        };
    }

    // 添加用户
    rpc PostUser(PostUserDto) returns (PostUserDto){
        option(google.api.http)={
            post:'/hello/post/user',
            body: '*'
        };
    }
}

 

 

 

生成后查看GrpcToken.csproj是否有生成

 <ItemGroup>
        <PackageReference Include="Grpc.AspNetCore" Version="2.56.0" />
        <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Grpc.JsonTranscoding" Version="7.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Grpc.Swagger" Version="0.3.0" />
        <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.5" />
        <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
        <ProtoBuf Include="Protos/auth.proto" GrpcService="Server" />
<ProtoBuf Include="Protos\hello.proto" GrpcService="Server" /> </ItemGroup>

 

在Grpc文件夹中添加类TokenServiceGrpc.cs 、HelloServiceGrpc.cs

public class TokenServiceGrpc:TokenService.TokenServiceBase
{
    private readonly GenerateTokenService _tokenService;

    public TokenServiceGrpc(GenerateTokenService tokenService)
    {
        _tokenService = tokenService;
    }

    /// <summary>
    /// 模拟登录
    /// </summary>
    /// <param name="request"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task<TokenResponse> GetToken(TokenRequest request, ServerCallContext context)
    {
        TokenResponse response = new();
        if (request.UserName == "admin" && request.Pwd=="123")
        {
            response.AccessToken = _tokenService.GenerateToken(new()
            {
                Username = "admin",
                Id = 1,
                RoleId = 1,
                RoleName = "管理员",
                Nickname = "誉尚学"
            });
        }

        return Task.FromResult(response);
    }

    
}
public class HelloServiceGrpc: HelloService.HelloServiceBase
{
    [Authorize]
    public override Task<HelloResponse> HelloUser(Empty request, ServerCallContext context)
    {
        var userClaims = context.GetHttpContext().User.Claims;

        var userName = userClaims.FirstOrDefault(p=>p.Type == "UserName");

        HelloResponse response = new();
        response.Msg = userName+"访问成功";
        return Task.FromResult(response);
    }

    public override Task<PostUserDto> PostUser(PostUserDto request, ServerCallContext context)
    {
        return Task.FromResult(request);
    }
}

 

 

Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<GenerateTokenService>();


builder.Services.AddControllers();

#region JWT认证

var jwtOption = builder.Configuration.GetSection("JwtTokenOption");
builder.Services.Configure<JwtTokenOption>(jwtOption);
JwtTokenOption jwtTokenOption = jwtOption.Get<JwtTokenOption>()!;
// 添加认证服务
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(p =>
    {
        var rsa = RSA.Create();
        rsa.ImportRSAPrivateKey(Convert.FromBase64String(jwtTokenOption.SecurityKey), out _);
        SecurityKey securityKey = new RsaSecurityKey(rsa);


        // 校验JWT是否合法
        p.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidAlgorithms = new string[] { "RS256" },
            ValidateIssuer = true, //是否验证Issuer
            ValidateAudience = true, //是否验证Audience
            ValidateLifetime = true, //是否验证失效时间
            ClockSkew = TimeSpan.Zero, //时钟脉冲相位差
            ValidateIssuerSigningKey = true, //是否验证SecurityKey
            ValidAudience = jwtTokenOption.Audience, //Audience
            ValidIssuer = jwtTokenOption.Issuer, //Issuer,这两项和前面签发jwt的设置一致
            IssuerSigningKey = securityKey, //拿到SecurityKey
        };
    });
builder.Services.AddAuthorization();

#endregion

// 转换为JSON
#if DEBUG
builder.Services.AddGrpc().AddJsonTranscoding();
builder.Services.AddSwaggerGen(c =>
{
    var filePath = Path.Combine(AppContext.BaseDirectory,
        $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
    c.IncludeXmlComments(filePath);
    c.IncludeGrpcXmlComments(filePath, includeControllerXmlComments: true);

}).AddGrpcSwagger();
builder.WebHost.ConfigureKestrel(p =>
{
    p.ConfigureEndpointDefaults(o =>
    {
        o.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2;
    });

});

#else
builder.Services.AddGrpc();
builder.WebHost.ConfigureKestrel(p => {
    p.ConfigureEndpointDefaults(o => {
        o.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
    });
    
});
#endif



var app = builder.Build();

#if DEBUG
app.UseSwagger();
app.UseSwaggerUI();
#endif

app.UseAuthentication();//认证
app.UseAuthorization();//授权
app.MapControllers();

app.MapGrpcService<TokenServiceGrpc>();

  app.MapGrpcService<HelloServiceGrpc>();



app.MapGet("token",([FromServices] GenerateTokenService tokenService) => tokenService.GenerateToken(new()
{
    Username = "admin",
    Id = 1,
    RoleId = 1,
    RoleName = "管理员",
    Nickname = "誉尚学"
}));

app.MapGet("test", [Authorize]() => "访问成功");

app.Run();

在GrpcToken.csproj添加

<PropertyGroup>
        <TargetFramework>net7.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <GenerateDocumentationFile>true</GenerateDocumentationFile>
    </PropertyGroup>

或者:项目->属性->勾上  生成包含API文档的文件

 

 

客户端

还是用之前的GrpcClient这个项目

安装包:Microsoft.AspNetCore.Authentication.JwtBearer

文件夹Protos内添加hello.proto文件

syntax = "proto3";
option csharp_namespace = "GrpcClient";
package hello;
import "google/protobuf/empty.proto";

message HelloResponse{
    string msg = 1;
}

service HelloService{
    rpc HelloUser(google.protobuf.Empty) returns (HelloResponse);
}

appsettings.Development.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "JwtTokenOption": {
    "TokenExpireTime": 60000,
    "Audience": "任我行",
    "Issuer": "任我行",
    // 如果RSA加密算法,则下面存放的是RSA的私钥(我这里用的RSA的私钥)
    "SecurityKey": "MIIEpAIBAAKCAQEA4cNvbucBVhIAzJMv/3aYYHlaojwdnGXdvEW3Qg8VhRgwJZyfRqEpJoRozwUluOHi7ayyerjiKm3DAm6nJ/qA1teq+jSAtspcyrliL2msCgqgCISpsY35hlKWXfNRQHqEjc6dL7QEmKsLqo4RclDZI5LHWYDWDprCDDFbHRGuY8vCgFYd4Y1wpEGzJ3JIL2VrBszIAB/Yn8LAFXJMZWmFlxRmDnWS9SuRc3XU9eMPK0L3rFeAVwMG/hqdo5KyrgseNCB3xUdxN44A1HMcTDB9DEPeTu8tCQoSki6gB22rxBO4ucvcJXKAtjJTQBY6QF52te5FLBMnhejxfhq6hhcq9QIDAQABAoIBAQDI61p/s5yv0ePeLNvZmd0wdq/flGqx5sJ4rP7UDoKTaZxnzMS/YewyeEKigy04JegEp95Lc8DsC7Uys/GVlc4V5egnNpSamOwOCwBDu+K9KQmVqyMufnDkRxnFUSctoBvZ7FhdvPMeP5NpXXhPaX5lt1os4IkghEBQA5jX/QVbj65UJEiG1x5/aMUeyhuEpKfxRvz1ZzeSSJsRMcThLd4hsY7TRwlGbPW8UVpTfPfAW89vKSGgvbBZ03NFofpU7b/HgZ7qrDa707IGRxLfejaFRxW1ua69pl+O86bu5dKFHi8OJwrjSAj2pQxdyV26ThW6xvNYdUya+Ri7iqzvD5hdAoGBAPfvDbcpVpycoU4HB54sNzz6W/1RIgnDL5KcGtBCUh8AKr/yE8QGbdKQheyfJWGlObQWXSAeQAHp5AYy+zookw4nkngpKUFAO/Uxfkkf1UB3QdGC/gsbB4b5vhWmwQtqN6d90TlwucvNplpoSe5HqjUcf86DctoMhw0gi7rr5zhLAoGBAOkbu6ZfBveJPQev2auDvl8KhvcFgrMuXwlsB68/4HtSVTQy33f55KM7udEQSML+faqdFycCU1hV3QVQcs/2oGaUulGZSUvZugR296WAUSZ4tUvPDnjnlWpt48nJNWM38PNLScOMhExvBwFwD30eaZ0G5kZhTsKD7BL3mIDcZ6G/AoGBALx5gZenWSwc9ZJ3TZc0TZmRSLS9JH7/Xf65pLiEciEW42ifAd+Wc44KR4SlRqmADOmVxp1P4aCSyMDdqJWBmqi79GBcCfyMdAfk4/d6t4YWIna+eZi/p204FQQoi7+9sykkQBTGWLdRUhCQDwOQfxd43r+CtaCEvXWBNDeYdWEZAoGAEqRGIGrvCrKt78RvWtkBS2ZzHqQRLLUjooRCJRCtqg8Og0siNd0FHMy08nQj7XwenptLc7Iq6iCLuVYSqHDnqOxx7f6dLvStfJfq/BBD7RiwHuzjEmYqu8Un90Yg/9tEaKB3uKyvE9G5NLM6ed4JwiYAGlbDzqhwI6ArUPrPSs8CgYBOOmAe3r9+xLrLNnvlCdhDchw5gn8dknNcjguy3czhL4lOlMzEetod3l45ngA7dAeuOz6Tvz/+7ljVvIyFG1fzbsz7PQ0JYQqPWFaROGq3Umg2R/ba3uggya6MgJOvP2Vko0i0nuw2fmLp6vqfnVDyFYhF864iWg567NeywjHoOQ=="
  }
}

生成后查看GrpcClient.csproj是否有生成

  <ItemGroup>
    <Protobuf Include="Protos\hello.proto">
      <GrpcServices>Client</GrpcServices>
      <Access>Public</Access>
      <ProtoCompile>True</ProtoCompile>
      <CompileOutputs>True</CompileOutputs>
      <OutputDir>obj\Debug\net7.0\</OutputDir>
      <Generator>MSBuild:Compile</Generator>
    </Protobuf>
    <Protobuf Include="Protos\person.proto">
      <GrpcServices>Client</GrpcServices>
      <Access>Public</Access>
      <ProtoCompile>True</ProtoCompile>
      <CompileOutputs>True</CompileOutputs>
      <OutputDir>obj\Debug\net7.0\</OutputDir>
      <Generator>MSBuild:Compile</Generator>
    </Protobuf>
    <Protobuf Include="Protos\user.proto">
      <GrpcServices>Client</GrpcServices>
      <Access>Public</Access>
      <ProtoCompile>True</ProtoCompile>
      <CompileOutputs>True</CompileOutputs>
      <OutputDir>obj\Debug\net7.0\</OutputDir>
      <Generator>MSBuild:Compile</Generator>
    </Protobuf>
  </ItemGroup>

 

Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<GenerateTokenService>();


#region JWT认证

var jwtOption = builder.Configuration.GetSection("JwtTokenOption");
builder.Services.Configure<JwtTokenOption>(jwtOption);
JwtTokenOption jwtTokenOption = jwtOption.Get<JwtTokenOption>()!;
// 添加认证服务
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(p =>
    {
        var rsa = RSA.Create();
        rsa.ImportRSAPrivateKey(Convert.FromBase64String(jwtTokenOption.SecurityKey), out _);
        SecurityKey securityKey = new RsaSecurityKey(rsa);


        // 校验JWT是否合法
        p.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidAlgorithms = new string[] { "RS256" },
            ValidateIssuer = true, //是否验证Issuer
            ValidateAudience = true, //是否验证Audience
            ValidateLifetime = true, //是否验证失效时间
            ClockSkew = TimeSpan.Zero, //时钟脉冲相位差
            ValidateIssuerSigningKey = true, //是否验证SecurityKey
            ValidAudience = jwtTokenOption.Audience, //Audience
            ValidIssuer = jwtTokenOption.Issuer, //Issuer,这两项和前面签发jwt的设置一致
            IssuerSigningKey = securityKey, //拿到SecurityKey
        };
    });
builder.Services.AddAuthorization();

#endregion

Action<GrpcClientFactoryOptions> opt = p =>
{
    p.Address = new Uri("http://localhost:5023");
};
builder.Services.AddGrpcClient<UserService.UserServiceClient>(opt);
builder.Services.AddGrpcClient<PersonService.PersonServiceClient>(opt);
builder.Services.AddGrpcClient<HelloService.HelloServiceClient>(p => p.Address = new Uri("http://localhost:5015"))
    .AddCallCredentials(async (context, metadata) =>
    {
        var serviceProvider = builder.Services.BuildServiceProvider();
        var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
        var token = await httpContextAccessor.HttpContext.GetTokenAsync("access_token");
        if (!string.IsNullOrWhiteSpace(token))
        {
            metadata.Add("Authorization", $"Bearer {token}");
        }
    }).ConfigureChannel(p => p.UnsafeUseInsecureChannelCallCredentials = true);



var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseRouting();


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

app.MapControllers();

app.Run();

控制器TokenController

[Route("[controller]/[action]")]
[ApiController]
public class TokenController:ControllerBase
{
    private readonly GenerateTokenService _tokenService;
    private readonly HelloService.HelloServiceClient _helloServiceClient;

    public TokenController(GenerateTokenService tokenService, HelloService.HelloServiceClient helloServiceClient)
    {
        _tokenService = tokenService;
        _helloServiceClient = helloServiceClient;
    }

    [HttpGet]
    public IActionResult GetToken()
    {
        return Ok(_tokenService.GenerateToken(new()
        {
            Username = "admin",
            Nickname = "管理员",
            RoleId = 1,
            RoleName = "管理员",
            Id = 1
        }));

    }

    [Authorize]
    [HttpGet]
    public IActionResult HelloUser()
    {
        var helloResponse = _helloServiceClient.HelloUser(new Empty());
        return Ok(helloResponse.Msg);
    }
}

 

posted @ 2024-02-19 15:44  野码  阅读(88)  评论(0编辑  收藏  举报