Check if user is logged in with Token Based Authentication in ASP.NET Core

拟墨画扇 提交于 2019-12-18 19:14:05

问题


I managed to implement this token based authentication system in my application, but I have a little question. How can I check if a user is signed it (eg if the there is a valid token in the request) within the method? So with the [Authorize] ?

So I have controller, and in that controller I want to check if the user is signed in. I thought of using this:

if (_signInManager.IsSignedIn(ClaimsPrincipal.Current))
{
    ...
}

but it does not work since ClaimsPrincipal.Current is always null


回答1:


You don't need to use the SigninManager or something similar. The user is injected on the pipeline (on the User property of the base controller) and it's info is filled automatically by the authentication middleware (cookie or token). So, on your controller:

bool isAuthenticated = User.Identity.IsAuthenticated;



回答2:


yes . put [Authorize] attribute above your class or methods to check if user is authenticate or not. You can get user by this code:

var principal = User as ClaimsPrincipal;
var check = User.Identity.IsAuthenticated;


来源:https://stackoverflow.com/questions/41315903/check-if-user-is-logged-in-with-token-based-authentication-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!