4
votes

I'm using the latest VS2019Pro with Core 3.1.

It seems like Blazor ServerApp has real-time code running within the @code{} tags in the .razor pages. So instead of using APIs to provide the data, I was thinking it would make a lot of sense to just create classes and methods to return the data.

The only issue I am facing is being able to use User.Identity.Name in a Class. Usually this is provided in the .razor pages and in Controllers without issue, but how can I (if it's even possible) use the same User.Identity.Name property within classes?

2

2 Answers

2
votes

You can use the standard .net core auth: https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-3.1

Basically you define a:

[CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }

Then you can await it:

private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            _authMessage = $"{user.Identity.Name} is authenticated.";
        }
        else
        {
            _authMessage = "The user is NOT authenticated.";
        }
    }

Edit -----

Something like this??

Base Component:

[CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }

public String Username {get;set;}

protected override async Task OnInitializedAsync(){
    Username = (await authenticationStateTask).User.Identity.Name;
}

Then in your other components:

@inherits BaseCompomnent

@Username
0
votes
 IMyRoleManager _myRoleManager;
    private AuthenticationStateProvider _authenticationStateProvider;
    public MyRepository(IMyRoleManager myRoleManager, AuthenticationStateProvider authentication)
    {
        _myRoleManager = myRoleManager;
        _authenticationStateProvider = authentication;
    }

 public async Task<bool> AddRoleToUser(string role)
    {
        var id = await GetUserIdFromAuthenticationStateProviderAsync();
        var result = await _myRoleManager.SetRoleForUser(role, id);
        return result;
    }

And in the startup file the correct entries have to be there for services.xxx (identity services)