first time include all file
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
using System;
|
||||
|
||||
namespace CarParkValidationAPI.Authorization
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public class AllowAnonymousAttribute : Attribute
|
||||
{ }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace CarParkValidationAPI.Models.Users
|
||||
{
|
||||
public class AuthenticateRequest
|
||||
{
|
||||
[Required]
|
||||
public string Username { get; set; }
|
||||
|
||||
[Required]
|
||||
public string Password { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using CarParkValidationAPI.Entities;
|
||||
|
||||
|
||||
public class AuthenticateResponse
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
public string Username { get; set; }
|
||||
public int? Role { get; set; }
|
||||
public int ValidationPointId { get; set; }
|
||||
public string Token { get; set; }
|
||||
public string Email { get; set; }
|
||||
public AuthenticateResponse(User user, string token)
|
||||
{
|
||||
Id = user.Id;
|
||||
FirstName = user.FirstName;
|
||||
LastName = user.LastName;
|
||||
Username = user.Username;
|
||||
Email = user.Email;
|
||||
Role = user.Role;
|
||||
Token = token;
|
||||
ValidationPointId = user.ValidationPointId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CarParkValidationAPI.Entities;
|
||||
using CarParkValidationAPI.Models;
|
||||
|
||||
namespace CarParkValidationAPI.Authorization
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
|
||||
{
|
||||
private readonly IList<AdminRole> _roles;
|
||||
|
||||
public AuthorizeAttribute(params AdminRole[] roles)
|
||||
{
|
||||
_roles = roles ?? new AdminRole[] { };
|
||||
}
|
||||
|
||||
public void OnAuthorization(AuthorizationFilterContext context)
|
||||
{
|
||||
// skip authorization if action is decorated with [AllowAnonymous] attribute
|
||||
var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
|
||||
if (allowAnonymous)
|
||||
return;
|
||||
|
||||
// authorization
|
||||
var user = (User)context.HttpContext.Items["User"];
|
||||
|
||||
if (user == null || (_roles.Any() && !_roles.Contains((AdminRole)user.Role)))
|
||||
{
|
||||
// not logged in or role not authorized
|
||||
context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CarParkValidationAPI.Models;
|
||||
using CarParkValidationAPI.Interface;
|
||||
|
||||
|
||||
namespace CarParkValidationAPI.Authorization
|
||||
{
|
||||
public class JwtMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings)
|
||||
{
|
||||
private readonly AppSettings _appSettings = appSettings.Value;
|
||||
|
||||
public async Task Invoke(HttpContext context, IUserService userService, IJwtUtils jwtUtils)
|
||||
{
|
||||
|
||||
string? token = context.Request.Headers.Authorization.FirstOrDefault()?.Split(" ").Last();
|
||||
if (null == token)
|
||||
context.Request.Cookies.TryGetValue("token", out token);
|
||||
|
||||
var user = jwtUtils.ValidateJwtToken(token);
|
||||
if (user != null)
|
||||
{
|
||||
// attach user to context on successful jwt validation
|
||||
//here to put in the real user
|
||||
//TODO if you want to add information for User
|
||||
context.Items["User"] = user;
|
||||
}
|
||||
|
||||
await next(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using CarParkValidationAPI.Entities;
|
||||
using CarParkValidationAPI.Interface;
|
||||
using CarParkValidationAPI.Models;
|
||||
|
||||
namespace CarParkValidationAPI.Authorization
|
||||
{
|
||||
|
||||
|
||||
public class JwtUtils : IJwtUtils
|
||||
{
|
||||
private readonly AppSettings _appSettings;
|
||||
|
||||
public JwtUtils(IOptions<AppSettings> appSettings)
|
||||
{
|
||||
_appSettings = appSettings.Value;
|
||||
}
|
||||
|
||||
public string GenerateJwtToken(User user)
|
||||
{
|
||||
// generate token that is valid for 2 days
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(new[] {
|
||||
new Claim("id", user.Id.ToString()),
|
||||
new Claim("subject", user.Username)
|
||||
|
||||
//add more if we need it
|
||||
}
|
||||
),
|
||||
Expires = DateTime.UtcNow.AddDays(2),
|
||||
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
||||
};
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
return tokenHandler.WriteToken(token);
|
||||
}
|
||||
// get back id and username. in subject
|
||||
public User? ValidateJwtToken(string token)
|
||||
{
|
||||
if (token == null)
|
||||
return null;
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
|
||||
try
|
||||
{
|
||||
tokenHandler.ValidateToken(token, new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
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
|
||||
}, out SecurityToken validatedToken);
|
||||
|
||||
var jwtToken = (JwtSecurityToken)validatedToken;
|
||||
// var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value); //old
|
||||
int userId = 0;
|
||||
string username = "";
|
||||
Claim claim;
|
||||
for (int i = 0; i< jwtToken.Claims.Count(); i++)
|
||||
{
|
||||
claim = jwtToken.Claims.ElementAt(i);
|
||||
if (claim.Type == "id")
|
||||
{
|
||||
userId = int.Parse(claim.Value);
|
||||
}
|
||||
else if (claim.Type == "subject")
|
||||
{
|
||||
username = claim.Value;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(username) && userId > 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
User user = new();
|
||||
user.Id = userId;
|
||||
user.Username = username;
|
||||
|
||||
// return user id from JWT token if validation successful
|
||||
return user;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// return null if validation fails
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user