Как я могу изменить тип аутентификации как номер телефона вместо имени пользователя в моем веб-интерфейсе? - PullRequest
0 голосов
/ 01 июня 2018

Моя аутентификация работает нормально, но мне нужно использовать phoneNumber пользователей вместо имен пользователей.Есть мой класс провайдера

using Identity.Infrastructure;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Identity.Providers
{
public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
        return Task.FromResult<object>(null);
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        var allowedOrigin = "*";

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        if (!user.EmailConfirmed)
        {
            context.SetError("invalid_grant", "User did not confirm email.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");

        var ticket = new AuthenticationTicket(oAuthIdentity, null);

        context.Validated(ticket);
    }
  }
}

, в этом контексте класса идет только с userName и паролем, поэтому он не может достичь PhoneNumber, даже если я отправлю его в качестве параметра. Думаю, проблема решится после того, как я смогу изменить

userManager.FindAsync(context.UserName, context.Password)

вот так

userManager.FindAsync(context.PhoneNumber, context.Password)

VS не позволяет мне вмешиваться OAuthGrantResourceOwnerCredentialsContext

 using Identity.Infrastructure;
 using Microsoft.AspNet.Identity.EntityFramework;
 using System;
 using System.Collections.Generic;
 using System.Net.Http;
 using System.Web.Http.Routing;

 namespace Identity.Models
 {
     public class ModelFactory
     {
         private UrlHelper _UrlHelper;
         private ApplicationUserManager _AppUserManager;

         public ModelFactory(HttpRequestMessage request, ApplicationUserManager appUserManager)
         {
             _UrlHelper = new UrlHelper(request);
             _AppUserManager = appUserManager;
         }

         public UserReturnModel Create(ApplicationUser appUser)
         {
             return new UserReturnModel
             {
                 Url = _UrlHelper.Link("GetUserById", new { id = appUser.Id }),
                 Id = appUser.Id,
                 UserName = appUser.UserName,
                 FullName = string.Format("{0} {1}", appUser.FirstName, appUser.LastName),
                 Email = appUser.Email,
                 EmailConfirmed = true,
                 Level = appUser.Level,
                 JoinDate = appUser.JoinDate,
                 Roles = _AppUserManager.GetRolesAsync(appUser.Id).Result,
                 Claims = _AppUserManager.GetClaimsAsync(appUser.Id).Result,
                 PhoneNumber = appUser.PhoneNumber
             };


         }

         public RoleReturnModel Create(IdentityRole appRole)
         {

             return new RoleReturnModel
             {
                 Url = _UrlHelper.Link("GetRoleById", new { id = appRole.Id }),
                 Id = appRole.Id,
                 Name = appRole.Name
             };
         }
     }

     public class RoleReturnModel
     {
         public string Url { get; set; }
         public string Id { get; set; }
         public string Name { get; set; }
     }
     public class UserReturnModel
     {
         public string Url { get; set; }
         public string Id { get; set; }
         public string UserName { get; set; }
         public string FullName { get; set; }
         public string PhoneNumber { get; set; }
         public string Email { get; set; }
         public bool EmailConfirmed { get; set; }
         public int Level { get; set; }
         public DateTime JoinDate { get; set; }
         public IList<string> Roles { get; set; }
         public IList<System.Security.Claims.Claim> Claims { get; set; }
     }
 }

В результате я остановился на аутентификации сphoneNumber вместо userName и установить deviceId в качестве пароля

1 Ответ

0 голосов
/ 01 июня 2018
public override Task<ApplicationUser> FindAsync(string Phone, string password)

    {
        //Do your  Stuff here
        //return base.FindAsync(userName, password);
    }

Переопределить FIndAsync () в IndentityConfig.cs

...