mirror of
https://gitee.com/dcren/openiddict-documentation.git
synced 2025-11-09 19:04:44 +08:00
Update the documentation pages
This commit is contained in:
@@ -68,36 +68,28 @@
|
||||
<article class="content wrap" id="_content" data-uid="">
|
||||
<h1 id="getting-started">Getting started</h1>
|
||||
|
||||
<p>To use OpenIddict, you need to:</p>
|
||||
<p><strong>To implement a custom OpenID Connect server using OpenIddict, the simplest option is to clone one of the official samples</strong> from the <a href="https://github.com/openiddict/openiddict-samples">openiddict-samples repository</a>.</p>
|
||||
<p>If you don't want to start from one of the recommended samples, you'll need to:</p>
|
||||
<ul>
|
||||
<li><p><strong>Install the latest <a href="https://www.microsoft.com/net/download">.NET Core 2.x tooling</a> and update your packages to reference the ASP.NET Core 2.x packages</strong>.</p>
|
||||
<li><p><strong>Install the <a href="https://www.microsoft.com/net/download">.NET Core 2.1.x, 3.1.x or .NET 5.0.x tooling</a></strong>.</p>
|
||||
</li>
|
||||
<li><p><strong>Have an existing project or create a new one</strong>: when creating a new project using Visual Studio's default ASP.NET Core template, using <strong>individual user accounts authentication</strong> is strongly recommended. When updating an existing project, you must provide your own <code>AccountController</code> to handle the registration process and the authentication flow.</p>
|
||||
<li><p><strong>Have an existing project or create a new one</strong>: when creating a new project using Visual Studio's default ASP.NET Core template,
|
||||
using <strong>individual user accounts authentication</strong> is strongly recommended as it automatically includes the default ASP.NET Core Identity UI, based on Razor Pages.</p>
|
||||
</li>
|
||||
<li><p><strong>Update your <code>.csproj</code> file</strong> to reference the <code>OpenIddict</code> packages:</p>
|
||||
<pre><code class="lang-xml"><PackageReference Include="OpenIddict" Version="2.0.0-*" />
|
||||
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="2.0.0-*" />
|
||||
<pre><code class="lang-xml"><PackageReference Include="OpenIddict.AspNetCore" Version="3.0.0" />
|
||||
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="3.0.0" />
|
||||
</code></pre></li>
|
||||
<li><p><strong>OPTIONAL: If you want to try out the latest features and bug fixes,</strong> there is a MyGet feed with nightly builds
|
||||
of OpenIddict.</p>
|
||||
<p>To reference the OpenIddict MyGet feed, <strong>create a <code>NuGet.config</code> file</strong> (at the root of your solution):</p>
|
||||
<pre><code class="lang-xml"><?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<packageSources>
|
||||
<add key="nuget" value="https://api.nuget.org/v3/index.json" />
|
||||
<add key="openiddict" value="https://www.myget.org/F/openiddict/api/v3/index.json" />
|
||||
</packageSources>
|
||||
</configuration>
|
||||
</code></pre></li>
|
||||
<li><p><strong>Configure the OpenIddict services</strong> in <code>Startup.ConfigureServices</code>:</p>
|
||||
<li><p><strong>Configure the OpenIddict core, server and validation services</strong> in <code>Startup.ConfigureServices</code>.
|
||||
Here's an example for the client credentials grant, used in machine-to-machine scenarios:</p>
|
||||
<pre><code class="lang-csharp">public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMvc();
|
||||
services.AddControllersWithViews();
|
||||
|
||||
services.AddDbContext<ApplicationDbContext>(options =>
|
||||
{
|
||||
// Configure the context to use Microsoft SQL Server.
|
||||
options.UseSqlServer(configuration["Data:DefaultConnection:ConnectionString"]);
|
||||
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
|
||||
|
||||
// Register the entity sets needed by OpenIddict.
|
||||
// Note: use the generic overload if you need
|
||||
@@ -105,56 +97,74 @@ of OpenIddict.</p>
|
||||
options.UseOpenIddict();
|
||||
});
|
||||
|
||||
// Register the Identity services.
|
||||
services.AddIdentity<ApplicationUser, IdentityRole>()
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
// Register the OpenIddict services.
|
||||
services.AddOpenIddict()
|
||||
|
||||
// Register the OpenIddict core components.
|
||||
.AddCore(options =>
|
||||
{
|
||||
// Configure OpenIddict to use the Entity Framework Core stores and entities.
|
||||
// Configure OpenIddict to use the Entity Framework Core stores and models.
|
||||
// Note: call ReplaceDefaultEntities() to replace the default OpenIddict entities.
|
||||
options.UseEntityFrameworkCore()
|
||||
.UseDbContext<ApplicationDbContext>();
|
||||
.UseDbContext<ApplicationDbContext>();
|
||||
})
|
||||
|
||||
// Register the OpenIddict server components.
|
||||
.AddServer(options =>
|
||||
{
|
||||
// Register the ASP.NET Core MVC binder used by OpenIddict.
|
||||
// Note: if you don't call this method, you won't be able to
|
||||
// bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
|
||||
options.UseMvc();
|
||||
// Enable the token endpoint.
|
||||
options.SetTokenEndpointUris("/connect/token");
|
||||
|
||||
// Enable the token endpoint (required to use the password flow).
|
||||
options.EnableTokenEndpoint("/connect/token");
|
||||
// Enable the client credentials flow.
|
||||
options.AllowClientCredentialsFlow();
|
||||
|
||||
// Allow client applications to use the grant_type=password flow.
|
||||
options.AllowPasswordFlow();
|
||||
// Register the signing and encryption credentials.
|
||||
options.AddDevelopmentEncryptionCertificate()
|
||||
.AddDevelopmentSigningCertificate();
|
||||
|
||||
// During development, you can disable the HTTPS requirement.
|
||||
options.DisableHttpsRequirement();
|
||||
|
||||
// Accept token requests that don't specify a client_id.
|
||||
options.AcceptAnonymousClients();
|
||||
// Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
|
||||
options.UseAspNetCore()
|
||||
.EnableTokenEndpointPassthrough();
|
||||
})
|
||||
|
||||
.AddValidation();
|
||||
// Register the OpenIddict validation components.
|
||||
.AddValidation(options =>
|
||||
{
|
||||
// Import the configuration from the local OpenIddict server instance.
|
||||
options.UseLocalServer();
|
||||
|
||||
// Register the ASP.NET Core host.
|
||||
options.UseAspNetCore();
|
||||
});
|
||||
|
||||
// Register the worker responsible of seeding the database with the sample clients.
|
||||
// Note: in a real world application, this step should be part of a setup script.
|
||||
services.AddHostedService<Worker>();
|
||||
}
|
||||
</code></pre></li>
|
||||
<li><p><strong>Make sure the authentication middleware is registered before all the other middleware, including <code>app.UseMvc()</code></strong>:</p>
|
||||
<li><p><strong>Make sure the ASP.NET Core authentication middleware is correctly registered at the right place</strong>:</p>
|
||||
<pre><code class="lang-csharp">public void Configure(IApplicationBuilder app)
|
||||
{
|
||||
app.UseAuthentication();
|
||||
app.UseDeveloperExceptionPage();
|
||||
|
||||
app.UseMvc();
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseEndpoints(options =>
|
||||
{
|
||||
options.MapControllers();
|
||||
options.MapDefaultControllerRoute();
|
||||
});
|
||||
|
||||
app.UseWelcomePage();
|
||||
}
|
||||
</code></pre></li>
|
||||
<li><p><strong>Update your Entity Framework Core context registration to register the OpenIddict entities</strong>:</p>
|
||||
<pre><code class="lang-csharp">services.AddDbContext<ApplicationDbContext>(options =>
|
||||
{
|
||||
// Configure the context to use Microsoft SQL Server.
|
||||
options.UseSqlServer(configuration["Data:DefaultConnection:ConnectionString"]);
|
||||
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
|
||||
|
||||
// Register the entity sets needed by OpenIddict.
|
||||
// Note: use the generic overload if you need
|
||||
@@ -163,7 +173,9 @@ of OpenIddict.</p>
|
||||
});
|
||||
</code></pre></li>
|
||||
</ul>
|
||||
<blockquote><p><strong>Note:</strong> if you change the default entity primary key (e.g. to <code>int</code> or <code>Guid</code> instead of <code>string</code>), make sure you use the <code>options.ReplaceDefaultEntities<TKey>()</code> core extension accepting a <code>TKey</code> generic argument and use the generic <code>options.UseOpenIddict<TKey>()</code> overload to configure Entity Framework Core to use the specified key type:</p>
|
||||
<p>-> [!NOTE]</p>
|
||||
<blockquote><p>Important: if you change the default entity primary key (e.g. to <code>int</code> or <code>Guid</code> instead of <code>string</code>), make sure you use the <code>options.ReplaceDefaultEntities<TKey>()</code>
|
||||
core extension accepting a <code>TKey</code> generic argument and use the generic <code>options.UseOpenIddict<TKey>()</code> overload to configure Entity Framework Core to use the specified key type:</p>
|
||||
<pre><code class="lang-csharp">services.AddOpenIddict()
|
||||
.AddCore(options =>
|
||||
{
|
||||
@@ -182,67 +194,85 @@ services.AddDbContext<ApplicationDbContext>(options =>
|
||||
});
|
||||
</code></pre></blockquote>
|
||||
<ul>
|
||||
<li><strong>Create your own authorization controller</strong>:</li>
|
||||
</ul>
|
||||
<p>To <strong>support the password or the client credentials flow, you must provide your own token endpoint action</strong>.
|
||||
To enable authorization code/implicit flows support, you'll similarly have to create your own authorization endpoint action and your own views/view models.</p>
|
||||
<p>The <strong>Mvc.Server sample comes with an <a href="https://github.com/openiddict/openiddict-core/blob/dev/samples/Mvc.Server/Controllers/AuthorizationController.cs"><code>AuthorizationController</code> that supports both the password flow and the authorization code flow and that you can easily reuse in your application</a></strong>.</p>
|
||||
<ul>
|
||||
<li><p><strong>Enable the corresponding flows in the OpenIddict options</strong>:</p>
|
||||
<pre><code class="lang-csharp">public void ConfigureServices(IServiceCollection services)
|
||||
<li><p><strong>Create your own authorization controller:</strong>
|
||||
Implementing a custom authorization controller is required to allow OpenIddict to create tokens based on the identities and claims you provide.
|
||||
Here's an example for the client credentials grant:</p>
|
||||
<pre><code class="lang-csharp">public class AuthorizationController : Controller
|
||||
{
|
||||
// Register the OpenIddict services.
|
||||
services.AddOpenIddict()
|
||||
.AddCore(options =>
|
||||
private readonly OpenIddictApplicationManager<OpenIddictEntityFrameworkCoreApplication> _applicationManager;
|
||||
|
||||
public AuthorizationController(OpenIddictApplicationManager<OpenIddictEntityFrameworkCoreApplication> applicationManager)
|
||||
=> _applicationManager = applicationManager;
|
||||
|
||||
[HttpPost("~/connect/token"), Produces("application/json")]
|
||||
public async Task<IActionResult> Exchange()
|
||||
{
|
||||
var request = HttpContext.GetOpenIddictServerRequest();
|
||||
if (request.IsClientCredentialsGrantType())
|
||||
{
|
||||
// Configure OpenIddict to use the Entity Framework Core stores and entities.
|
||||
options.UseEntityFrameworkCore()
|
||||
.UseDbContext<ApplicationDbContext>();
|
||||
})
|
||||
// Note: the client credentials are automatically validated by OpenIddict:
|
||||
// if client_id or client_secret are invalid, this action won't be invoked.
|
||||
|
||||
.AddServer(options =>
|
||||
{
|
||||
// Register the ASP.NET Core MVC binder used by OpenIddict.
|
||||
// Note: if you don't call this method, you won't be able to
|
||||
// bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
|
||||
options.UseMvc();
|
||||
var application = await _applicationManager.FindByClientIdAsync(request.ClientId);
|
||||
if (application == null)
|
||||
{
|
||||
throw new InvalidOperationException("The application details cannot be found in the database.");
|
||||
}
|
||||
|
||||
// Enable the authorization/token endpoints (required to use the code flow).
|
||||
options.EnableAuthorizationEndpoint("/connect/authorize")
|
||||
.EnableTokenEndpoint("/connect/token");
|
||||
// Create a new ClaimsIdentity containing the claims that
|
||||
// will be used to create an id_token, a token or a code.
|
||||
var identity = new ClaimsIdentity(
|
||||
TokenValidationParameters.DefaultAuthenticationType,
|
||||
Claims.Name, Claims.Role);
|
||||
|
||||
// Allow client applications to use the code flow.
|
||||
options.AllowAuthorizationCodeFlow();
|
||||
// Use the client_id as the subject identifier.
|
||||
identity.AddClaim(Claims.Subject, await _applicationManager.GetClientIdAsync(application),
|
||||
Destinations.AccessToken, Destinations.IdentityToken);
|
||||
|
||||
// During development, you can disable the HTTPS requirement.
|
||||
options.DisableHttpsRequirement();
|
||||
})
|
||||
identity.AddClaim(Claims.Name, await _applicationManager.GetDisplayNameAsync(application),
|
||||
Destinations.AccessToken, Destinations.IdentityToken);
|
||||
|
||||
.AddValidation();
|
||||
return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
|
||||
}
|
||||
|
||||
throw new NotImplementedException("The specified grant type is not implemented.");
|
||||
}
|
||||
}
|
||||
</code></pre></li>
|
||||
<li><p><strong>Register your client application</strong>:</p>
|
||||
<pre><code class="lang-csharp">// Create a new service scope to ensure the database context
|
||||
// is correctly disposed when this methods returns.
|
||||
using (var scope = app.ApplicationServices.CreateScope())
|
||||
<li><p><strong>Register your client application</strong> (e.g from an <code>IHostedService</code> implementation):</p>
|
||||
<pre><code class="lang-csharp">public class Worker : IHostedService
|
||||
{
|
||||
var provider = scope.ServiceProvider;
|
||||
var context = provider.GetRequiredService<ApplicationDbContext>();
|
||||
await context.Database.EnsureCreatedAsync();
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
var manager = provider.GetRequiredService<IOpenIddictApplicationManager>();
|
||||
public Worker(IServiceProvider serviceProvider)
|
||||
=> _serviceProvider = serviceProvider;
|
||||
|
||||
if (await manager.FindByClientIdAsync("[client identifier]") == null)
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var descriptor = new OpenIddictApplicationDescriptor
|
||||
{
|
||||
ClientId = "[client identifier]",
|
||||
ClientSecret = "[client secret]",
|
||||
RedirectUris = { new Uri("[redirect uri]") }
|
||||
};
|
||||
using var scope = _serviceProvider.CreateScope();
|
||||
|
||||
await manager.CreateAsync(descriptor);
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
await context.Database.EnsureCreatedAsync();
|
||||
|
||||
var manager = scope.ServiceProvider.GetRequiredService<OpenIddictApplicationManager<OpenIddictEntityFrameworkCoreApplication>>();
|
||||
|
||||
if (await manager.FindByClientIdAsync("console") is null)
|
||||
{
|
||||
await manager.CreateAsync(new OpenIddictApplicationDescriptor
|
||||
{
|
||||
ClientId = "console",
|
||||
ClientSecret = "388D45FA-B36B-4988-BA59-B187D329C207",
|
||||
DisplayName = "My client application",
|
||||
Permissions =
|
||||
{
|
||||
Permissions.Endpoints.Token,
|
||||
Permissions.GrantTypes.ClientCredentials
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
}
|
||||
</code></pre></li>
|
||||
</ul>
|
||||
|
||||
Reference in New Issue
Block a user