├── .github └── FUNDING.yml ├── .gitignore ├── ApiAuthDemo.sln ├── ApiAuthDemo ├── ApiAuthDemo.csproj ├── Controllers │ ├── AccountController.cs │ └── ValuesController.cs ├── GlobalUsings.cs ├── Infrastructure │ ├── BasicAuth │ │ ├── BasicAuthAttribute.cs │ │ └── BasicAuthFilter.cs │ └── Jwt │ │ └── TokenManagement.cs ├── Program.cs ├── Services │ └── UserService.cs ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── BasicAuthApiConsumer ├── BasicAuthApiConsumer.csproj └── Program.cs ├── LICENSE ├── README.md ├── basic-auth-edge.gif ├── swagger-auth.gif ├── swagger-auth.png └── swagger-json.png /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: changhuixu 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.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 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | 332 | CSharpLabs/RunExeFromWebApi/WebApi/App_Data/ 333 | -------------------------------------------------------------------------------- /ApiAuthDemo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29709.97 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiAuthDemo", "ApiAuthDemo\ApiAuthDemo.csproj", "{55564851-52F7-4E0B-8D0A-7680A6BD4209}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BasicAuthApiConsumer", "BasicAuthApiConsumer\BasicAuthApiConsumer.csproj", "{2170F03B-4973-493E-B238-AFD3242BD070}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {55564851-52F7-4E0B-8D0A-7680A6BD4209}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {55564851-52F7-4E0B-8D0A-7680A6BD4209}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {55564851-52F7-4E0B-8D0A-7680A6BD4209}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {55564851-52F7-4E0B-8D0A-7680A6BD4209}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {2170F03B-4973-493E-B238-AFD3242BD070}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {2170F03B-4973-493E-B238-AFD3242BD070}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {2170F03B-4973-493E-B238-AFD3242BD070}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {2170F03B-4973-493E-B238-AFD3242BD070}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {3717471C-DAA3-462B-BB97-FFF889368B8C} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /ApiAuthDemo/ApiAuthDemo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | 6 | 7 | 8 | true 9 | $(NoWarn);1591 10 | enable 11 | enable 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /ApiAuthDemo/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | namespace ApiAuthDemo.Controllers; 2 | 3 | [ApiController] 4 | [Route("[controller]")] 5 | public class AccountController(ILogger logger) : ControllerBase 6 | { 7 | /// 8 | /// JWT login 9 | /// 10 | /// 11 | /// 12 | /// 13 | /// 14 | [AllowAnonymous] 15 | [HttpPost("login")] 16 | public ActionResult Login([FromBody] LoginRequest request, [FromServices] IUserService userService, 17 | [FromServices] TokenManagement tokenManagement) 18 | { 19 | if (!ModelState.IsValid) 20 | { 21 | return BadRequest("Invalid Request"); 22 | } 23 | 24 | if (!userService.IsValidUser(request.UserName, request.Password)) 25 | { 26 | return BadRequest("Invalid Request"); 27 | } 28 | 29 | var claims = new[] 30 | { 31 | new Claim(ClaimTypes.Name,request.UserName) 32 | }; 33 | 34 | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenManagement.Secret)); 35 | var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); 36 | var jwtToken = new JwtSecurityToken( 37 | tokenManagement.Issuer, 38 | tokenManagement.Audience, 39 | claims, 40 | expires: DateTime.Now.AddMinutes(tokenManagement.AccessExpiration), 41 | signingCredentials: credentials); 42 | var token = new JwtSecurityTokenHandler().WriteToken(jwtToken); 43 | logger.LogInformation("User [{userName}] logged in the system.", request.UserName); 44 | return Ok(new LoginResult 45 | { 46 | UserName = request.UserName, 47 | JwtToken = token 48 | }); 49 | } 50 | } 51 | 52 | public class LoginRequest 53 | { 54 | /// 55 | /// 56 | /// 57 | /// admin 58 | [Required] 59 | [JsonPropertyName("username")] 60 | public string UserName { get; set; } = string.Empty; 61 | 62 | /// 63 | /// 64 | /// 65 | /// securePassword 66 | [Required] 67 | [JsonPropertyName("password")] 68 | public string Password { get; set; } = string.Empty; 69 | } 70 | 71 | public class LoginResult 72 | { 73 | /// 74 | /// 75 | /// 76 | /// admin 77 | public string UserName { get; set; } = string.Empty; 78 | public string JwtToken { get; set; } = string.Empty; 79 | } -------------------------------------------------------------------------------- /ApiAuthDemo/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | namespace ApiAuthDemo.Controllers; 2 | 3 | [ApiController] 4 | [Route("api/[controller]")] 5 | public class ValuesController(ILogger logger) : ControllerBase 6 | { 7 | /// 8 | /// API allows anonymous 9 | /// 10 | /// 11 | [HttpGet] 12 | [AllowAnonymous] 13 | public IEnumerable Get() 14 | { 15 | var rng = new Random(); 16 | return Enumerable.Range(1, 3).Select(_ => rng.Next(0, 100)); 17 | } 18 | 19 | /// 20 | /// API requires JWT auth 21 | /// 22 | /// 23 | [HttpGet("jwt")] 24 | [Authorize] 25 | public IEnumerable JwtAuth() 26 | { 27 | var username = User.Identity!.Name; 28 | logger.LogInformation("User [{username}] is visiting jwt auth", username); 29 | var rng = new Random(); 30 | return Enumerable.Range(1, 10).Select(_ => rng.Next(0, 100)); 31 | } 32 | 33 | /// 34 | /// API requires Basic auth 35 | /// 36 | /// 37 | [HttpGet("basic")] 38 | [BasicAuth] // You can optionally provide a specific realm --> [BasicAuth("my-realm")] 39 | public IEnumerable BasicAuth() 40 | { 41 | var username = User.FindFirstValue(ClaimTypes.NameIdentifier); 42 | logger.LogInformation("basic auth from User [{username}]", username); 43 | var rng = new Random(); 44 | return Enumerable.Range(1, 10).Select(_ => rng.Next(0, 100)); 45 | } 46 | 47 | [HttpGet("basic-logout")] 48 | [BasicAuth] 49 | [ApiExplorerSettings(IgnoreApi = true)] 50 | public IActionResult BasicAuthLogout() 51 | { 52 | logger.LogInformation("basic auth logout"); 53 | // NOTE: there's no good way to log out basic authentication. This method is a hack. 54 | HttpContext.Response.Headers.WWWAuthenticate = "Basic realm=\"My Realm\""; 55 | return new UnauthorizedResult(); 56 | } 57 | } -------------------------------------------------------------------------------- /ApiAuthDemo/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using ApiAuthDemo.Infrastructure.BasicAuth; 2 | global using Microsoft.AspNetCore.Authorization; 3 | global using Microsoft.AspNetCore.Mvc; 4 | global using System.Text.Json.Serialization; 5 | global using System.ComponentModel.DataAnnotations; 6 | global using System.IdentityModel.Tokens.Jwt; 7 | global using System.Security.Claims; 8 | global using System.Text; 9 | global using ApiAuthDemo.Infrastructure.Jwt; 10 | global using ApiAuthDemo.Services; 11 | global using Microsoft.IdentityModel.Tokens; -------------------------------------------------------------------------------- /ApiAuthDemo/Infrastructure/BasicAuth/BasicAuthAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace ApiAuthDemo.Infrastructure.BasicAuth; 2 | 3 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 4 | public class BasicAuthAttribute : TypeFilterAttribute 5 | { 6 | public BasicAuthAttribute(string realm = "My Realm") : base(typeof(BasicAuthFilter)) 7 | { 8 | Arguments = [realm]; 9 | } 10 | } -------------------------------------------------------------------------------- /ApiAuthDemo/Infrastructure/BasicAuth/BasicAuthFilter.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Http.Headers; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | 5 | namespace ApiAuthDemo.Infrastructure.BasicAuth; 6 | 7 | public class BasicAuthFilter : IAuthorizationFilter 8 | { 9 | private readonly string _realm; 10 | 11 | public BasicAuthFilter(string realm) 12 | { 13 | _realm = realm; 14 | if (string.IsNullOrWhiteSpace(_realm)) 15 | { 16 | throw new ArgumentNullException(nameof(realm), "Please provide a non-empty realm value."); 17 | } 18 | } 19 | public void OnAuthorization(AuthorizationFilterContext context) 20 | { 21 | try 22 | { 23 | var authHeader = context.HttpContext.Request.Headers.Authorization.ToString(); 24 | var authHeaderValue = AuthenticationHeaderValue.Parse(authHeader); 25 | if (authHeaderValue.Scheme.Equals(AuthenticationSchemes.Basic.ToString(), StringComparison.OrdinalIgnoreCase)) 26 | { 27 | var credentials = Encoding.UTF8 28 | .GetString(Convert.FromBase64String(authHeaderValue.Parameter ?? string.Empty)) 29 | .Split(':', 2); 30 | if (credentials.Length == 2) 31 | { 32 | if (IsAuthorized(context, credentials[0], credentials[1])) 33 | { 34 | context.HttpContext.User.AddIdentity(new ClaimsIdentity(new List 35 | { 36 | new(ClaimTypes.NameIdentifier, credentials[0]) 37 | })); 38 | return; 39 | } 40 | } 41 | } 42 | 43 | ReturnUnauthorizedResult(context); 44 | } 45 | catch (FormatException) 46 | { 47 | ReturnUnauthorizedResult(context); 48 | } 49 | } 50 | public bool IsAuthorized(AuthorizationFilterContext context, string username, string password) 51 | { 52 | var userService = context.HttpContext.RequestServices.GetRequiredService(); 53 | return userService.IsValidUser(username, password); 54 | } 55 | 56 | private void ReturnUnauthorizedResult(AuthorizationFilterContext context) 57 | { 58 | // Return 401 and a basic authentication challenge (causes browser to show login dialog) 59 | context.HttpContext.Response.Headers.WWWAuthenticate = $"Basic realm=\"{_realm}\""; 60 | context.Result = new UnauthorizedResult(); 61 | } 62 | } -------------------------------------------------------------------------------- /ApiAuthDemo/Infrastructure/Jwt/TokenManagement.cs: -------------------------------------------------------------------------------- 1 | namespace ApiAuthDemo.Infrastructure.Jwt; 2 | 3 | public class TokenManagement 4 | { 5 | public string Secret { get; set; } = string.Empty; 6 | public string Issuer { get; set; } = string.Empty; 7 | public string Audience { get; set; } = string.Empty; 8 | public int AccessExpiration { get; set; } 9 | public int RefreshExpiration { get; set; } 10 | } -------------------------------------------------------------------------------- /ApiAuthDemo/Program.cs: -------------------------------------------------------------------------------- 1 | namespace ApiAuthDemo; 2 | 3 | public class Program 4 | { 5 | public static void Main(string[] args) 6 | { 7 | CreateHostBuilder(args).Build().Run(); 8 | } 9 | 10 | public static IHostBuilder CreateHostBuilder(string[] args) => 11 | Host.CreateDefaultBuilder(args) 12 | .ConfigureWebHostDefaults(webBuilder => 13 | { 14 | webBuilder.UseStartup(); 15 | }); 16 | } -------------------------------------------------------------------------------- /ApiAuthDemo/Services/UserService.cs: -------------------------------------------------------------------------------- 1 | namespace ApiAuthDemo.Services; 2 | 3 | public interface IUserService 4 | { 5 | bool IsValidUser(string userName, string password); 6 | } 7 | 8 | public class UserService(ILogger logger) : IUserService 9 | { 10 | // you can inject database for user validation 11 | public bool IsValidUser(string userName, string password) 12 | { 13 | logger.LogInformation("Validating user [{userName}]", userName); 14 | if (string.IsNullOrWhiteSpace(userName)) 15 | { 16 | return false; 17 | } 18 | 19 | if (string.IsNullOrWhiteSpace(password)) 20 | { 21 | return false; 22 | } 23 | return true; 24 | } 25 | } -------------------------------------------------------------------------------- /ApiAuthDemo/Startup.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.OpenApi.Models; 4 | 5 | namespace ApiAuthDemo; 6 | 7 | public class Startup(IConfiguration configuration) 8 | { 9 | // This method gets called by the runtime. Use this method to add services to the container. 10 | public void ConfigureServices(IServiceCollection services) 11 | { 12 | services.AddControllers(); 13 | 14 | var token = configuration.GetRequiredSection("tokenManagement").Get()!; 15 | services.AddSingleton(token); 16 | services.AddAuthentication(x => 17 | { 18 | x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 19 | x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 20 | }).AddJwtBearer(x => 21 | { 22 | x.RequireHttpsMetadata = true; 23 | x.SaveToken = true; 24 | x.TokenValidationParameters = new TokenValidationParameters 25 | { 26 | ValidateIssuer = true, 27 | ValidIssuer = token.Issuer, 28 | ValidateIssuerSigningKey = true, 29 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)), 30 | ValidAudience = token.Audience, 31 | ValidateAudience = false 32 | }; 33 | }); 34 | 35 | services.AddSwaggerGen(c => 36 | { 37 | c.SwaggerDoc("v1", new OpenApiInfo 38 | { 39 | Version = "v1", 40 | Title = "API Auth Demo", 41 | Description = "A simple demo with JWT Auth APIs and Basic Auth APIs", 42 | Contact = new OpenApiContact 43 | { 44 | Name = "GitHub Repository", 45 | Email = string.Empty, 46 | Url = new Uri("https://github.com/dotnet-labs/ApiAuthDemo") 47 | } 48 | }); 49 | var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; 50 | var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); 51 | c.IncludeXmlComments(xmlPath, true); 52 | 53 | // add JWT Authentication 54 | var securityScheme = new OpenApiSecurityScheme 55 | { 56 | Name = "JWT Authentication", 57 | Description = "Enter JWT Bearer token **_only_**", 58 | In = ParameterLocation.Header, 59 | Type = SecuritySchemeType.Http, 60 | Scheme = "bearer", // must be lowercase 61 | BearerFormat = "JWT", 62 | Reference = new OpenApiReference 63 | { 64 | Id = JwtBearerDefaults.AuthenticationScheme, 65 | Type = ReferenceType.SecurityScheme 66 | } 67 | }; 68 | c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme); 69 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 70 | { 71 | {securityScheme, Array.Empty()} 72 | }); 73 | 74 | // add Basic Authentication 75 | var basicSecurityScheme = new OpenApiSecurityScheme 76 | { 77 | Type = SecuritySchemeType.Http, 78 | Scheme = "basic", 79 | Reference = new OpenApiReference { Id = "BasicAuth", Type = ReferenceType.SecurityScheme } 80 | }; 81 | c.AddSecurityDefinition(basicSecurityScheme.Reference.Id, basicSecurityScheme); 82 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 83 | { 84 | {basicSecurityScheme, Array.Empty()} 85 | }); 86 | }); 87 | 88 | services.AddScoped(); 89 | } 90 | 91 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 92 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 93 | { 94 | if (env.IsDevelopment()) 95 | { 96 | app.UseDeveloperExceptionPage(); 97 | } 98 | app.UseHsts(); 99 | app.UseHttpsRedirection(); 100 | 101 | app.UseSwagger(); 102 | app.UseSwaggerUI(c => 103 | { 104 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"); 105 | c.DocumentTitle = "API Auth Demo"; 106 | c.DefaultModelsExpandDepth(0); 107 | c.RoutePrefix = string.Empty; 108 | }); 109 | 110 | app.UseRouting(); 111 | app.UseAuthentication(); 112 | app.UseAuthorization(); 113 | 114 | app.UseEndpoints(endpoints => 115 | { 116 | endpoints.MapControllers(); 117 | }); 118 | } 119 | } -------------------------------------------------------------------------------- /ApiAuthDemo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ApiAuthDemo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "tokenManagement": { 11 | "secret": "1234567890123456789", 12 | "issuer": "https://mywebapi.com", 13 | "audience": "My WebApi Users", 14 | "accessExpiration": 20, 15 | "refreshExpiration": 60 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /BasicAuthApiConsumer/BasicAuthApiConsumer.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /BasicAuthApiConsumer/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Http.Headers; 3 | using System.Text; 4 | 5 | const string url = "https://localhost:44389"; 6 | const string userName = "admin"; 7 | const string password = "p@s5w0rd"; 8 | 9 | var httpClient = new HttpClient(); 10 | httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( 11 | AuthenticationSchemes.Basic.ToString(), 12 | Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userName}:{password}")) 13 | ); 14 | var response = await httpClient.GetAsync($"{url}/api/values/basic"); 15 | response.EnsureSuccessStatusCode(); 16 | var result = await response.Content.ReadAsStringAsync(); 17 | Console.WriteLine(result); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Changhui Xu 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 | # JWT auth and Basic auth, Swagger UI Security Configuration 2 | 3 | [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I3I63W4OK) 4 | 5 | This repository demos a Web API project, `ApiAuthDemo`, which is configured to use JWT authentication globally, and some action methods can be configured to use Basic Auth using an attribute. The demo website root is its Swagger user interface. 6 | 7 | There is another Console app `BasicAuthApiConsumer`, which is a demo to consume a Basic Authentication API endpoint. The Console app needs to run after you start the `ApiAuthDemo` website, and you can adjust the URL in the Console program accordingly. 8 | 9 | ## Medium Articles 10 | 11 | ### [Basic Authentication](https://codeburst.io/adding-basic-authentication-to-an-asp-net-core-web-api-project-5439c4cf78ee) 12 | 13 | > How to add Basic Authentication to an ASP.NET Core 3 Web API project. 14 | 15 | ### [API Security in Swagger](https://codeburst.io/api-security-in-swagger-f2afff82fb8e) 16 | 17 | > How to configure security schemes for our API documentation in Swagger. 18 | 19 | ## Screen recordings 20 | 21 | ### Screen recording for an API with Basic Authentication 22 | 23 | ![Screen recording for an API with Basic Authentication](./basic-auth-edge.gif) 24 | 25 | ### Screen recording for API authentication in Swagger UI 26 | 27 | ![Screen recording for API authentication in Swagger UI](./swagger-auth.gif) 28 | 29 | ## License 30 | 31 | Feel free to use the code in this repository as it is under MIT license. 32 | 33 | [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I3I63W4OK) 34 | -------------------------------------------------------------------------------- /basic-auth-edge.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-labs/ApiAuthDemo/fb7561c7dd00209e7a1280bb8e1abc3cd07b7587/basic-auth-edge.gif -------------------------------------------------------------------------------- /swagger-auth.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-labs/ApiAuthDemo/fb7561c7dd00209e7a1280bb8e1abc3cd07b7587/swagger-auth.gif -------------------------------------------------------------------------------- /swagger-auth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-labs/ApiAuthDemo/fb7561c7dd00209e7a1280bb8e1abc3cd07b7587/swagger-auth.png -------------------------------------------------------------------------------- /swagger-json.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-labs/ApiAuthDemo/fb7561c7dd00209e7a1280bb8e1abc3cd07b7587/swagger-json.png --------------------------------------------------------------------------------