forked from explorer14/JwtAuthenticationHelper
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactored out a method in the IServiceCollection extension class tha…
…t allows adding JWT Bearer auth without cookies for WebAPIs. Also, added a sample API implementation showing Policy based claims/roles check
- Loading branch information
1 parent
a646811
commit 50f69f4
Showing
16 changed files
with
347 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
79 changes: 79 additions & 0 deletions
79
JwtTokenAuthRefImplementation.API/Controllers/AuthController.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Security.Claims; | ||
using System.Threading.Tasks; | ||
using JwtAuthenticationHelper.Abstractions; | ||
using Microsoft.AspNetCore.Authentication; | ||
using Microsoft.AspNetCore.Authorization; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace JwtTokenAuthRefImplementation.API.Controllers | ||
{ | ||
[Produces("application/json")] | ||
[Route("api/auth")] | ||
[ApiController] | ||
public class AuthController : Controller | ||
{ | ||
private readonly IJwtTokenGenerator jwtTokenGenerator; | ||
|
||
public AuthController(IJwtTokenGenerator jwtTokenGenerator) | ||
{ | ||
this.jwtTokenGenerator = jwtTokenGenerator; | ||
} | ||
|
||
[HttpPost("login")] | ||
[AllowAnonymous] | ||
public async Task<IActionResult> Login([FromBody]UserCredentials userCredentials) | ||
{ | ||
// Replace this with your custom authentication logic which will | ||
// securely return the authenticated user's details including | ||
// any role specific info | ||
if (userCredentials.Username == "user1" && userCredentials.Password == "pass1") | ||
{ | ||
var userInfo = new UserInfo | ||
{ | ||
FirstName = "UserFName", | ||
LastName = "UserLName", | ||
HasAdminRights = true | ||
}; | ||
|
||
var accessTokenResult = jwtTokenGenerator.GenerateAccessTokenWithClaimsPrincipal( | ||
userCredentials.Username, | ||
AddMyClaims(userInfo)); | ||
|
||
return Ok(accessTokenResult.AccessToken); | ||
} | ||
else | ||
{ | ||
return Unauthorized(); | ||
} | ||
} | ||
|
||
private static IEnumerable<Claim> AddMyClaims(UserInfo authenticatedUser) | ||
{ | ||
var myClaims = new List<Claim> | ||
{ | ||
new Claim(ClaimTypes.GivenName, authenticatedUser.FirstName), | ||
new Claim(ClaimTypes.Surname, authenticatedUser.LastName), | ||
new Claim("HasAdminRights", authenticatedUser.HasAdminRights ? "Y" : "N") | ||
}; | ||
|
||
return myClaims; | ||
} | ||
} | ||
|
||
internal class UserInfo | ||
{ | ||
public string FirstName { get; set; } | ||
public string LastName { get; set; } | ||
public bool HasAdminRights { get; set; } | ||
} | ||
|
||
public class UserCredentials | ||
{ | ||
public string Username { get; set; } | ||
public string Password { get; set; } | ||
} | ||
} |
47 changes: 47 additions & 0 deletions
47
JwtTokenAuthRefImplementation.API/Controllers/ValuesController.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Authorization; | ||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace JwtTokenAuthRefImplementation.API.Controllers | ||
{ | ||
[Route("api/[controller]")] | ||
[ApiController] | ||
[Authorize(Policy = "RequiresAdmin")] | ||
public class ValuesController : ControllerBase | ||
{ | ||
// GET api/values | ||
[HttpGet] | ||
public IEnumerable<string> Get() | ||
{ | ||
return new string[] { "value1", "value2" }; | ||
} | ||
|
||
// GET api/values/5 | ||
[HttpGet("{id}")] | ||
public string Get(int id) | ||
{ | ||
return "value"; | ||
} | ||
|
||
// POST api/values | ||
[HttpPost] | ||
public void Post([FromBody] string value) | ||
{ | ||
} | ||
|
||
// PUT api/values/5 | ||
[HttpPut("{id}")] | ||
public void Put(int id, [FromBody] string value) | ||
{ | ||
} | ||
|
||
// DELETE api/values/5 | ||
[HttpDelete("{id}")] | ||
public void Delete(int id) | ||
{ | ||
} | ||
} | ||
} |
24 changes: 24 additions & 0 deletions
24
JwtTokenAuthRefImplementation.API/JwtTokenAuthRefImplementation.API.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>netcoreapp2.1</TargetFramework> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Folder Include="wwwroot\" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.0-preview1-final" /> | ||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0-preview1-final" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.1.0-preview1-final" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\JwtAuthenticationHelper\JwtAuthenticationHelper.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace JwtTokenAuthRefImplementation.API | ||
{ | ||
public class Program | ||
{ | ||
public static void Main(string[] args) | ||
{ | ||
CreateWebHostBuilder(args).Build().Run(); | ||
} | ||
|
||
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => | ||
WebHost.CreateDefaultBuilder(args) | ||
.UseStartup<Startup>(); | ||
} | ||
} |
28 changes: 28 additions & 0 deletions
28
JwtTokenAuthRefImplementation.API/Properties/launchSettings.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
{ | ||
"iisSettings": { | ||
"windowsAuthentication": false, | ||
"anonymousAuthentication": true, | ||
"iisExpress": { | ||
"applicationUrl": "http://localhost:49686", | ||
"sslPort": 44391 | ||
} | ||
}, | ||
"profiles": { | ||
"IIS Express": { | ||
"commandName": "IISExpress", | ||
"launchBrowser": true, | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development", | ||
"ASPNETCORE_HTTPS_PORT": "44391" | ||
} | ||
}, | ||
"JwtTokenAuthRefImplementation.API": { | ||
"commandName": "Project", | ||
"launchBrowser": true, | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development", | ||
"ASPNETCORE_URLS": "https://localhost:5001;http://localhost:5000" | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
using JwtAuthenticationHelper.Extensions; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.IdentityModel.Tokens; | ||
using System; | ||
using System.Text; | ||
|
||
namespace JwtTokenAuthRefImplementation.API | ||
{ | ||
public class Startup | ||
{ | ||
public Startup(IConfiguration configuration) | ||
{ | ||
Configuration = configuration; | ||
} | ||
|
||
public IConfiguration Configuration { get; } | ||
|
||
// This method gets called by the runtime. Use this method to add services to the container. | ||
public void ConfigureServices(IServiceCollection services) | ||
{ | ||
// retrieve the configured token params and establish a TokenValidationParameters object, | ||
// we are going to need this later. | ||
var validationParams = new TokenValidationParameters | ||
{ | ||
ClockSkew = TimeSpan.Zero, | ||
|
||
ValidateAudience = true, | ||
ValidAudience = Configuration["Token:Audience"], | ||
|
||
ValidateIssuer = true, | ||
ValidIssuer = Configuration["Token:Issuer"], | ||
|
||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Token:SigningKey"])), | ||
ValidateIssuerSigningKey = true, | ||
|
||
RequireExpirationTime = true, | ||
ValidateLifetime = true | ||
}; | ||
|
||
services.AddJwtAuthenticationForAPI(validationParams); | ||
services.AddAuthorization(options => | ||
{ | ||
options.AddPolicy("RequiresAdmin", policy => policy.RequireClaim("HasAdminRights")); | ||
}); | ||
|
||
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); | ||
} | ||
|
||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | ||
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | ||
{ | ||
if (env.IsDevelopment()) | ||
{ | ||
app.UseDeveloperExceptionPage(); | ||
} | ||
else | ||
{ | ||
app.UseHsts(); | ||
} | ||
|
||
app.UseHttpsRedirection(); | ||
app.UseAuthentication(); | ||
app.UseMvc(); | ||
} | ||
} | ||
} |
14 changes: 14 additions & 0 deletions
14
JwtTokenAuthRefImplementation.API/appsettings.Development.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Debug", | ||
"System": "Information", | ||
"Microsoft": "Information" | ||
} | ||
}, | ||
"Token": { | ||
"Issuer": "Token.WebAPI", | ||
"Audience": "Token.WebAPI.Clients", | ||
"SigningKey": "d739d787-c3b3-47e6-aaba-2814c17551ab" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Warning" | ||
} | ||
} | ||
} |
Oops, something went wrong.