openiddict-documentation/guide/getting-started.html
2021-08-27 11:27:10 +00:00

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&#39;t want to start from one of the recommended samples, you&#39;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&#39;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">&lt;PackageReference Include=&quot;OpenIddict.AspNetCore&quot; Version=&quot;3.1.1&quot; /&gt;
&lt;PackageReference Include=&quot;OpenIddict.EntityFrameworkCore&quot; Version=&quot;3.1.1&quot; /&gt;
</code></pre></li>
<li><p><strong>Configure the OpenIddict core, server and validation services</strong> in <code>Startup.ConfigureServices</code>.
Here&#39;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&lt;ApplicationDbContext&gt;(options =&gt;
{
// Configure the context to use Microsoft SQL Server.
options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;));
// 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 =&gt;
{
// Configure OpenIddict to use the Entity Framework Core stores and models.
// Note: call ReplaceDefaultEntities() to replace the default entities.
options.UseEntityFrameworkCore()
.UseDbContext&lt;ApplicationDbContext&gt;();
})
// Register the OpenIddict server components.
.AddServer(options =&gt;
{
// Enable the token endpoint.
options.SetTokenEndpointUris(&quot;/connect/token&quot;);
// 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 =&gt;
{
// 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&lt;Worker&gt;();
}
</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 =&gt;
{
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&lt;ApplicationDbContext&gt;(options =&gt;
{
// Configure the context to use Microsoft SQL Server.
options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;));
// 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&lt;TKey&gt;()</code>
core extension accepting a <code>TKey</code> generic argument and use the generic <code>options.UseOpenIddict&lt;TKey&gt;()</code> overload to configure EF Core to use the specified type:</p>
<pre><code class="lang-csharp">services.AddOpenIddict()
.AddCore(options =&gt;
{
// Configure OpenIddict to use the default entities with a custom key type.
options.UseEntityFrameworkCore()
.UseDbContext&lt;ApplicationDbContext&gt;()
.ReplaceDefaultEntities&lt;Guid&gt;();
});
services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
{
// Configure the context to use Microsoft SQL Server.
options.UseSqlServer(configuration[&quot;Data:DefaultConnection:ConnectionString&quot;]);
options.UseOpenIddict&lt;Guid&gt;();
});
</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&#39;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)
=&gt; _applicationManager = applicationManager;
[HttpPost(&quot;~/connect/token&quot;), Produces(&quot;application/json&quot;)]
public async Task&lt;IActionResult&gt; Exchange()
{
var request = HttpContext.GetOpenIddictServerRequest();
if (!request.IsClientCredentialsGrantType())
{
throw new NotImplementedException(&quot;The specified grant is not implemented.&quot;);
}
// Note: the client credentials are automatically validated by OpenIddict:
// if client_id or client_secret are invalid, this action won&#39;t be invoked.
var application =
await _applicationManager.FindByClientIdAsync(request.ClientId) ??
throw new InvalidOperationException(&quot;The application cannot be found.&quot;);
// 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)
=&gt; _serviceProvider = serviceProvider;
public async Task StartAsync(CancellationToken cancellationToken)
{
using var scope = _serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService&lt;ApplicationDbContext&gt;();
await context.Database.EnsureCreatedAsync();
var manager =
scope.ServiceProvider.GetRequiredService&lt;IOpenIddictApplicationManager&gt;();
if (await manager.FindByClientIdAsync(&quot;console&quot;) is null)
{
await manager.CreateAsync(new OpenIddictApplicationDescriptor
{
ClientId = &quot;console&quot;,
ClientSecret = &quot;388D45FA-B36B-4988-BA59-B187D329C207&quot;,
DisplayName = &quot;My client application&quot;,
Permissions =
{
Permissions.Endpoints.Token,
Permissions.GrantTypes.ClientCredentials
}
});
}
}
public Task StopAsync(CancellationToken cancellationToken) =&gt; 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>