C#
C#: Blazor 전역 로그인 체크
개태형님
2021. 12. 1. 22:13
로그인이 안되어 있을 시 로그인 페이지를 제외한 모든 페이지의 접근을 로그인 페이지로 redirect를 시켜버리는 방법이다.
_Import.razor 에 아래와 같은 속성을 추가한다.
보통 해당 속성은 인증이 필요한 페이지에 추가하지만, 이러면 모든 페이지 접근 시 인증 권한이 있는지 체크하게 된다.
@attribute [Authorize]
로그인 페이지에는 아래와 같이 권한을 체크하지 않는 속성을 추가한다.
@attribute [AllowAnonymous]
마지막으로, App.razor에 로그인이 안되어 있을 시 로그인 페이지로 redirect 시키는 처리를 한다.
CascadingAuthenticationState : 로그인 상태를 모든 위치에서 공유함
AuthorizeRouteView : 기존 RouteView에 인증확인이 추가됨
NotAuthorized : 미인증 시 처리될 구문
@inject NavigationManager NavigationManager
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@{ NavigationManager.NavigateTo("/login"); }
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>