[Blazor] getting current user details in a Blazor component[*.cs]
작성일 21-09-18 00:09
페이지 정보
작성자sbLAB 조회 9,531회 댓글 0건본문
https://docs.microsoft.com/ko-kr/aspnet/core/blazor/security/?view=aspnetcore-5.0 <-- 이렇게 해야함.
using Microsoft.AspNetCore.Components.Authorization;
public partial class Cyber : ComponentBase
{
...
//Blazor 로그인 인증정보 접근 Inject
[Inject] AuthenticationStateProvider AuthenticationStateProvider { get; set; }
...
protected override async Task OnInitializedAsync()
{
cyberReqModel_form.UserId = await GetClaimsPrincipalData_userIdentityName();
}
//로그인정보 얻기
private async Task<string> GetClaimsPrincipalData_userIdentityName()
{
var _authMessage="";
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated) {
_authMessage = user.Identity.Name;
}
else {
_authMessage = "none";
}
return _authMessage;
}
}
---------------------------------------------------------------------------
아래소스는 정상작동 안됨(http 연결 끊김[disconnected])
CodeBehind Style
[Startup.cs]
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHttpContextAccessor(); //cs코드에서 Auth ID 사용가능
...
}
[Cyber.cs]
using Microsoft.AspNetCore.Http;
public partial class Cyber : ComponentBase{
...
[Inject]
IHttpContextAccessor httpContextAccessor { get; set; } //Blazor 로그인 인증정보 접근 Inject
...
public string AuthUserId;
}
protected override async Task OnInitializedAsync(){
AuthUserId = httpContextAccessor.HttpContext.User.Identity.Name;
}
@Code in razor Style
댓글목록
등록된 댓글이 없습니다.