Jan
Jan

Reputation: 167

How to request call to controller with anonymous user?

I am using Blazor WebAssemlby with Authentication. When I am authenticated with loged in everythink work ok. But when I am not loged in (anonymous), I wanna post request to one of a controller (to get some data) and it not work.

How can I use Country controller for anonymous user?

Here is my code.

View:

@page "/certificate"
@using SkupinaPrimera.Shared.Models
@using Microsoft.AspNetCore.Authorization
@inject HttpClient Http
@attribute [AllowAnonymous]

<h3>Claim your Certificate</h3>

@code {
private User user = new User();
List<Country> countries = new List<Country>();

[AllowAnonymous]
protected override void OnInitialized()
{
    GetCountries();
}

private async Task GetCountries() {  
    try
    {
       var result = await Http.GetFromJsonAsync<List<Country>>("Country");
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
    }
 }
}

Controller:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SkupinaPrimera.Shared.Models;

namespace SkupinaPrimera.Client.Pages
{
    [AllowAnonymous]
    [ApiController]
    [Route("Country")]
    public class CountryController : ControllerBase
    {
        // GET
        [AllowAnonymous]
        [HttpGet]
        public IEnumerable<Country> Get()
        {
            var cultureInfo = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            var countries = new List<Country>();
            foreach (var info in cultureInfo)
            {
                if (!string.IsNullOrWhiteSpace(info.Name))
                {
                    var regionInfo = new RegionInfo(info.LCID);
                    if (countries.Count(x => x.Name == regionInfo.EnglishName) == 0)
                    {
                        countries.Add(new Country
                        {
                            Id = info.LCID,
                            Name = regionInfo.EnglishName
                        });
                    }
                }
            }

            return countries.OrderBy(x=>x.Name);
        }
    }
}

Update: In network I can see this call. What is it for?

https://localhost:44372/connect/authorize?client_id=Project.Client&redirect_uri=https%3A%2F%2Flocalhost%3A44372%2Fauthentication%2Flogin-callback&response_type=code&scope=Project.ServerAPI%20openid%20profile&state=ba2527a68ed4480497e48a68b390599b&code_challenge=dwd_kgszWFyWq2OrAMuedK26RfjOt4v2ieHEQ7W46l8&code_challenge_method=S256&prompt=none&response_mode=query

Upvotes: 1

Views: 1252

Answers (1)

Michael Washington
Michael Washington

Reputation: 3075

See: https://learn.microsoft.com/en-us/aspnet/core/security/blazor/webassembly/additional-scenarios?view=aspnetcore-3.1#unauthenticated-or-unauthorized-web-api-requests-in-an-app-with-a-secure-default-client

You need to add code like this in your program.cs file:

builder.Services.AddHttpClient("ServerAPI.NoAuthenticationClient", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));

And consume it like this:

@inject IHttpClientFactory ClientFactory

protected override async Task OnInitializedAsync()
{
    // Create a httpClient to use for non-authenticated calls
    NoAuthenticationClient =
         ClientFactory.CreateClient(
             "ServerAPI.NoAuthenticationClient");

    // Make the non-authenticated call
    await NoAuthenticationClient.PostAsJsonAsync(
            "SyncfusionHelpDesk", objHelpDeskTicket);
}

Upvotes: 3

Related Questions