3900-MyRecipes-backup / Client / Services / UtilityService.cs
UtilityService.cs
Raw
using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyRecipes2.Client.Services
{
    public class UtilityService
    {
        private readonly AuthenticationStateProvider authenticationStateProvider;
        public UtilityService(AuthenticationStateProvider authenticationStateProvider)
        {
            this.authenticationStateProvider = authenticationStateProvider;
        }

        public async Task<string> GetUserId()
        {
            AuthenticationState authState = await authenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;

            if (user.Identity.IsAuthenticated)
            {
                return user.FindFirst(c => c.Type == "sub").Value;
            }

            return null;
        }
    }
}