Надеюсь, вы все здоровы, на этот раз я здесь, чтобы задать вопрос, который я не могу понять, и речь идет об Identity. Дело в том, что я хочу получить идентификатор пользователя из Иски основной или везде, где это, сейчас единственное, что у меня естьПретензии GetUserId равно null
var principal = ClaimsPrincipal.Current;
var id1 = principal.Claims.FirstOrDefault(c => c.ValueType == ClaimTypes.NameIdentifier);
, но когда я пытаюсь получить UserId, и я иду к информации внутри претензий я не могу найти значение, даже если я сохранил его в авторизованном аккаунте при входе в систему.
Я работаю с MVC шаблона и Web API сервисом Моей службой размещенная в IIS и с этим я управляю аутентификацией с помощью AccountController Токена
это мой AuthenticationProperties
public static AuthenticationProperties CreateProperties(string userName, string userid)
{
IDictionary<string, string> data = new Dictionary<string, string> { { "userName", userName }, { "userId", userid } };
return new AuthenticationProperties(data);
}
и моего GrantResourceOwnerCredentiales
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
//var userManager = DependencyResolver.Current.GetService<ApplicationUserManager>();
AppJobSeeker user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName, user.Id);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);...
и у меня есть метод, который создает AuthenticationTicket и получить UserName и ю е UserId а
private void CreateTicket(SignInResult result, SignInModel model, string returnUrl)
{
//Let's keep the user authenticated in the MVC webapp.
//By using the AccessToken, we can use User.Identity.Name in the MVC controllers to make API calls.
FormsAuthentication.SetAuthCookie(result.AccessToken, model.RememberMe);
//Create an AuthenticationTicket to generate a cookie used to authenticate against Web API.
//But before we can do that, we need a ClaimsIdentity that can be authenticated in Web API.
var claims = new[]
{
new Claim(ClaimTypes.Name, result.UserName), //Name is the default name claim type, and UserName is the one known also in Web API.
new Claim(ClaimTypes.NameIdentifier, result.UserId), //If you want to use User.Identity.GetUserId in Web API, you need a NameIdentifier claim.
};
//Generate a new ClaimsIdentity, using the DefaultAuthenticationTypes.ApplicationCookie authenticationType.
//This also matches what we've set up in Web API.
var authTicket = new AuthenticationTicket(new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie), new AuthenticationProperties
{
ExpiresUtc = result.Expires,
IsPersistent = model.RememberMe,
IssuedUtc = result.Issued,
RedirectUri = returnUrl
});
...
Everithing выглядит хорошо, когда я логин, но когда я иду на другой контроллер я не могу извлечь идент
Спасибо Рикард, я решил проблему, я использовал GetUserId в неправильном месте. (Сторона MVC), когда я должен использовать его на стороне WebApi. – AVMP