Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Claims in HttpContext.User #4

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .vs/WebApi/xs/UserPrefs.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<Properties StartupConfiguration="{CA2E06B1-6D12-485E-83C9-769D909E59BF}|Default">
<MonoDevelop.Ide.Workbench>
<Pads>
<Pad Id="ProjectPad">
<State name="__root__">
<Node name="WebApi" expanded="True">
<Node name="WebApi" expanded="True">
<Node name="Entities" expanded="True" />
<Node name="Helpers" expanded="True">
<Node name="AuthorizeAttribute.cs" selected="True" />
</Node>
<Node name="Models" expanded="True" />
<Node name="Services" expanded="True" />
</Node>
</Node>
</State>
</Pad>
</Pads>
</MonoDevelop.Ide.Workbench>
<MonoDevelop.Ide.ItemProperties.WebApi PreferredExecutionTarget="/Applications/Google Chrome.app" />
<MonoDevelop.Ide.DebuggingService.PinnedWatches />
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" />
<MonoDevelop.Ide.DebuggingService.Breakpoints>
<BreakpointStore />
</MonoDevelop.Ide.DebuggingService.Breakpoints>
<MultiItemStartupConfigurations />
</Properties>
1 change: 1 addition & 0 deletions .vs/WebApi/xs/project-cache/WebApi-Debug.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions Controllers/UsersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ namespace WebApi.Controllers
[Route("[controller]")]
public class UsersController : ControllerBase
{
private IUserService _userService;
private readonly IUserService userService;

public UsersController(IUserService userService)
{
_userService = userService;
this.userService = userService;
}

[HttpPost("authenticate")]
public IActionResult Authenticate(AuthenticateRequest model)
{
var response = _userService.Authenticate(model);
var response = userService.Authenticate(model);

if (response == null)
return BadRequest(new { message = "Username or password is incorrect" });
Expand All @@ -30,7 +30,7 @@ public IActionResult Authenticate(AuthenticateRequest model)
[HttpGet]
public IActionResult GetAll()
{
var users = _userService.GetAll();
var users = userService.GetAll();
return Ok(users);
}
}
Expand Down
24 changes: 23 additions & 1 deletion Helpers/AuthorizeAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,40 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using WebApi.Entities;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
// We're checking here to see if the route has been decorated with an [AllowAnonymous] attribute. If it has, we skip authorization
// for the route. Doing this allows us to apply the [Authorize] attribute by default in the startup using:
//
// services.AddControllers().AddMvcOptions(x => x.Filters.Add(new AuthorizeAttribute()))
//
if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
{
var hasAllowAnonymousAttribute = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
.Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
if (hasAllowAnonymousAttribute)
{
return;
}
}

var user = (User)context.HttpContext.Items["User"];
if (user == null)

var userId = context.HttpContext.User.Claims.FirstOrDefault(x => x.Type == "id")?.Value;
if (userId == null)

{
// not logged in
context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
}
}
}
}
13 changes: 6 additions & 7 deletions Helpers/JwtMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebApi.Services;
Expand All @@ -26,12 +27,12 @@ public async Task Invoke(HttpContext context, IUserService userService)
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

if (token != null)
attachUserToContext(context, userService, token);
AttachUserToContext(context, userService, token);

await _next(context);
}

private void attachUserToContext(HttpContext context, IUserService userService, string token)
private void AttachUserToContext(HttpContext context, IUserService userService, string token)
{
try
{
Expand All @@ -43,15 +44,13 @@ private void attachUserToContext(HttpContext context, IUserService userService,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
// set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
ClockSkew = TimeSpan.Zero
ClockSkew = TimeSpan.Zero // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
}, out SecurityToken validatedToken);

var jwtToken = (JwtSecurityToken)validatedToken;
var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);

// attach user to context on successful jwt validation
context.Items["User"] = userService.GetById(userId);
var identity = new ClaimsIdentity(jwtToken.Claims);
context.User.AddIdentity(identity);
}
catch
{
Expand Down
16 changes: 16 additions & 0 deletions Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true
},
"profiles": {
"WebApi": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:24180",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
4 changes: 3 additions & 1 deletion Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ public Startup(IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
services.AddControllers()
//.AddMvcOptions(x => x.Filters.Add(new AuthorizeAttribute())) //Uncomment this line to add the authorize attribute to all route by default
;

// configure strongly typed settings object
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
Expand Down
17 changes: 17 additions & 0 deletions WebApi.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi", "WebApi.csproj", "{CA2E06B1-6D12-485E-83C9-769D909E59BF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CA2E06B1-6D12-485E-83C9-769D909E59BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CA2E06B1-6D12-485E-83C9-769D909E59BF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CA2E06B1-6D12-485E-83C9-769D909E59BF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CA2E06B1-6D12-485E-83C9-769D909E59BF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal