mirror of
https://gitee.com/dcren/openiddict-documentation.git
synced 2025-04-05 17:38:03 +08:00
319 lines
14 KiB
HTML
319 lines
14 KiB
HTML
<!DOCTYPE html>
|
|
<!--[if IE]><![endif]-->
|
|
<html>
|
|
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
|
<title>Getting started </title>
|
|
<meta name="viewport" content="width=device-width">
|
|
<meta name="title" content="Getting started ">
|
|
<meta name="generator" content="docfx 2.56.7.0">
|
|
|
|
<link rel="shortcut icon" href="../images/favicon.ico">
|
|
<link rel="stylesheet" href="../styles/docfx.vendor.css">
|
|
<link rel="stylesheet" href="../styles/docfx.css">
|
|
<link rel="stylesheet" href="../styles/main.css">
|
|
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
|
|
<meta property="docfx:navrel" content="../toc.html">
|
|
<meta property="docfx:tocrel" content="toc.html">
|
|
|
|
|
|
|
|
</head> <body data-spy="scroll" data-target="#affix" data-offset="120">
|
|
<div id="wrapper">
|
|
<header>
|
|
|
|
<nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
|
|
<div class="container">
|
|
<div class="navbar-header">
|
|
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
|
|
<span class="sr-only">Toggle navigation</span>
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
</button>
|
|
|
|
<a class="navbar-brand" href="../index.html">
|
|
<img id="logo" class="svg" src="../images/logo.png" alt="">
|
|
</a> </div>
|
|
<div class="collapse navbar-collapse" id="navbar">
|
|
<form class="navbar-form navbar-right" role="search" id="search">
|
|
<div class="form-group">
|
|
<input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</nav>
|
|
|
|
<div class="subnav navbar navbar-default">
|
|
<div class="container hide-when-search" id="breadcrumb">
|
|
<ul class="breadcrumb">
|
|
<li></li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
</header>
|
|
<div role="main" class="container body-content hide-when-search">
|
|
|
|
<div class="sidenav hide-when-search">
|
|
<a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
|
|
<div class="sidetoggle collapse" id="sidetoggle">
|
|
<div id="sidetoc"></div>
|
|
</div>
|
|
</div>
|
|
<div class="article row grid-right">
|
|
<div class="col-md-10">
|
|
<article class="content wrap" id="_content" data-uid="">
|
|
<h1 id="getting-started">Getting started</h1>
|
|
|
|
<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 <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 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 latest <code>OpenIddict</code> packages:</p>
|
|
<pre><code class="lang-xml"><PackageReference Include="OpenIddict.AspNetCore" Version="3.1.1" />
|
|
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="3.1.1" />
|
|
</code></pre></li>
|
|
<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.AddControllersWithViews();
|
|
|
|
services.AddDbContext<ApplicationDbContext>(options =>
|
|
{
|
|
// Configure the context to use Microsoft SQL Server.
|
|
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
|
|
|
|
// Register the entity sets needed by OpenIddict.
|
|
// Note: use the generic overload if you need
|
|
// to replace the default OpenIddict entities.
|
|
options.UseOpenIddict();
|
|
});
|
|
|
|
services.AddOpenIddict()
|
|
|
|
// Register the OpenIddict core components.
|
|
.AddCore(options =>
|
|
{
|
|
// Configure OpenIddict to use the Entity Framework Core stores and models.
|
|
// Note: call ReplaceDefaultEntities() to replace the default entities.
|
|
options.UseEntityFrameworkCore()
|
|
.UseDbContext<ApplicationDbContext>();
|
|
})
|
|
|
|
// Register the OpenIddict server components.
|
|
.AddServer(options =>
|
|
{
|
|
// Enable the token endpoint.
|
|
options.SetTokenEndpointUris("/connect/token");
|
|
|
|
// Enable the client credentials flow.
|
|
options.AllowClientCredentialsFlow();
|
|
|
|
// Register the signing and encryption credentials.
|
|
options.AddDevelopmentEncryptionCertificate()
|
|
.AddDevelopmentSigningCertificate();
|
|
|
|
// Register the ASP.NET Core host and configure the ASP.NET Core options.
|
|
options.UseAspNetCore()
|
|
.EnableTokenEndpointPassthrough();
|
|
})
|
|
|
|
// 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 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.UseDeveloperExceptionPage();
|
|
|
|
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.GetConnectionString("DefaultConnection"));
|
|
|
|
// Register the entity sets needed by OpenIddict.
|
|
// Note: use the generic overload if you need
|
|
// to replace the default OpenIddict entities.
|
|
options.UseOpenIddict();
|
|
});
|
|
</code></pre><div class="WARNING"><h5>Warning</h5><p>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 EF Core to use the specified type:</p>
|
|
<pre><code class="lang-csharp">services.AddOpenIddict()
|
|
.AddCore(options =>
|
|
{
|
|
// Configure OpenIddict to use the default entities with a custom key type.
|
|
options.UseEntityFrameworkCore()
|
|
.UseDbContext<ApplicationDbContext>()
|
|
.ReplaceDefaultEntities<Guid>();
|
|
});
|
|
|
|
services.AddDbContext<ApplicationDbContext>(options =>
|
|
{
|
|
// Configure the context to use Microsoft SQL Server.
|
|
options.UseSqlServer(configuration["Data:DefaultConnection:ConnectionString"]);
|
|
|
|
options.UseOpenIddict<Guid>();
|
|
});
|
|
</code></pre></div>
|
|
</li>
|
|
<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
|
|
{
|
|
private readonly IOpenIddictApplicationManager _applicationManager;
|
|
|
|
public AuthorizationController(IOpenIddictApplicationManager applicationManager)
|
|
=> _applicationManager = applicationManager;
|
|
|
|
[HttpPost("~/connect/token"), Produces("application/json")]
|
|
public async Task<IActionResult> Exchange()
|
|
{
|
|
var request = HttpContext.GetOpenIddictServerRequest();
|
|
if (!request.IsClientCredentialsGrantType())
|
|
{
|
|
throw new NotImplementedException("The specified grant is not implemented.");
|
|
}
|
|
|
|
// Note: the client credentials are automatically validated by OpenIddict:
|
|
// if client_id or client_secret are invalid, this action won't be invoked.
|
|
|
|
var application =
|
|
await _applicationManager.FindByClientIdAsync(request.ClientId) ??
|
|
throw new InvalidOperationException("The application cannot be found.");
|
|
|
|
// 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);
|
|
|
|
// Use the client_id as the subject identifier.
|
|
identity.AddClaim(Claims.Subject,
|
|
await _applicationManager.GetClientIdAsync(application),
|
|
Destinations.AccessToken, Destinations.IdentityToken);
|
|
|
|
identity.AddClaim(Claims.Name,
|
|
await _applicationManager.GetDisplayNameAsync(application),
|
|
Destinations.AccessToken, Destinations.IdentityToken);
|
|
|
|
return SignIn(new ClaimsPrincipal(identity),
|
|
OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
|
|
}
|
|
}
|
|
</code></pre></li>
|
|
<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
|
|
{
|
|
private readonly IServiceProvider _serviceProvider;
|
|
|
|
public Worker(IServiceProvider serviceProvider)
|
|
=> _serviceProvider = serviceProvider;
|
|
|
|
public async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
using var scope = _serviceProvider.CreateScope();
|
|
|
|
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
|
await context.Database.EnsureCreatedAsync();
|
|
|
|
var manager =
|
|
scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();
|
|
|
|
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><p>Before running the application, make sure the database is updated with OpenIddict tables by running <code>Add-Migration</code> and <code>Update-Database</code>.</p>
|
|
</li>
|
|
</ul>
|
|
</article>
|
|
</div>
|
|
|
|
<div class="hidden-sm col-md-2" role="complementary">
|
|
<div class="sideaffix">
|
|
<div class="contribution">
|
|
<ul class="nav">
|
|
<li>
|
|
<a href="https://github.com/openiddict/openiddict-documentation/blob/dev/guide/getting-started.md/#L1" class="contribution-link">Improve this Doc</a>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
<nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
|
|
<h5>In This Article</h5>
|
|
<div></div>
|
|
</nav>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<footer>
|
|
<div class="grad-bottom"></div>
|
|
<div class="footer">
|
|
<div class="container">
|
|
<span class="pull-right">
|
|
<a href="#top">Back to top</a>
|
|
</span>
|
|
|
|
<span>Generated by <strong>DocFX</strong></span>
|
|
</div>
|
|
</div>
|
|
</footer>
|
|
</div>
|
|
|
|
<script type="text/javascript" src="../styles/docfx.vendor.js"></script>
|
|
<script type="text/javascript" src="../styles/docfx.js"></script>
|
|
<script type="text/javascript" src="../styles/main.js"></script>
|
|
</body>
|
|
</html>
|