How to add user to database and authorize user as well

How to add user to database and authorize user as well

Content Index :

How to add user to database and authorize user as well
Tag : angular , By : Alecsandru Soare
Date : January 12 2021, 08:33 AM

Any of those help I was able to answer my own question.
I went and studied promises in more detailed and learned that a promise can have chained .then functions. .then functions are called in order in which they are written and only fire when the previous promise has been completed.
  register(username:string, email:string, password:string)
    return new Promise ((resolve, reject) =>{
      .then( (userData) => {resolve(userData), 
      err => reject(err) 
        return userData}) //make sure to return the parameters you want to use in the next .then call.
      .then( (userData) => {
        console.log("The userData is +: " + userData.uid)


No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

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))

        //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 =>

    services.AddIdentity<ApplicationUser, IdentityRole>()

    // 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>();

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

Tag : chash , By : Mike
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))
            return Task.CompletedTask;

        //check if token has subjectId
        var subClaim = context.User?.Claims?.FirstOrDefault(c => c.Type == "sub");
        if (subClaim == null)
            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)
            return Task.CompletedTask;

        //other checkpoints
        //your db functions to check if user has desired claims

        return Task.CompletedTask;
public void ConfigureServices(IServiceCollection services)
   //deleted extra lines for brevity 
   services.AddAuthorization(options =>
      options.AddPolicy("AccessControl", policy =>
           policy.AddRequirements(new MinimumPermissionRequirement());
   services.AddScoped<IAuthorizationHandler, MinimumPermissionHandler>();
[Authorize(Policy = "AccessControl")]
Related Posts Related QUESTIONS :
  • font size increase decrease by button using angular 7
  • Are selectors and module declarations mandatory for components?
  • Why angular is adding '#' in each route?
  • how to block the subsequent clicks in angular?
  • Ionic Angular TypeError: architect_1.createBuilder is not a function
  • Angular app doesn't work on Firefox after updating it to Version 8
  • Angular: Formatting numbers percentage
  • Matrix in FormGroup [Angular 2+]
  • "export 'DOCUMENT' was not found in '@angular/platform-browser'
  • angular autocomplete material
  • Prevent click event from triggering other click elements undernethe the front element
  • How to know when an image has been fully loaded in angular?
  • How to read config file to set API URL inside an Angular App packaged as a WAR and deployed on IBM Liberty
  • npm ERR! Unexpected end of JSON input while parsing near
  • override custom scss variable inside another angular-cli(7) (library) project
  • Angular-7 How to navigate to certain section of the single page website
  • how to disable an input field from a group of input fields in Angular
  • How to unit test selection of a mat-autocomplete option?
  • angular 8 form reset with value not working correctly
  • ng: error in production with Cb(...).firestore is not a function
  • Property 'result' does not exist on type 'EventTarget'
  • Cannot read property 'subscribe' of undefined on Ionic 4 , Angular 8
  • Repository is not clean. Please commit or stash any changes before updating In Angular 8
  • @angular-devkit/core module not found after angular-cli global fresh install
  • Lazy module loading error after updating to Angular 8
  • Using mat-tab-group focusChange event, How to stop user navigating to other tab
  • Best practice class member initialization
  • Angular 8 : TypeError: Found non-callable @@iterator
  • ng build --prod non-exported function
  • (Ionic4) How to dynamically go to previous page?
  • Angular 8.0.1 platform.es5.js:102 Uncaught TypeError: Object(...) is not a function
  • Zsh : command not found : ng on new Mac OS Catalina
  • Ag grid: How to add a row with sorting order
  • Failed to construct 'Worker': Module scripts are not supported on DedicatedWorker yet in Angular 8
  • How to write a function which will be return : Observable <ModelTemp>
  • cannot compile Ivy Rendering Engine in Angular 8
  • What is best way to apply ngif directive to <li> element?
  • Angular 7: Trigger valuechanges on addControl, if value's present
  • Function inside a ts file
  • Angular - Are admin files downloadable?
  • node_modules/@angular/cdk/table"' has no exported member 'CdkTextColumn'
  • node_modules/rxjs/Subject"' has no exported member 'Subject'
  • Angular - how to http service subscribe without response
  • how to test all my Service are injected into component
  • After upgrading to Angular8, AppEngine is serving scripts with the incorrect mime-type
  • Angular 6 - Cannot read property 'outlets' of null
  • Setting up background img with angular 7
  • Make BehaviorSubject persist across browser tabs? (@HostListener?)
  • Angular 7 : How to deploy Angular "Build" folder along with ASP.Net Web Api in Visual Studio 2017
  • How return name of image from FormControl in ReactivForms
  • Angular 7 HTTP Post 500 Internal Server Error
  • Ionic show data which is equal to the value
  • Angular directive inputs over component from another module cause an error
  • ValidationError: Progress Plugin Invalid Options
  • Angular mat-table : - Sort icon missing on custom sort
  • How use routing in angular correctly?
  • Automatic width mat-option in Angular Material
  • Angular Material Table how to pass object to displayedColumns instead of array
  • angular ngFor trackBy does not work as I expected
  • Module ag-grid-angular/main has no exported member AgGridNg2.ts
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com