@manhng

Welcome to my blog!

Authentication Authorization in ASP.NET CORE

April 9, 2021 18:10

Authentication Authorization in ASP.NET CORE (edit)

Getting

public class JwtMiddleware
{
private readonly RequestDelegate _next;

public JwtMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context, IJwtUtils jwtUtils)
{
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
var user = jwtUtils.ValidateJwtToken(token);
if (user != null)
{
context.Items["User"] = user;
}

await _next(context);
}
}

Setting

public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter
{
private readonly string[] allowedRoles;

public CustomAuthorizeAttribute(params string[] roles)
{
allowedRoles = roles;
}

public void OnAuthorization(AuthorizationFilterContext context)
{
var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
if (allowAnonymous)
return;

var user = context.HttpContext.Items["User"] as AdminUserToken;
var roles = user?.Roles;
var intersectRoles = roles == null ? new string[] { } : allowedRoles.Intersect(roles);
var isUnauthorized = intersectRoles == null || intersectRoles.Count() == 0;
if (roles == null || isUnauthorized)
context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
}
}

ASP.NET Core 2.2 - Basic Authentication Tutorial with Example API | Jason Watmore's Blog

ASP.NET Core Middleware | Microsoft Docs

Use cookie authentication without ASP.NET Core Identity | Microsoft Docs

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-5.0

https://www.red-gate.com/simple-talk/dotnet/net-development/using-auth-cookies-in-asp-net-core/

https://jakeydocs.readthedocs.io/en/latest/security/authentication/cookie.html

https://www.yogihosting.com/aspnet-core-cookie-authentication/

https://www.c-sharpcorner.com/article/cookie-authentication-in-net-core-3-0/

Samples (Microsoft.AspNetCore.Authentication.Cookies)

AspNetCore.Docs/aspnetcore/security/authentication/cookie/samples at main · dotnet/AspNetCore.Docs · GitHub

FormsAuthentication
FormsAuthenticationTicket
HttpCookie
FormsAuthentication.SetAuthCookie

HttpContext.Current.User.Identity.Name
HttpContext.Current.Session
HttpRuntime.Cache.Insert

Categories

Recent posts