frontend api aspnet core identity mvc

Salvatore Sanollo 25 Reputation points
2023-10-25T23:18:12.0633333+00:00

Hi everyone,

I have two projects:

  1. WebAPI with aspnet core identity;
  2. website with MVC;

I need to use the APIs in the MVC project through services (server-side code) and not through js libraries.

I configured my service using HttpClient but now I have two questions:

  1. where do I save the jwt token received from the login endpoint?
  2. if I receive an http 401, how do I redirect to the login page?

Thank you

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,281 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ping Ni-MSFT 2,640 Reputation points Microsoft Vendor
    2023-10-26T08:49:02.89+00:00

    Hi @Salvatore Sanollo,

    For how to custom middleware you could check this official document.

    For your current scenario by using HttpClient, a better way is to custom DelegatingHandler

    public class RedirectUnAuthorizedHandler : DelegatingHandler
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
    
        public RedirectUnAuthorizedHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        }
    
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
    
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                _httpContextAccessor.HttpContext.Response.Redirect("/Account/Login");
    
            }
    
            return response;
        }
    }
    

    Be sure register the services in the Startup.cs or Program.cs (beyond .NET 6).

    builder.Services.AddHttpClient("MyApi")
        .AddHttpMessageHandler<RedirectUnAuthorizedHandler>();
    builder.Services.AddSingleton<RedirectUnAuthorizedHandler>();
    builder.Services.AddHttpContextAccessor();
    
    //.....
    app.UseRouting(); 
    app.UseAuthentication(); 
    app.UseAuthorization();  
    app.MapControllerRoute(     
        name: "default",     
        pattern: "{controller=Home}/{action=Index}/{id?}");  
    app.Run(); 
    

    Call the api:

    public class HomeController : Controller
    {
        public HomeController(IHttpClientFactory factory)
        {
            _client = factory.CreateClient("MyApi");        
        }
        private readonly HttpClient _client;
      
        public async Task<IActionResult> Index()
        {
            var res = await _client.GetAsync("https://localhost:xxxx/Your_Api_URL");
            return View();
        }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments