Home > Blockchain >  Database calls in Custom Authorization Handler returning a NullReference Error in Blazor Server
Database calls in Custom Authorization Handler returning a NullReference Error in Blazor Server

Time:02-11

I'm currently creating a Blazor Server application that uses Azure AD for Authentication. The authentication works perfectly but I want to set up some AuthorisedView's within the application.

I've created a custom Authorization Handler whereby I take the user's email and find what user group they belong to within my own sql server. For the database calls I'm using Dapper with some table models. When I make a database call within the HandleRequirementAsync function it returns a NullReference exception. I cannot see where there could be an error within the code, am I missing something obvious?

The users list should return the user in the database and then groups list should return the group that user is assigned to based on an ID. Both of these calls work perfectly throughout the rest of the application, it only causes errors within this section below.

GroupHandler.cs

public class GroupHandler : AuthorizationHandler<GroupRequirement>
{
    public IUserData _dbUser;
    public IGroupData _dbGroup;

    protected async override Task<Task> HandleRequirement(AuthorizationHandlerContect context, GroupRequirement requirement)
    {
        var emailAddress = context.User.Identity.Name;

        List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);
        List<GroupModel> groups = await _dbGroup.GetGroupByID(users[0].Group_ID.ToString());

        if(groups[0].Group.Contains(requirement.Group))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

GroupRequirement.cs

public class GroupRequirement : IAuthorizationRequirement
{
    public string Group { get; }

    public GroupRequirement(string group)
    {
        Group = group;
    }
}

Startup.cs

services.AddAuthorization(config =>
{
    config.AddPolicy("IsAdmin", policy =>
        policy.Requirements.Add(new GroupRequirement("Admin")));
});

Error

NullReferenceException: Object reference not set an instance of an object

GroupHandler.HandleRequirementAsync(AuthorizationHandlerContext context, GroupRequirement requirement) in GroupHandler.cs, line 30

List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);

CodePudding user response:

The problem lies inside these lines, as you don't initialize your objects at all. So, they are null by default. Please, initialize this properties.

    public IUserData _dbUser;
    public IGroupData _dbGroup;

CodePudding user response:

It looks like you never assign the _dbGroup Field in your GroupHandler class.

Depending on your Setup you may be able to inject a IUserData via a constructor.

  • Related