Blazor Client Side - Перенаправление на страницу входа - PullRequest
1 голос
/ 29 февраля 2020

Я пытаюсь работать со стороны клиента Blazor и перенаправлять вход в систему, когда пользователь не подключен.

Моя проблема, когда я следую некоторому учебному пособию или официальной документации, пользователь перенаправляет на правильный URL, но страницу пусто.

Здесь код:

app.razor

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        @* <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/> *@
        <AuthorizeRouteView RouteData="routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                <RedirectToLogin></RedirectToLogin>
            </NotAuthorized>
        </AuthorizeRouteView>
    </Found>
    <NotFound>
        <CascadingAuthenticationState>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </CascadingAuthenticationState>
    </NotFound>
</Router>

redirectToLogin.razor

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@inject NavigationManager Navigation
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {

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

    protected override async Task OnInitializedAsync()
    {
        string signInUrl = "signin";
        //Navigation.NavigateTo("signin", true);
        var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var returnUrl = Navigation.ToBaseRelativePath(Navigation.Uri);

        if (returnUrl != signInUrl && (authenticationState?.User?.Identity is null || !authenticationState.User.Identity.IsAuthenticated))
        {
            Console.WriteLine(returnUrl);
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                Navigation.NavigateTo(signInUrl, true);
            }
            else
            {
                Navigation.NavigateTo($"{signInUrl}?returnUrl={returnUrl}", true);
            }
        }
    }

}

закачиваемые услуги:

    services.AddOptions();
    services.AddAuthorizationCore();
    services.AddScoped<TokenAuthenticationStateProvider>();
    services.AddScoped<AuthenticationStateProvider>(provider => provider.GetRequiredService<TokenAuthenticationStateProvider>());

Спасибо за вашу помощь.

ОБНОВЛЕНИЕ 1:

SignIn.razor

@page "/signin"

<h1>Connection</h1>
@inject NavigationManager NavigationManager

<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
    <div class="card card-signin my-5">
        <div class="card-body">
            <h5 class="card-title text-center">Connection</h5>
            <EditForm @ref="loginform" Model="credentials" OnValidSubmit="SubmitCredentials">
                <DataAnnotationsValidator/>
                <div class="form-label-group">
                    <InputText class="form-control" @bind-Value="credentials.Email"/>
                    <label for="inputEmail">Email</label>
                    <ValidationMessage For="@(() => credentials.Email)"/>
                </div>
                <div class="form-label-group">
                    <InputText type="password" class="form-control" @bind-Value="credentials.Password"/>
                    <label for="inputPassword">Mot de passe</label>
                    <ValidationMessage For="@(() => credentials.Password)"/>
                </div>
                <div class="custom-control custom-checkbox mb-3">
                    <input type="checkbox" class="custom-control-input" id="customCheck1">
                    <label class="custom-control-label" for="customCheck1">Se souvenir de moi</label>
                </div>
                <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Se connecter</button>
                <hr class="my-4">
            </EditForm>
        </div>
    </div>
</div>

@code {

    public class Credentials
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

    Credentials credentials = new Credentials();
    bool loginFailure;
    EditForm loginform { get; set; }

    Task SubmitCredentials()
    {
        return null;
    //await AuthStateProvider.SetTokenAsync(credentials.Email, DateTime.MaxValue);
    }

}

решено:

services.AddAuthorizationCore (); следует вызывать после всех других служб .

 services.AddOptions();
        services.AddScoped<TokenAuthenticationStateProvider>();
        services.AddScoped<AuthenticationStateProvider>(provider => provider.GetRequiredService<TokenAuthenticationStateProvider>());
services.AddAuthorizationCore();
...