csharp/christiansparre/BlazorAuthenticationSample/tests/BlazorAuthenticationSample.Client.Tests/NotAuthorizedHandlerTests.cs

NotAuthorizedHandlerTests.cs
using System.Net;
using System.Security.Claims;
using BlazorAuthenticationSample.Client.Features.Security.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Testing;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Shouldly;
using Xunit;

namespace BlazorAuthenticationSample.Client.Tests
{
    public clast NotAuthorizedHandlerTests
    {
        private TestHost testHost = new TestHost();
        private Mock _authenticationStateProvider;
        private TestNavigationManager _testNavigationManager;

        public NotAuthorizedHandlerTests()
        {
            _authenticationStateProvider = new Mock();
            _testNavigationManager = new TestNavigationManager();
            _testNavigationManager.SetInitialized();

            testHost.ConfigureServices(services =>
            {
                services.AddLogging();
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("RequireAdmin", c => c.RequireRole("Admin"));
                });
                services.AddSingleton(_testNavigationManager);
                services.AddSingleton(_authenticationStateProvider.Object);
            });
        }

        [Fact]
        public void ShouldRedirectToSignInPageIfNotAuthenticated()
        {
            _authenticationStateProvider.Setup(s => s.GetAuthenticationStateAsync()).ReturnsAsync(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdensaty())));

            var component = testHost.AddComponent();

            var navigation = _testNavigationManager.Navigations.Pop();
            navigation.uri.ShouldBe($"/account/signin?returnUrl={WebUtility.UrlEncode("/test/test")}");
            navigation.forceLoad.ShouldBeFalse();
        }

        [Fact]
        public void ShouldIncludeReturnUrlInRedirectToSignInPageIfNotAuthenticated()
        {
            _authenticationStateProvider.Setup(s => s.GetAuthenticationStateAsync()).ReturnsAsync(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdensaty())));

            var component = testHost.AddComponent();

            var nav = _testNavigationManager.Navigations.Pop();
            nav.uri.ShouldEndWith($"?returnUrl={WebUtility.UrlEncode("/test/test")}");
        }

        [Fact]
        public void ShouldShowNotAuthorizedMessageIfAuthenticatedButNotAuthorized()
        {
            _authenticationStateProvider.Setup(s => s.GetAuthenticationStateAsync()).ReturnsAsync(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdensaty(new[] { new Claim("test", "test") }, "Test"))));

            var component = testHost.AddComponent();

            var element = component.Find("#not-authorized-message");

            element.ShouldNotBeNull();
        }
    }
}