How to create a Custom Authorize Attribute by comparing User Id stored in table with Current User Id in Asp.net MVC 5?
Tag : chash , By : Richard Laksana
Date : March 29 2020, 07:55 AM
it fixes the issue I need to control access to edit method of my controller on the basis of user id i.e only that user can access the edit method who created that specific data. User Id is stored in the table EmpProfile UserID column and want to compare the current logged in user with the UserID stored and allow access on this basis. My Custom Authorize Attribute Code is: , In response to your comment: public ActionResult Edit(Int32? id) {
// Repeat the below logic for each action you want access-control in, ensure it is also in your POST handlers too.
if( !this.IsAuthorized() ) return this.Http401();
}
protected boolean IsAuthorized() {
if( this.Request.User.Identity.Name == "someoneIDontLike" ) return false;
return true;
}
protected ActionResult Http401(String message) {
this.Response.StatusCode = 401;
// This requires you to create your own custom HTTP 401 "Unauthorized" view file and viewmodel
return this.View( new Http401ViewModel(message) );
}
|
Application authorize and authenticate user with database
Tag : mysql , By : user184415
Date : March 29 2020, 07:55 AM
Hope this helps Honestly, your best approach is to follow best security practices around your server. You could use a salt, but the hash function will have to live on the server, too, and if a hacker has access to the server in the first place then it won't be long before they find the hash and pull the password. I think efficient organization actually produces some security through obscurity. That is, put the DB connect credentials and string in a config file. Still, access to the application code will give a hacker the clues to get what they want, but it doesn't mean you shouldn't follow best coding practices.
|
How to authorize service to use Microsoft Graph user account without user interaction?
Tag : azure , By : Kristian Hofslaeter
Date : March 29 2020, 07:55 AM
With these it helps Please try to click Grant Permissions(better using admin account) in "Required permissions" blade after granted "Have full access to all files user can access" permission for Microsoft Graph: After that acquire token using Resource Owner Password flow , you will find Files.ReadWrite.All in scp claims . Then you could call microsoft graph api to list files .
|
Is there a better way than using an IAsyncActionFilter to authorize if user is in role or user id is in database for spe
Tag : chash , By : jamerson
Date : March 29 2020, 07:55 AM
I hope this helps you . Requirement: There are some controller methods which only can be called if: , Is there a better way to do this (with ASP.NET Core)? public class RecordOwnerRequirement : IAuthorizationRequirement
{
}
public class RecordOwnerHandler : AuthorizationHandler<RecordOwnerRequirement>
{
private readonly ApplicationDbContext dbContext;
private readonly IActionContextAccessor actionContextAccessor;
public RecordOwnerHandler(ApplicationDbContext dbContext, IActionContextAccessor actionContextAccessor)
{
this.dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
this.actionContextAccessor = actionContextAccessor ?? throw new ArgumentNullException(nameof(actionContextAccessor));
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RecordOwnerRequirement requirement)
{
if (IsUserAuthorized(context))
{
context.Succeed(requirement);
}
//TODO: Use the following if targeting a version of
//.NET Framework older than 4.6:
// return Task.FromResult(0);
return Task.CompletedTask;
}
private bool IsUserAuthorized(AuthorizationHandlerContext context)
{
var id = this.actionContextAccessor.ActionContext.RouteData.Values["id"];
// Use the dbContext to compare the id against the database...
// Return the result
return true;
}
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
//*********************************************************************
// Add policy for record owner
services.AddAuthorization(options =>
{
options.AddPolicy("RecordOwner", policy =>
policy.Requirements.Add(new RecordOwnerRequirement()));
});
//*********************************************************************
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
//*********************************************************************
// Register record owner handler with the DI container
services.AddTransient<IAuthorizationHandler, RecordOwnerHandler>();
services.AddTransient<IActionContextAccessor, ActionContextAccessor>();
//*********************************************************************
services.AddMvc();
}
public class HomeController : Controller
{
[Authorize(Roles = "TaskAdmin", Policy = "RecordOwner")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
}
|
How to make a middleware that can call database to check user claims to authorize a user in asp.net core 2.2
Date : March 29 2020, 07:55 AM
wish helps you All you need is to create an AuthorizationHandler, please follow the instructions: 1- create a class and name it MinimumPermissionHandler or whatever. copy and paste following codes in it: public class MinimumPermissionRequirement : IAuthorizationRequirement { }
public class MinimumPermissionHandler : AuthorizationHandler<MinimumPermissionRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumPermissionRequirement requirement)
{
if (!(context.Resource is AuthorizationFilterContext filterContext))
{
context.Fail();
return Task.CompletedTask;
}
//check if token has subjectId
var subClaim = context.User?.Claims?.FirstOrDefault(c => c.Type == "sub");
if (subClaim == null)
{
context.Fail();
return Task.CompletedTask;
}
//check if token is expired
var exp = context.User.Claims.FirstOrDefault(c => c.Type == "exp")?.Value;
if(exp == null || new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(long.Parse(exp)).ToLocalTime() < DateTime.Now)
{
context.Fail();
return Task.CompletedTask;
}
//other checkpoints
//your db functions to check if user has desired claims
context.Succeed(requirement);
return Task.CompletedTask;
}
}
public void ConfigureServices(IServiceCollection services)
{
//deleted extra lines for brevity
services.AddAuthorization(options =>
{
options.AddPolicy("AccessControl", policy =>
{
policy.RequireAuthenticatedUser();
policy.AddRequirements(new MinimumPermissionRequirement());
});
});
//injection
services.AddScoped<IAuthorizationHandler, MinimumPermissionHandler>();
}
[Authorize(Policy = "AccessControl")]
|