configure-auth
하는 일
이 스킬은 Blazor Web App에 인증과 권한 부여를 추가합니다. 로그인 페이지, 역할 확인, 보호된 페이지가 포함됩니다. Blazor 앱을 보호해야 하는 .NET 개발자를 위한 스킬입니다.
사용하는 경우
- ✓일부 페이지에 로그인이나 특정 역할이 필요할 때.
- ✓Blazor 앱에 ASP.NET Core Identity 로그인과 로그아웃 페이지가 필요할 때.
- ✓대화형 컴포넌트 안에서 인증 상태가 없거나 로그인이 실패할 때.
스킬 링크
https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/configure-auth/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“제 Blazor Web App에 ASP.NET Core Identity 로그인을 추가하고, 관리자 역할만 관리자 페이지에 접근하도록 보호해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
에이전트가 앱의 상호 작용 설정을 읽고, 인증 서비스를 등록하며, 루트 컴포넌트를 연결하고, 각 렌더 모드에 맞춰 보호된 경로와 역할 확인을 설정합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Configure Auth
Step 1 — Read AGENTS.md
Read AGENTS.md at the workspace root for the project's interactivity mode and scope before making changes.
Step 2 — Register auth services in Program.cs
// Program.cs (server project)
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddAuthorization();
For ASP.NET Core Identity add the Identity services:
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();
builder.Services.AddIdentityCore<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager()
.AddDefaultTokenProviders();
Step 3 — Wire App.razor for auth and render mode
The App.razor component must use AuthorizeRouteView and conditionally apply the render mode so that pages excluded from interactive routing render statically.
<!DOCTYPE html>
<html>
<head>
<HeadOutlet @rendermode="RenderModeForPage" />
</head>
<body>
<Routes @rendermode="RenderModeForPage" />
<script src="_framework/blazor.web.js"></script>
</body>
</html>
@code {
[CascadingParameter]
public HttpContext HttpContext { get; set; } = default!;
private IComponentRenderMode? RenderModeForPage =>
HttpContext.AcceptsInteractiveRouting()
? InteractiveServer // replace with the app's render mode
: null;
}
In Routes.razor (or wherever the router lives), use AuthorizeRouteView:
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="routeData"
DefaultLayout="typeof(Layout.MainLayout)">
<NotAuthorized>
@if (context.User.Identity?.IsAuthenticated != true)
{
<RedirectToLogin />
}
else
{
<p>You are not authorized to access this resource.</p>
}
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
</Router>
Step 4 — Protect pages and components
[Authorize] attribute on pages
@page "/admin"
@attribute [Authorize]
With roles or policies:
@attribute [Authorize(Roles = "Admin")]
@attribute [Authorize(Policy = "RequireManager")]
AuthorizeView for conditional UI
<AuthorizeView>
<Authorized>Welcome, @context.User.Identity?.Name!</Authorized>
<NotAuthorized><a href="Account/Login">Log in</a></NotAuthorized>
</AuthorizeView>
Role/policy variants:
<AuthorizeView Roles="Admin,Manager">
<Authorized>Admin content here</Authorized>
</AuthorizeView>
Access auth state in code
[CascadingParameter]
private Task<AuthenticationState>? AuthState { get; set; }
protected override async Task OnInitializedAsync()
{
if (AuthState is not null)
{
var state = await AuthState;
var isAdmin = state.User.IsInRole("Admin");
}
}
Step 5 — Identity pages must stay static SSR
SignInManager and UserManager use HttpContext internally and throw in interactive components. Identity pages (login, register, manage) must render as static SSR.
In a globally interactive app, mark every Identity page:
@page "/Account/Login"
@attribute [ExcludeFromInteractiveRouting]
This forces a full-page navigation (exits the interactive circuit) so the page renders through the static SSR pipeline with a real HttpContext.
App.razor must use AcceptsInteractiveRouting() (Step 3) to return null for these pages — otherwise the framework still tries to render them interactively.
In a per-page app, Identity pages are static by default (no @rendermode directive), so [ExcludeFromInteractiveRouting] is not needed.
Step 6 — Auth state in WebAssembly / Auto mode
WebAssembly components run in the browser and have no HttpContext. Auth state must be serialized from the server during prerendering and deserialized on the client.
Server Program.cs:
builder.Services.AddAuthenticationStateSerialization();
Client .Client/Program.cs:
builder.Services.AddAuthenticationStateDeserialization();
Without these calls, `Task<Authenti
자주 묻는 질문
Identity를 다루나요?
네. ASP.NET Core Identity 설정과 로그인 페이지를 다룹니다.
역할과 정책을 쓸 수 있나요?
네. 역할 기반과 정책 기반 접근 제어를 다룹니다.
인증이 렌더 모드에 따라 달라지는 이유는 무엇인가요?
정적 페이지와 대화형 페이지에서 인증 상태가 다르게 동작하므로 설정도 달라집니다.
상세 정보
작성자의 원본 설명
Add authentication and authorization to a Blazor Web App, accounting for the app's render mode. USE WHEN the user needs [Authorize] on pages, AuthorizeView, role or policy-based access, login/logout Identity pages, or AuthenticationStateProvider. Also USE WHEN auth state is null after WebAssembly loads, SignInManager throws in an interactive component, NotAuthorized content never renders in static SSR, or HttpContext.User is null in an interactive component. DO NOT USE for general component authoring (see author-component), for prerendering concerns unrelated to auth (see support-prerendering)
repo: dotnet/skills
인기도
- GitHub 스타
- 5.8k
- 순위
- #14563
- 라이선스
- MIT
- 업데이트
- 2026. 11. 2.
댓글
- …
이 저장소의 다른 스킬
create-custom-agent
5.8k에이전트가 자체 도구, 지침, 다른 에이전트로의 핸드오프를 가진 VS Code 커스텀 에이전트 파일을 만들도록 돕습니다.
create-skill
5.8k에이전트가 올바른 이름, 명확한 트리거 설명, 표준을 따르는 SKILL.md 파일로 새 에이전트 스킬을 만들도록 돕습니다.
csharp-scripts
5.8k에이전트가 .NET 명령줄 도구로 작은 C# 프로그램을 전체 프로젝트 없이 단일 파일로 실행하도록 돕습니다.
dotnet-pinvoke
5.8k에이전트가 .NET에서 네이티브 C나 C++ 라이브러리를 올바르게 호출하도록 돕습니다. 시그니처, 문자열 처리, 메모리, 안전 핸들을 다룹니다.