├── .gitignore ├── AuthorizationServer ├── AuthorizationServer.csproj ├── Controllers │ ├── AccountController.cs │ ├── AuthorizationController.cs │ └── HomeController.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── TestData.cs ├── ViewModels │ └── LoginViewModel.cs ├── Views │ ├── Account │ │ └── Login.cshtml │ ├── Home │ │ └── Index.cshtml │ ├── Shared │ │ └── _Layout.cshtml │ ├── _ViewImports.cshtml │ └── _ViewStart.cshtml ├── appsettings.Development.json ├── appsettings.json └── wwwroot │ └── css │ └── site.css ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | .DS_Store 7 | .idea 8 | 9 | # User-specific files 10 | *.rsuser 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Mono auto generated files 20 | mono_crash.* 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | [Dd]ebugPublic/ 25 | [Rr]elease/ 26 | [Rr]eleases/ 27 | x64/ 28 | x86/ 29 | [Aa][Rr][Mm]/ 30 | [Aa][Rr][Mm]64/ 31 | bld/ 32 | [Bb]in/ 33 | [Oo]bj/ 34 | [Ll]og/ 35 | [Ll]ogs/ 36 | 37 | # Visual Studio 2015/2017 cache/options directory 38 | .vs/ 39 | # Uncomment if you have tasks that create the project's static files in wwwroot 40 | #wwwroot/ 41 | 42 | # Visual Studio 2017 auto generated files 43 | Generated\ Files/ 44 | 45 | # MSTest test Results 46 | [Tt]est[Rr]esult*/ 47 | [Bb]uild[Ll]og.* 48 | 49 | # NUnit 50 | *.VisualState.xml 51 | TestResult.xml 52 | nunit-*.xml 53 | 54 | # Build Results of an ATL Project 55 | [Dd]ebugPS/ 56 | [Rr]eleasePS/ 57 | dlldata.c 58 | 59 | # Benchmark Results 60 | BenchmarkDotNet.Artifacts/ 61 | 62 | # .NET Core 63 | project.lock.json 64 | project.fragment.lock.json 65 | artifacts/ 66 | 67 | # StyleCop 68 | StyleCopReport.xml 69 | 70 | # Files built by Visual Studio 71 | *_i.c 72 | *_p.c 73 | *_h.h 74 | *.ilk 75 | *.meta 76 | *.obj 77 | *.iobj 78 | *.pch 79 | *.pdb 80 | *.ipdb 81 | *.pgc 82 | *.pgd 83 | *.rsp 84 | *.sbr 85 | *.tlb 86 | *.tli 87 | *.tlh 88 | *.tmp 89 | *.tmp_proj 90 | *_wpftmp.csproj 91 | *.log 92 | *.vspscc 93 | *.vssscc 94 | .builds 95 | *.pidb 96 | *.svclog 97 | *.scc 98 | 99 | # Chutzpah Test files 100 | _Chutzpah* 101 | 102 | # Visual C++ cache files 103 | ipch/ 104 | *.aps 105 | *.ncb 106 | *.opendb 107 | *.opensdf 108 | *.sdf 109 | *.cachefile 110 | *.VC.db 111 | *.VC.VC.opendb 112 | 113 | # Visual Studio profiler 114 | *.psess 115 | *.vsp 116 | *.vspx 117 | *.sap 118 | 119 | # Visual Studio Trace Files 120 | *.e2e 121 | 122 | # TFS 2012 Local Workspace 123 | $tf/ 124 | 125 | # Guidance Automation Toolkit 126 | *.gpState 127 | 128 | # ReSharper is a .NET coding add-in 129 | _ReSharper*/ 130 | *.[Rr]e[Ss]harper 131 | *.DotSettings.user 132 | 133 | # TeamCity is a build add-in 134 | _TeamCity* 135 | 136 | # DotCover is a Code Coverage Tool 137 | *.dotCover 138 | 139 | # AxoCover is a Code Coverage Tool 140 | .axoCover/* 141 | !.axoCover/settings.json 142 | 143 | # Visual Studio code coverage results 144 | *.coverage 145 | *.coveragexml 146 | 147 | # NCrunch 148 | _NCrunch_* 149 | .*crunch*.local.xml 150 | nCrunchTemp_* 151 | 152 | # MightyMoose 153 | *.mm.* 154 | AutoTest.Net/ 155 | 156 | # Web workbench (sass) 157 | .sass-cache/ 158 | 159 | # Installshield output folder 160 | [Ee]xpress/ 161 | 162 | # DocProject is a documentation generator add-in 163 | DocProject/buildhelp/ 164 | DocProject/Help/*.HxT 165 | DocProject/Help/*.HxC 166 | DocProject/Help/*.hhc 167 | DocProject/Help/*.hhk 168 | DocProject/Help/*.hhp 169 | DocProject/Help/Html2 170 | DocProject/Help/html 171 | 172 | # Click-Once directory 173 | publish/ 174 | 175 | # Publish Web Output 176 | *.[Pp]ublish.xml 177 | *.azurePubxml 178 | # Note: Comment the next line if you want to checkin your web deploy settings, 179 | # but database connection strings (with potential passwords) will be unencrypted 180 | *.pubxml 181 | *.publishproj 182 | 183 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 184 | # checkin your Azure Web App publish settings, but sensitive information contained 185 | # in these scripts will be unencrypted 186 | PublishScripts/ 187 | 188 | # NuGet Packages 189 | *.nupkg 190 | # NuGet Symbol Packages 191 | *.snupkg 192 | # The packages folder can be ignored because of Package Restore 193 | **/[Pp]ackages/* 194 | # except build/, which is used as an MSBuild target. 195 | !**/[Pp]ackages/build/ 196 | # Uncomment if necessary however generally it will be regenerated when needed 197 | #!**/[Pp]ackages/repositories.config 198 | # NuGet v3's project.json files produces more ignorable files 199 | *.nuget.props 200 | *.nuget.targets 201 | 202 | # Microsoft Azure Build Output 203 | csx/ 204 | *.build.csdef 205 | 206 | # Microsoft Azure Emulator 207 | ecf/ 208 | rcf/ 209 | 210 | # Windows Store app package directories and files 211 | AppPackages/ 212 | BundleArtifacts/ 213 | Package.StoreAssociation.xml 214 | _pkginfo.txt 215 | *.appx 216 | *.appxbundle 217 | *.appxupload 218 | 219 | # Visual Studio cache files 220 | # files ending in .cache can be ignored 221 | *.[Cc]ache 222 | # but keep track of directories ending in .cache 223 | !?*.[Cc]ache/ 224 | 225 | # Others 226 | ClientBin/ 227 | ~$* 228 | *~ 229 | *.dbmdl 230 | *.dbproj.schemaview 231 | *.jfm 232 | *.pfx 233 | *.publishsettings 234 | orleans.codegen.cs 235 | 236 | # Including strong name files can present a security risk 237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 238 | #*.snk 239 | 240 | # Since there are multiple workflows, uncomment next line to ignore bower_components 241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 242 | #bower_components/ 243 | 244 | # RIA/Silverlight projects 245 | Generated_Code/ 246 | 247 | # Backup & report files from converting an old project file 248 | # to a newer Visual Studio version. Backup files are not needed, 249 | # because we have git ;-) 250 | _UpgradeReport_Files/ 251 | Backup*/ 252 | UpgradeLog*.XML 253 | UpgradeLog*.htm 254 | ServiceFabricBackup/ 255 | *.rptproj.bak 256 | 257 | # SQL Server files 258 | *.mdf 259 | *.ldf 260 | *.ndf 261 | 262 | # Business Intelligence projects 263 | *.rdl.data 264 | *.bim.layout 265 | *.bim_*.settings 266 | *.rptproj.rsuser 267 | *- [Bb]ackup.rdl 268 | *- [Bb]ackup ([0-9]).rdl 269 | *- [Bb]ackup ([0-9][0-9]).rdl 270 | 271 | # Microsoft Fakes 272 | FakesAssemblies/ 273 | 274 | # GhostDoc plugin setting file 275 | *.GhostDoc.xml 276 | 277 | # Node.js Tools for Visual Studio 278 | .ntvs_analysis.dat 279 | node_modules/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # CodeRush personal settings 306 | .cr/personal 307 | 308 | # Python Tools for Visual Studio (PTVS) 309 | __pycache__/ 310 | *.pyc 311 | 312 | # Cake - Uncomment if you are using it 313 | # tools/** 314 | # !tools/packages.config 315 | 316 | # Tabs Studio 317 | *.tss 318 | 319 | # Telerik's JustMock configuration file 320 | *.jmconfig 321 | 322 | # BizTalk build output 323 | *.btp.cs 324 | *.btm.cs 325 | *.odx.cs 326 | *.xsd.cs 327 | 328 | # OpenCover UI analysis results 329 | OpenCover/ 330 | 331 | # Azure Stream Analytics local run output 332 | ASALocalRun/ 333 | 334 | # MSBuild Binary and Structured Log 335 | *.binlog 336 | 337 | # NVidia Nsight GPU debugger configuration file 338 | *.nvuser 339 | 340 | # MFractors (Xamarin productivity tool) working folder 341 | .mfractor/ 342 | 343 | # Local History for Visual Studio 344 | .localhistory/ 345 | 346 | # BeatPulse healthcheck temp database 347 | healthchecksdb 348 | 349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 350 | MigrationBackup/ 351 | 352 | # Ionide (cross platform F# VS Code tools) working folder 353 | .ionide/ 354 | -------------------------------------------------------------------------------- /AuthorizationServer/AuthorizationServer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /AuthorizationServer/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Security.Claims; 3 | using System.Threading.Tasks; 4 | using AuthorizationServer.ViewModels; 5 | using Microsoft.AspNetCore.Authentication; 6 | using Microsoft.AspNetCore.Authentication.Cookies; 7 | using Microsoft.AspNetCore.Authorization; 8 | using Microsoft.AspNetCore.Mvc; 9 | 10 | namespace AuthorizationServer.Controllers 11 | { 12 | public class AccountController : Controller 13 | { 14 | [HttpGet] 15 | [AllowAnonymous] 16 | public IActionResult Login(string returnUrl = null) 17 | { 18 | ViewData["ReturnUrl"] = returnUrl; 19 | return View(); 20 | } 21 | 22 | [HttpPost] 23 | [AllowAnonymous] 24 | [ValidateAntiForgeryToken] 25 | public async Task Login(LoginViewModel model) 26 | { 27 | ViewData["ReturnUrl"] = model.ReturnUrl; 28 | 29 | if (ModelState.IsValid) 30 | { 31 | var claims = new List 32 | { 33 | new Claim(ClaimTypes.Name, model.Username) 34 | }; 35 | 36 | var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); 37 | 38 | await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity)); 39 | 40 | if (Url.IsLocalUrl(model.ReturnUrl)) 41 | { 42 | return Redirect(model.ReturnUrl); 43 | } 44 | 45 | return RedirectToAction(nameof(HomeController.Index), "Home"); 46 | } 47 | 48 | return View(model); 49 | } 50 | 51 | public async Task Logout() 52 | { 53 | await HttpContext.SignOutAsync(); 54 | 55 | return RedirectToAction(nameof(HomeController.Index), "Home"); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /AuthorizationServer/Controllers/AuthorizationController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Authentication; 8 | using Microsoft.AspNetCore.Authentication.Cookies; 9 | using Microsoft.AspNetCore.Authorization; 10 | using Microsoft.AspNetCore.Http; 11 | using Microsoft.AspNetCore.Mvc; 12 | using OpenIddict.Abstractions; 13 | using OpenIddict.Server.AspNetCore; 14 | 15 | namespace AuthorizationServer.Controllers 16 | { 17 | public class AuthorizationController : Controller 18 | { 19 | [HttpGet("~/connect/authorize")] 20 | [HttpPost("~/connect/authorize")] 21 | [IgnoreAntiforgeryToken] 22 | public async Task Authorize() 23 | { 24 | var request = HttpContext.GetOpenIddictServerRequest() ?? 25 | throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); 26 | 27 | // Retrieve the user principal stored in the authentication cookie. 28 | var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); 29 | 30 | // If the user principal can't be extracted, redirect the user to the login page. 31 | if (!result.Succeeded) 32 | { 33 | return Challenge( 34 | authenticationSchemes: CookieAuthenticationDefaults.AuthenticationScheme, 35 | properties: new AuthenticationProperties 36 | { 37 | RedirectUri = Request.PathBase + Request.Path + QueryString.Create( 38 | Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList()) 39 | }); 40 | } 41 | 42 | // Create a new claims principal 43 | var claims = new List 44 | { 45 | // 'subject' claim which is required 46 | new Claim(OpenIddictConstants.Claims.Subject, result.Principal.Identity.Name), 47 | new Claim("some claim", "some value").SetDestinations(OpenIddictConstants.Destinations.AccessToken), 48 | new Claim(OpenIddictConstants.Claims.Email, "some@email").SetDestinations(OpenIddictConstants.Destinations.IdentityToken) 49 | }; 50 | 51 | var claimsIdentity = new ClaimsIdentity(claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); 52 | 53 | var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); 54 | 55 | // Set requested scopes (this is not done automatically) 56 | claimsPrincipal.SetScopes(request.GetScopes()); 57 | 58 | // Signing in with the OpenIddict authentiction scheme trigger OpenIddict to issue a code (which can be exchanged for an access token) 59 | return SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); 60 | } 61 | 62 | [HttpPost("~/connect/token")] 63 | public async Task Exchange() 64 | { 65 | var request = HttpContext.GetOpenIddictServerRequest() ?? 66 | throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); 67 | 68 | ClaimsPrincipal claimsPrincipal; 69 | 70 | if (request.IsClientCredentialsGrantType()) 71 | { 72 | // Note: the client credentials are automatically validated by OpenIddict: 73 | // if client_id or client_secret are invalid, this action won't be invoked. 74 | 75 | var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); 76 | 77 | // Subject (sub) is a required field, we use the client id as the subject identifier here. 78 | identity.AddClaim(OpenIddictConstants.Claims.Subject, request.ClientId ?? throw new InvalidOperationException()); 79 | 80 | // Add some claim, don't forget to add destination otherwise it won't be added to the access token. 81 | identity.AddClaim("some-claim", "some-value", OpenIddictConstants.Destinations.AccessToken); 82 | 83 | claimsPrincipal = new ClaimsPrincipal(identity); 84 | 85 | claimsPrincipal.SetScopes(request.GetScopes()); 86 | } 87 | 88 | else if (request.IsAuthorizationCodeGrantType()) 89 | { 90 | // Retrieve the claims principal stored in the authorization code 91 | claimsPrincipal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal; 92 | } 93 | 94 | else if (request.IsRefreshTokenGrantType()) 95 | { 96 | // Retrieve the claims principal stored in the refresh token. 97 | claimsPrincipal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal; 98 | } 99 | 100 | else 101 | { 102 | throw new InvalidOperationException("The specified grant type is not supported."); 103 | } 104 | 105 | // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens. 106 | return SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); 107 | } 108 | 109 | [Authorize(AuthenticationSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)] 110 | [HttpGet("~/connect/userinfo")] 111 | public async Task Userinfo() 112 | { 113 | var claimsPrincipal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal; 114 | 115 | return Ok(new 116 | { 117 | Name = claimsPrincipal.GetClaim(OpenIddictConstants.Claims.Subject), 118 | Occupation = "Developer", 119 | Age = 43 120 | }); 121 | } 122 | } 123 | } -------------------------------------------------------------------------------- /AuthorizationServer/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace AuthorizationServer.Controllers 4 | { 5 | public class HomeController : Controller 6 | { 7 | public IActionResult Index() 8 | { 9 | return View(); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /AuthorizationServer/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace AuthorizationServer 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /AuthorizationServer/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:41840", 7 | "sslPort": 44375 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "AuthorizationServer": { 19 | "commandName": "Project", 20 | "dotnetRunMessages": "true", 21 | "launchBrowser": true, 22 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /AuthorizationServer/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.Cookies; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | 8 | namespace AuthorizationServer 9 | { 10 | public class Startup 11 | { 12 | public void ConfigureServices(IServiceCollection services) 13 | { 14 | services.AddControllersWithViews(); 15 | 16 | services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) 17 | .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => 18 | { 19 | options.LoginPath = "/account/login"; 20 | }); 21 | 22 | services.AddDbContext(options => 23 | { 24 | // Configure the context to use an in-memory store. 25 | options.UseInMemoryDatabase(nameof(DbContext)); 26 | 27 | // Register the entity sets needed by OpenIddict. 28 | options.UseOpenIddict(); 29 | }); 30 | 31 | services.AddOpenIddict() 32 | 33 | // Register the OpenIddict core components. 34 | .AddCore(options => 35 | { 36 | // Configure OpenIddict to use the EF Core stores/models. 37 | options.UseEntityFrameworkCore() 38 | .UseDbContext(); 39 | }) 40 | 41 | // Register the OpenIddict server components. 42 | .AddServer(options => 43 | { 44 | options 45 | .AllowClientCredentialsFlow() 46 | .AllowAuthorizationCodeFlow() 47 | .RequireProofKeyForCodeExchange() 48 | .AllowRefreshTokenFlow(); 49 | 50 | options 51 | .SetTokenEndpointUris("/connect/token") 52 | .SetAuthorizationEndpointUris("/connect/authorize") 53 | .SetUserinfoEndpointUris("/connect/userinfo"); 54 | 55 | // Encryption and signing of tokens 56 | options 57 | .AddEphemeralEncryptionKey() 58 | .AddEphemeralSigningKey() 59 | .DisableAccessTokenEncryption(); 60 | 61 | // Register scopes (permissions) 62 | options.RegisterScopes("api"); 63 | 64 | // Register the ASP.NET Core host and configure the ASP.NET Core-specific options. 65 | options 66 | .UseAspNetCore() 67 | .EnableTokenEndpointPassthrough() 68 | .EnableAuthorizationEndpointPassthrough() 69 | .EnableUserinfoEndpointPassthrough(); 70 | }); 71 | 72 | services.AddHostedService(); 73 | } 74 | 75 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 76 | { 77 | if (env.IsDevelopment()) 78 | { 79 | app.UseDeveloperExceptionPage(); 80 | } 81 | 82 | app.UseStaticFiles(); 83 | 84 | app.UseRouting(); 85 | 86 | app.UseAuthentication(); 87 | 88 | app.UseAuthorization(); 89 | 90 | app.UseEndpoints(endpoints => 91 | { 92 | endpoints.MapDefaultControllerRoute(); 93 | }); 94 | } 95 | } 96 | } -------------------------------------------------------------------------------- /AuthorizationServer/TestData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using OpenIddict.Abstractions; 8 | 9 | namespace AuthorizationServer 10 | { 11 | public class TestData : IHostedService 12 | { 13 | private readonly IServiceProvider _serviceProvider; 14 | 15 | public TestData(IServiceProvider serviceProvider) 16 | { 17 | _serviceProvider = serviceProvider; 18 | } 19 | 20 | public async Task StartAsync(CancellationToken cancellationToken) 21 | { 22 | using var scope = _serviceProvider.CreateScope(); 23 | 24 | var context = scope.ServiceProvider.GetRequiredService(); 25 | await context.Database.EnsureCreatedAsync(cancellationToken); 26 | 27 | var manager = scope.ServiceProvider.GetRequiredService(); 28 | 29 | if (await manager.FindByClientIdAsync("postman", cancellationToken) is null) 30 | { 31 | await manager.CreateAsync(new OpenIddictApplicationDescriptor 32 | { 33 | ClientId = "postman", 34 | ClientSecret = "postman-secret", 35 | DisplayName = "Postman", 36 | RedirectUris = { new Uri("https://oauth.pstmn.io/v1/callback") }, 37 | Permissions = 38 | { 39 | OpenIddictConstants.Permissions.Endpoints.Authorization, 40 | OpenIddictConstants.Permissions.Endpoints.Token, 41 | 42 | OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, 43 | OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, 44 | OpenIddictConstants.Permissions.GrantTypes.RefreshToken, 45 | 46 | OpenIddictConstants.Permissions.Prefixes.Scope + "api", 47 | OpenIddictConstants.Permissions.ResponseTypes.Code 48 | } 49 | }, cancellationToken); 50 | } 51 | } 52 | 53 | public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; 54 | } 55 | } -------------------------------------------------------------------------------- /AuthorizationServer/ViewModels/LoginViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace AuthorizationServer.ViewModels 4 | { 5 | public class LoginViewModel 6 | { 7 | [Required] 8 | public string Username { get; set; } 9 | [Required] 10 | public string Password { get; set; } 11 | public string ReturnUrl { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /AuthorizationServer/Views/Account/Login.cshtml: -------------------------------------------------------------------------------- 1 | @model AuthorizationServer.ViewModels.LoginViewModel 2 |
3 | 4 |
5 | 6 | 7 |
8 |

