IdentityServer4 имеет простое MeadleWare для использования в Asp.Net Core
public void ConfigureServices(IServiceCollection services){
...
var cert = new X509Certificate2("/Cert/cert.pfx", "123456");
services.AddIdentityServer()
.AddInMemoryApiResources(Config.GetApisResources())
.AddSigningCredential(cert)
.AddInMemoryClients(Config.GetClients())
.Services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
...
}
public void Configure(ILoggerFactory loggerFactory, IApplicationBuilder app, IHostingEnvironment env){
...
app.UseIdentityServer();
...
}
и создайте файл конфигурации:
public class Config
{
public static IEnumerable<ApiResource> GetApisResources()
{
return new[]
{
// simple API with a single scope (in this case the scope name is the same as the api name)
new ApiResource("api1"),
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "spa",
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
//IdentityTokenLifetime=10,
AllowOfflineAccess=true,
RefreshTokenExpiration = TokenExpiration.Absolute,
AbsoluteRefreshTokenLifetime = 999999,
RefreshTokenUsage=TokenUsage.ReUse,
AccessTokenType=AccessTokenType.Jwt,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes =
{
"api1",
IdentityServerConstants.StandardScopes.OfflineAccess
},
AccessTokenLifetime=36000
}
};
}
}
затем в resourceServer используйте сильфон MW:
public void ConfigureServices(IServiceCollection services){
...
services.AddAuthentication(o =>
{
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.Authority = "http://localhost:5000";
o.Audience = "self";
o.RequireHttpsMetadata = false;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = false,
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
RequireExpirationTime = true,
ClockSkew = TimeSpan.Zero
};
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 401;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync(c.Exception.ToString());
},
OnTokenValidated = context =>
{
return Task.CompletedTask;
},
OnMessageReceived = context =>
{
return Task.CompletedTask;
},
OnChallenge = context =>
{
return Task.CompletedTask;
}
};
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseAuthentication();
...
}