Pergunta

I am working on a single page application using the asp.net mvc 5 template and registering external logins (google in this instance) fails with a validation exception - "The UserId field is required." the code in question:

// POST api/Account/RegisterExternal [OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("RegisterExternal")]
public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

        if (externalLogin == null)
        {
            return InternalServerError();
        }

        IdentityUser user = new IdentityUser//(model.UserName);
        {
             UserName = model.UserName
        };
        user.Logins.Add(new IdentityUserLogin
        {
             LoginProvider = externalLogin.LoginProvider,
             ProviderKey = externalLogin.ProviderKey
        });
        IdentityResult result = await UserManager.CreateAsync(user);
        IHttpActionResult errorResult = GetErrorResult(result);

        if (errorResult != null)
        {
           return errorResult;
        }

        return Ok();
    }
    catch (Exception exception)
    {
        throw;
    }
}

I appreciate the help

Foi útil?

Solução

The fix was simple but I find it strange it that the code generated by the template doesn't work out of the box. The IdentityUserLogin object has a UserID property that must be set.

IdentityUser user = new IdentityUser
{
    UserName = model.UserName
};
user.Logins.Add(new IdentityUserLogin()
{
    LoginProvider = externalLogin.LoginProvider,
    ProviderKey = externalLogin.ProviderKey, 
    UserId = user.Id
});
IdentityResult result = await UserManager.CreateAsync(user);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top