0

I am trying to make custome authorization code in blazor. Based off previous stackoverflow posts I have contructed the following. My issue is that the tag is still not registering. I have:

public class MyServerAuthenticationStateProvider : AuthenticationStateProvider
{
    string UserId;
    string Password;
    bool IsAuthenticated = false;
    private ClaimsPrincipal claimsPrincipal;


    public void LoadUser(string _UserId, string _Password)
    {
        UserId = _UserId;
        Password = _Password;
    }


    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var userService = new UserService();

        var identity = IsAuthenticated
            ? new ClaimsIdentity(await userService.GetClaims(UserId))
            : new ClaimsIdentity();

        var result = new AuthenticationState(new ClaimsPrincipal(identity));
        return result;
    }
}

And:

 @page "/"
 @using BadgerWatchWeb.Services
 @inject AuthenticationStateProvider AuthenticationStateProvider

<h1>Sup</h1>


<AuthorizeView>
<Authorized>
    <h1>Hello, @context.User.Identity.Name!</h1>
    <p>You can only see this content if you're authenticated.</p>
</Authorized>
<NotAuthorized>
    <h1>Authentication Failure!</h1>
    <p>You're not signed in.</p>
</NotAuthorized>
<Authorizing>
    <h1>Authorizing</h1>
</Authorizing>
</AuthorizeView>


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

protected override async Task OnInitializedAsync()
{
    var myStateProvider = AuthenticationStateProvider as MyServerAuthenticationStateProvider;
   myStateProvider.LoadUser("mperry", "testtest");
   await myStateProvider.GetAuthenticationStateAsync();
}

}

I really need to know if this is the accepted way to do custom authentication in blazoe.

1 Answers1

0

You appear to have an error in your GetAuthenticationStateAsync method - it should be returning a Task:

public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
    var userService = new UserService();

    var identity = IsAuthenticated
        ? new ClaimsIdentity(await userService.GetClaims(UserId))
        : new ClaimsIdentity();

    var result = new AuthenticationState(new ClaimsPrincipal(identity));
    return Task.FromResult(result); //<<-- Note: Task.FromResult() here
}

Also, have a read through Authentication and Authorization for helpful information on custom authentication and authorization with Blazor, such as registering your custom authentication provider in ConfigureServices.

AlwaysLearning
  • 7,915
  • 5
  • 27
  • 35