-
-
Notifications
You must be signed in to change notification settings - Fork 302
/
Startup.cs
140 lines (111 loc) · 5.85 KB
/
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
using System;
using System.Reflection;
using System.Security.Claims;
using System.Web.Http;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Integration.WebApi;
using Microsoft.Extensions.DependencyInjection;
using OpenIddict.Abstractions;
using OpenIddict.Server.Owin;
using OpenIddict.Validation.Owin;
using Owin;
using static OpenIddict.Abstractions.OpenIddictConstants;
using static OpenIddict.Server.OpenIddictServerEvents;
namespace Kalarba.Server;
public class Startup
{
public void Configuration(IAppBuilder app)
{
var services = new ServiceCollection();
services.AddOpenIddict()
// Register the OpenIddict server components.
.AddServer(options =>
{
// Enable the token endpoint.
options.SetTokenEndpointUris("connect/token");
// Enable the password and the refresh token flows.
options.AllowPasswordFlow();
// Enable the degraded to allow using the server feature without a backing database.
options.EnableDegradedMode();
// Accept anonymous clients (i.e clients that don't send a client_id).
options.AcceptAnonymousClients();
// Register the signing and encryption credentials.
options.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
// Register the OWIN host and configure the OWIN-specific options.
options.UseOwin()
.DisableTransportSecurityRequirement();
// Register an event handler responsible for validating token requests.
options.AddEventHandler<ValidateTokenRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
// Client authentication is not used in this sample,
// so there's nothing specific to validate here.
return default;
}));
// Register an event handler responsible for handling token requests.
options.AddEventHandler<HandleTokenRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
if (!context.Request.IsPasswordGrantType())
{
throw new InvalidOperationException("The specified grant type is not supported.");
}
// Validate the username/password parameters.
//
// In a real world application, you'd use likely use a key derivation function like PBKDF2 to slow the
// username/password validation process down and a time-constant comparer to prevent timing attacks.
if (!string.Equals(context.Request.Username, "[email protected]", StringComparison.Ordinal) ||
!string.Equals(context.Request.Password, "P@ssw0rd", StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidGrant,
description: "The username/password couple is invalid.");
return default;
}
// Create the claims-based identity that will be used by OpenIddict to generate tokens.
var identity = new ClaimsIdentity(
authenticationType: OpenIddictServerOwinDefaults.AuthenticationType,
nameType: Claims.Name,
roleType: Claims.Role);
// Add the claims that will be persisted in the tokens.
identity.AddClaim(new Claim(Claims.Subject, "999d4ea0-164f-4c1b-8585-b83f313995c9"));
identity.AddClaim(new Claim(Claims.Name, "Alice").SetDestinations(Destinations.AccessToken));
identity.AddClaim(new Claim(Claims.PreferredUsername, "Alice").SetDestinations(Destinations.AccessToken));
context.SignIn(new ClaimsPrincipal(identity));
return default;
}));
})
// Register the OpenIddict validation components.
.AddValidation(options =>
{
// Import the configuration from the local OpenIddict server instance.
options.UseLocalServer();
// Register the OWIN host.
options.UseOwin();
});
// Create a new Autofac container and import the OpenIddict services.
var builder = new ContainerBuilder();
builder.Populate(services);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
app.UseErrorPage();
// Register the Autofac scope injector middleware.
app.UseAutofacLifetimeScopeInjector(container);
// Register the two OpenIddict server/validation middleware.
app.UseMiddlewareFromContainer<OpenIddictServerOwinMiddleware>();
app.UseMiddlewareFromContainer<OpenIddictValidationOwinMiddleware>();
var configuration = new HttpConfiguration
{
DependencyResolver = new AutofacWebApiDependencyResolver(container)
};
configuration.MapHttpAttributeRoutes();
configuration.SuppressDefaultHostAuthentication();
// Configure ASP.NET Web API to use token authentication.
configuration.Filters.Add(new HostAuthenticationFilter(OpenIddictValidationOwinDefaults.AuthenticationType));
// Register the Web API/Autofac integration middleware.
app.UseAutofacWebApi(configuration);
app.UseWebApi(configuration);
}
}