Вход MVC 5 OWIN с претензиями и AntiforgeryToken. Пропустить ли я провайдера ClaimsIdentity?
Я пытаюсь узнать претензии на вход MVC 5 OWIN. Я старался держать его как можно проще. Я начал с шаблона MVC и вставил код своих претензий (см. Ниже). Я получаю сообщение об ошибке, когда я использую помощник @Html.AntiForgeryToken() в представлении.
Ошибка:
A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or
'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovid
er' was not present on the provided ClaimsIdentity.
To enable anti-forgery token support with claims-based authentication, please verify that
the configured claims provider is providing both of these claims on the ClaimsIdentity
instances it generates. If the configured claims provider instead uses a different claim
type as a unique identifier, it can be configured by setting the static property
AntiForgeryConfig.UniqueClaimTypeIdentifier.
Exception Details: System.InvalidOperationException: A claim of type
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or
'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was
not present on the provided ClaimsIdentity. To enable anti-forgery token
support with claims-based authentication, please verify that the configured claims provider
is providing both of these claims on the ClaimsIdentity instances it generates.
If the configured claims provider instead uses a different claim type as a unique
identifier, it can be configured by setting the static property
AntiForgeryConfig.UniqueClaimTypeIdentifier.
Source Error:
Line 4: using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new
{ id = "logoutForm", @class = "navbar-right" }))
Line 5: {
Line 6: @Html.AntiForgeryToken()
Действие входа в систему
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "Brock"),
new Claim(ClaimTypes.Email, "[email protected]")
};
var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);
return RedirectToAction("Welcome");
}
_LoginPartial.cshtml
@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
Я попытался установить ClaimTypes.NameIdentifier
(как в этом SO-ответе)
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
И тогда я "только"? получить эту ошибку
A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' was
not present on the provided ClaimsIdentity.
Я хочу сохранить antiforgeryToken, потому что он может помочь в использовании межсайтовых скриптов.
Ответы
Ответ 1
Идентификатор претензии не имеет ClaimTypes.NameIdentifier
, вы должны добавить больше в массив претензий:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "username"),
new Claim(ClaimTypes.Email, "[email protected]"),
new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid
};
Чтобы отобразить информацию, чтобы претендовать на дополнительные исправления:
ClaimTypes.Name => map to username
ClaimTypes.NameIdentifier => map to user_id
Так как имя пользователя также уникально, вы можете использовать username
для поддержки токена анти-подделки.
Ответ 2
В Application_Start()
укажите, какой Claim
использовать как NameIdentifier
:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
...
System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier =
System.Security.Claims.ClaimTypes.NameIdentifier;
...
}
}
Смотрите: http://brockallen.com/2012/07/08/mvc-4-antiforgerytoken-and-claims/
Ответ 3
AntiForgeryConfig
Один из способов решения этой проблемы - установить AntiForgeryConfig для использования другого типа ClaimType.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
}
Добавить идентификаторы имен NameIdentifier и IdentityProvider
В качестве альтернативы вы можете добавить NameIdentifier и IdentityProvider ClaimTypes к своим требованиям.
List<Claim> _claims = new List<Claim>();
_claims.AddRange(new List<Claim>
{
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", _user.Email)),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", _user.Email)
})
Смотрите: https://stack247.wordpress.com/2013/02/22/antiforgerytoken-a-claim-of-type-nameidentifier-or-identityprovider-was-not-present-on-provided-claimsidentity/
Ответ 4
Я использовал это в Global.asax.cs Application_Start() и решил ошибку:
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
Ответ 5
У меня была аналогичная проблема с этим, которая оказалась связанной с куки; Я разрабатывал два MVC-сайта одновременно, и поскольку сайты ASP.Net используют одно и то же имя файла cookie, по умолчанию оба сайта мешают друг другу. Исправление файлов cookie устраняет проблему. Там больше на этом в ответе здесь.
Ответ 6
Ваш файл Global.asax.cs должен быть таким:
namespace YOUR_PROJECT_NAME
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
}
}
Значит, если это не так, как thta, вы должны добавить этот код к этому:
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
и не забудьте изменить "YOUR_PROJECT_NAME" на свое.