Context.User.Identity.Name은 SignalR 2.X.X에서 null입니다.어떻게 고치나요?
-
20-12-2019 - |
문제
이것이 나를 미치게 만든다.
저는 최신 signalR 릴리스(2.0.2)를 사용하고 있습니다.내 허브 코드입니다(OnConnected).
public override Task OnConnected()
{
//User is null then Identity and Name too.
Connections.Add(Context.User.Identity.Name, Context.ConnectionId);
return base.OnConnected();
}
그리고 이것은 내 컨트롤러의 로그인 방법입니다.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UnitOfWork.UserRepository.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
}
TempData["ErrorMessage"] = Resources.InvalidUserNameOrPassword;
// If we got this far, something failed, redisplay form
return RedirectToAction("Index","Home");
}
OnDisconnected에서 어떤 사람들이 이 문제를 겪고 있다는 것을 알았지만 저는 거기까지 가지도 못했습니다.
MCV5 템플릿을 사용하고 있습니다.
무엇이 잘못되었는지 아시나요?
해결책
최종 솔루션을 찾았습니다. 이것은 내 OWIN 시작 클래스의 코드입니다.
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
// Enable the application to use a cookie to store information for the signed i user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Index")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseMicrosoftAccountAuthentication(new MicrosoftProvider().GetAuthenticationOptions());
app.UseTwitterAuthentication(new TwitterProvider().GetAuthenticationOptions());
app.UseFacebookAuthentication(new FacebookProvider().GetAuthenticationOptions());
app.UseGoogleAuthentication(new GoogleProvider().GetAuthenticationOptions());
}
.
나 자신을 커피를 만드는 것은 "인증 후에 signalr을 매핑하는 것과 voila! 이제는 예상대로 군장입니다. / P>
public void Configuration(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed i user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Index")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseMicrosoftAccountAuthentication(new MicrosoftProvider().GetAuthenticationOptions());
app.UseTwitterAuthentication(new TwitterProvider().GetAuthenticationOptions());
app.UseFacebookAuthentication(new FacebookProvider().GetAuthenticationOptions());
app.UseGoogleAuthentication(new GoogleProvider().GetAuthenticationOptions());
app.MapSignalR();
}
. 다른 팁
동일한 프로젝트에서 Web API 및 Signalr을 사용하는 경우 Web API 등록하기 전에 SignalR 을 맵핑해야합니다.
변경 사항 :
app.UseWebApi(GlobalConfiguration.Configuration);
app.MapSignalR();
.
다음과 같이 :
app.MapSignalR();
app.UseWebApi(GlobalConfiguration.Configuration);
. 인증을 확인하십시오.구성을 BEFOR 시작 app.mapmignalrr ()
이 this
를 변경했습니다. public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
ConfigureAuth(app);
}
}
.
이
에 public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR();
}
}
.
포옹 ..
매핑하는 경우 /signalr
'분지형 파이프라인'으로서 이 작업을 수행해야 합니다.꼭 이용해 보세요 bp.UseCookieAuthentication
그리고는 아니다 app
:
app.Map("/signalr", bp =>
{
bp.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/store/youRaccount/login")
});
팁:배송으로 케이스를 교체해서 봤더니 youRaccount
URL 표시줄에서 작동했다는 것을 알 수 있습니다 :-)
.NET 코어 신호 전용
최신 .NET 코어 신호의 경우 전체 명령어는 웨스 메트를 사용하는 경우 쿼리 문자열에서 AccessToken을 수동으로 가져와야한다고 설명합니다.이것은 놓치기 쉽습니다.
https : //docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=AsphnetCore-2.2
기본적으로 AddAuthentication()
를 호출하는 경우 AddJwtBearer()
를 추가 한 다음 OnMessageReceived
핸들러에 대한 핸들러를 설정해야합니다.
위의 링크에서 'OnMessagereceived'를 검색합니다.이게 당신 자신을 당신 자신을 추가해야한다는 의미에서 조금 gnarly입니다. 그러나 그것이 너무 쉽게 놓치는 것이 쉽습니다.