API OAuth2 Token Management是一种重要的方案,它使用IdentityModel.AspNetCore实现AuthorizationCodeTokenRequest。该解决方法需要遵循以下步骤:
在NuGet中安装IdentityModel.AspNetCore。
添加以下代码段到Startup类的ConfigureServices方法中,以便设置IdentityServer4作为身份提供者。
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.IdentityModel.Tokens.Jwt; using IdentityModel.AspNetCore.OAuth2Introspection; using IdentityModel;
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "https://demo.identityserver.io";
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.ClientId = "interactive";
options.ResponseType = OidcConstants.ResponseTypes.Code;
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
app.UseMvc();
}
}
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://demo.identityserver.io"); if (disco.IsError) throw new Exception(disco.Error);
var token = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest { Address = disco.TokenEndpoint, ClientId = "interactive", Client