9 | 10 |

11 |
-------------------------------------------------------------------------------- /AuthorizationServer/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | @using Microsoft.AspNetCore.Authentication 2 | 3 | @if (User.Identity.IsAuthenticated) 4 | { 5 | var authenticationResult = await Context.AuthenticateAsync(); 6 | var issued = authenticationResult.Properties.Items[".issued"]; 7 | var expires = authenticationResult.Properties.Items[".expires"]; 8 |
9 |

You are signed in as

10 |

@User.Identity.Name

11 |
12 |
13 |
Issued
14 |
@issued
15 |
Expires
16 |
@expires
17 |
18 |
19 |

Sign out

20 |
21 | } 22 | 23 | @if (!User.Identity.IsAuthenticated) 24 | { 25 |
26 |

You are not signed in

27 |

Sign in

28 |
29 | } -------------------------------------------------------------------------------- /AuthorizationServer/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | OpenIddict - Authorization Server 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 |
17 |

18 | Authorization Server 19 |

20 |
21 |
22 |
23 |
24 | @RenderBody() 25 |
26 |
27 |
28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /AuthorizationServer/Views/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers -------------------------------------------------------------------------------- /AuthorizationServer/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "_Layout"; 3 | } -------------------------------------------------------------------------------- /AuthorizationServer/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /AuthorizationServer/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /AuthorizationServer/wwwroot/css/site.css: -------------------------------------------------------------------------------- 1 | :focus { 2 | outline: 0 !important; 3 | } 4 | .input-validation-error { 5 | border: 1px solid darkred; 6 | } 7 | form { 8 | width: 100%; 9 | } 10 | .form-control { 11 | border:0; 12 | border-radius: 0; 13 | border-bottom: 1px solid lightgray; 14 | font-size:0.9rem; 15 | } 16 | .form-control:focus{ 17 | border-bottom-color: lightgray; 18 | box-shadow: none; 19 | } 20 | .form-control.form-control-last { 21 | border-bottom: 0; 22 | } 23 | .form-control::placeholder { 24 | opacity: 0.6; 25 | } 26 | .form-control.input-validation-error { 27 | border: 1px solid darkred; 28 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Robin van der Knaap 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Authorization Server: OpenIddict 2 | Authorization Server implemented with [OpenIddict 3](https://github.com/openiddict/openiddict-core). 3 | 4 | This repository is part of a blog series: [Setting up an authorization server with OpenIddict](https://dev.to/robinvanderknaap/setting-up-an-authorization-server-with-openiddict-part-i-introduction-4jid). 5 | 6 | ## Prerequisites 7 | - [.NET 6](https://dotnet.microsoft.com/) 8 | 9 | ## Getting started 10 | Open up a terminal in the root folder 11 | 12 | dotnet run --project AuthorizationServer 13 | 14 | Visit [https://localhost:5001](https://localhost:5001). In case of certificate errors run the following command: 15 | 16 | dotnet dev-certs https --trust 17 | --------------------------------------------------------------------------------