{"id":41020106,"url":"https://github.com/ivanclay/dotnet-aspnetcore-mvc","last_synced_at":"2026-01-22T09:32:35.762Z","repository":{"id":310229445,"uuid":"1039129755","full_name":"ivanclay/dotnet-aspnetcore-mvc","owner":"ivanclay","description":null,"archived":false,"fork":false,"pushed_at":"2025-08-16T17:33:51.000Z","size":1147,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-16T17:33:57.130Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ivanclay.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-08-16T14:44:32.000Z","updated_at":"2025-08-16T17:33:54.000Z","dependencies_parsed_at":"2025-08-16T17:48:20.993Z","dependency_job_id":null,"html_url":"https://github.com/ivanclay/dotnet-aspnetcore-mvc","commit_stats":null,"previous_names":["ivanclay/dotnet-aspnetcore-mvc"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/ivanclay/dotnet-aspnetcore-mvc","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ivanclay%2Fdotnet-aspnetcore-mvc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ivanclay%2Fdotnet-aspnetcore-mvc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ivanclay%2Fdotnet-aspnetcore-mvc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ivanclay%2Fdotnet-aspnetcore-mvc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ivanclay","download_url":"https://codeload.github.com/ivanclay/dotnet-aspnetcore-mvc/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ivanclay%2Fdotnet-aspnetcore-mvc/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28660770,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-22T01:17:37.254Z","status":"online","status_checked_at":"2026-01-22T02:00:07.137Z","response_time":144,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-01-22T09:32:35.696Z","updated_at":"2026-01-22T09:32:35.751Z","avatar_url":"https://github.com/ivanclay.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🔐 ASP.NET Core JWT Authentication\n## MVC \u0026 Web API Integration\n\nThis project demonstrates a clean and modular implementation of JWT-based authentication using ASP.NET Core MVC and Web API. It includes token generation, validation, and middleware integration to secure endpoints and enable role-based access control.\n\n---\n\n## 📁 Project Structure\n\n- `Auth.WebAPI`: Responsible for issuing JWT tokens via a login endpoint.\n- `Auth.MVC`: A client application that consumes the token and accesses protected resources.\n- `AuthService`: Encapsulates token generation logic using `System.IdentityModel.Tokens.Jwt`.\n\n---\n\n## 🚀 Getting Started\n\n### Prerequisites\n\n- [.NET 6.0+](https://dotnet.microsoft.com/en-us/download)\n- Visual Studio or VS Code\n- Postman or any HTTP client for testing\n\n---\n\n## ⚙️ Configuration\n\nEnsure your `appsettings.json` contains the following section:\n\n```json\n\"Jwt\": {\n  \"Key\": \"your-secure-key\",\n  \"Issuer\": \"AuthApp\",\n  \"Audience\": \"AuthApp\"\n}\n```\n\n---\n\n## 🔧 Web API Setup (`Auth.WebAPI`)\n\n### `AuthService.cs`\n\nHandles token creation with embedded claims:\n\n```csharp\npublic class AuthService\n{\n    private readonly IConfiguration _config;\n\n    public AuthService(IConfiguration config)\n    {\n        _config = config;\n    }\n\n    public string GenerateToken(string username, string role, string profile)\n    {\n        var claims = new[]\n        {\n            new Claim(ClaimTypes.Name, username),\n            new Claim(ClaimTypes.Role, role),\n            new Claim(\"profile\", profile)\n        };\n\n        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config[\"Jwt:Key\"]));\n        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);\n\n        var token = new JwtSecurityToken(\n            issuer: _config[\"Jwt:Issuer\"],\n            audience: _config[\"Jwt:Audience\"],\n            claims: claims,\n            expires: DateTime.UtcNow.AddHours(1),\n            signingCredentials: creds);\n\n        return new JwtSecurityTokenHandler().WriteToken(token);\n    }\n}\n```\n\n### `AuthController.cs`\n\nExposes a login endpoint that returns a JWT upon successful authentication:\n\n```csharp\n[HttpPost(\"login\")]\npublic IActionResult Login([FromBody] LoginModel model)\n{\n    if (model.Username == \"ivan\" \u0026\u0026 model.Password == \"123\")\n    {\n        var token = _authService.GenerateToken(model.Username, \"Admin\", \"Finance\");\n        return Ok(new { token });\n    }\n\n    return Unauthorized();\n}\n```\n\n---\n\n## 🖥️ MVC Client Setup (`Auth.MVC`)\n\n### `Program.cs`\n\nConfigures authentication and authorization using JWT Bearer:\n\n```csharp\nbuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddJwtBearer(options =\u003e\n    {\n        options.RequireHttpsMetadata = false;\n        options.TokenValidationParameters = new TokenValidationParameters\n        {\n            ValidateIssuer = true,\n            ValidateAudience = true,\n            ValidateLifetime = true,\n            ValidateIssuerSigningKey = true,\n            ValidIssuer = \"AuthApp\",\n            ValidAudience = \"AuthApp\",\n            IssuerSigningKey = new SymmetricSecurityKey(\n                Encoding.UTF8.GetBytes(builder.Configuration[\"Jwt:Key\"]))\n        };\n    });\n```\n\n### Middleware Pipeline\n\n```csharp\napp.UseStaticFiles();\napp.UseRouting();\napp.UseMiddleware\u003cJwtMiddleware\u003e(); // Injects token into request headers\napp.UseAuthentication();            // Validates token\napp.UseAuthorization();             // Enforces policies\napp.MapDefaultControllerRoute();\n```\n\n---\n\n## 🔐 Securing Endpoints\n\nUse the `[Authorize]` attribute to protect controllers or actions:\n\n```csharp\n[Authorize(Roles = \"Admin\")]\npublic IActionResult Dashboard()\n{\n    return View();\n}\n```\n\n---\n\n## 🧪 Testing\n\n1. Send a `POST` request to `/api/auth/login` with valid credentials.\n2. Receive a JWT token in the response.\n3. Include the token in the `Authorization` header of MVC requests:\n   ```\n   Authorization: Bearer \u003cyour-token\u003e\n   ```\n4. Access protected routes and verify role-based access.\n\n---\n\n## 📌 Notes\n\n- Token expiration is set to 1 hour.\n- Claims include `Name`, `Role` and `Profile`.\n- Middleware ensures token is injected and validated before authorization.\n\n---\n\n## 🧠 Credits\n\nCrafted with care by me, with a focus on clarity, modularity, and security.  \nIf you find this helpful, feel free to fork, extend, or adapt it to your own needs.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fivanclay%2Fdotnet-aspnetcore-mvc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fivanclay%2Fdotnet-aspnetcore-mvc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fivanclay%2Fdotnet-aspnetcore-mvc/lists"}