gRPC中整合asp.net identity實現oAuth認證

Celery發表於2019-05-27

gRPC中整合asp.net identity實現oAuth認證

在asp.net core 3.0中開啟identity認證

asp.net core 3.0種需要匯入的identity包與core 2.2發生了些變化:

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.0.0-preview5-19227-01" />
  <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview5-19227-01" />
  <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.0.0-preview5-19227-01" />
  <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0-preview5-19227-01" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0-preview5-19227-01" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0-preview5.19227.1" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0-preview5.19227.1" />
</ItemGroup>

複製程式碼

程式碼的配置方式變化不大,主要集中在ConfigureServices中:

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services
    .AddDefaultIdentity<IdentityUser>(delegate (IdentityOptions options)
    {
        options.Password.RequiredLength = 6;
        options.Password.RequireLowercase = false;
        options.Password.RequireUppercase = false;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireDigit = false;
    })
    .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            LifetimeValidator = (before, expires, token, param) => expires > DateTime.UtcNow,
            ValidateAudience = false,
            ValidateIssuer = false,
            ValidateActor = false,
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("41B71F9E-4204-4E88-8E91-64B1981F1B82"))
        };
    });
複製程式碼

在asp.net core 3.0中同時整合gRPC與Restful API

在Kestrel中同時支援HTTP1與HTTP2:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder
                .ConfigureKestrel(options =>
                {
                    options.ListenLocalhost(50051, listenOptions =>
                    {
                        listenOptions.UseHttps("server.pfx", "1111");
                        listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                    });
                })
                .UseStartup<Startup>();
        });
複製程式碼

需要特別注意的一點,關於Kestrel的文件有提到,同時開啟Http1與Http2需要TLS和ALPN導向HTTP/2,否則預設在HTTP1.1。

基於Bearer Token的gRPC服務授權

gRPC整合到asp.net core3.0之後,預設的授權方式可以直接使用在gRPC服務上:

[Authorize(AuthenticationSchemes = "Bearer")]
public class GreeterService : Greeter.GreeterBase
{
    public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloReply
        {
            Message = "Hello " + request.Name
        });
    }
}
複製程式碼

完整程式碼請參考Github程式碼庫

相關文章