0
votes

I started from a visual studio template, a new Blazor WebAssembly with authentication and web API as the server-side.

Now i want to secure my Pages and the server API. I do the following:

Page:
<AuthorizeView Roles="Administrator">
    <Authorized>
        <h1>Weather forecast</h1>

        <p>This component demonstrates fetching data from the server.</p>

        @if (forecasts == null)
        {
            <p><em>Loading...</em></p>
        }
        else
        {
            <table class="table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Temp. (C)</th>
                        <th>Temp. (F)</th>
                        <th>Summary</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var forecast in forecasts)
                    {
                        <tr>
                            <td>@forecast.Date.ToShortDateString()</td>
                            <td>@forecast.TemperatureC</td>
                            <td>@forecast.TemperatureF</td>
                            <td>@forecast.Summary</td>
                        </tr>
                    }
                </tbody>
            </table>
        }
    </Authorized>
    <NotAuthorized>
    ...
    </NotAuthorized>
</AuthorizeView>

@code {

    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        var response = await Http.GetAsync("Api/WeatherForecast/Get");
        //var resp = await Http.GetFromJsonAsync<WeatherForecast[]>("Api/WeatherForecast/Get");

        if (response.IsSuccessStatusCode)
        {
            var s = await response.Content.ReadAsStringAsync();
            forecasts = await response.Content.ReadFromJsonAsync<WeatherForecast[]>();
        }
    }
}

API
[Authorize]
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class WeatherForecastController : Controller
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            this.logger = logger;
        }

      
        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

The User that call the page "fetchdata" is not logged in and can not show des site. But OnInitializedAsync is still called. The API blocks because [Authorize].

But now here comes the problem. With the var response = await Http.GetAsync("Api/WeatherForecast/Get"); i get an HttpCode 200 back. But the API is never called?! Where does it come from?

Is something wrong here? How can i make my Page and my API secure?

I do not want to use the AuthenticationStateProvider in every Page like that:

@code {

private WeatherForecast[] forecasts;

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

protected override async Task OnInitializedAsync()
{

    if(authenticationStateTask.Result.User.IsInRole("Administrator"))
    {
        var response = await Http.GetAsync("Api/WeatherForecast/Get");
        //var resp = await Http.GetFromJsonAsync<WeatherForecast[]>("Api/WeatherForecast/Get");

        if (response.IsSuccessStatusCode)
        {
            var s = await response.Content.ReadAsStringAsync();
            forecasts = await response.Content.ReadFromJsonAsync<WeatherForecast[]>();
        }
    }

}

}

1

1 Answers

0
votes

You don't have to! :) The question is though, do you want the entire app to be secure, or just a couple pages?

Personally, I prefer injecting @inject AuthenticationStateProvider AuthenticationStateProvider and then getting the auth state using GetAuthenticationStateAsync(); inside of OnInitializedAsync(). Example:

protected override async Task OnInitializedAsync()
{
    try
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        if(authState.User.Identity.IsAuthenticated)
            UserName = $"Hi, {authState.User.Claims.FirstOrDefault(x => x.Type == "display_name")?.Value}!";
    }
    catch (Exception ex)
    {
        Logger.LogError($"Failed to initialize menu. Error: {ex}");
    }
}

You can get away with using <AuthorizeView /> components to handle rendering content for authenticated/authorized users. Example from my own app:

<AuthorizeView>
    <Authorized>
        <CascadingValue Name="DeviceType" IsFixed="true" Value="DeviceType">
            <NavMenu />
        </CascadingValue>
    </Authorized>
</AuthorizeView>

I use this to only render my navigation if the current user is logged in. If not, no menu.