. NET 4.5 API с Identity.Core v2 - User.Identity.Name всегда имеет значение null - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь получить доступ к имени пользователя, отправившего запрос в ApiController.

string uname = User.Identity.Name;

User.Identity содержит:

{System.Security.Claims.ClaimsIdentity}
    [System.Security.Claims.ClaimsIdentity]: {System.Security.Claims.ClaimsIdentity}
    AuthenticationType: "Bearer"
    IsAuthenticated: true
    Name: null

Свойство Name всегда имеет значение null.

Я также пробовал использовать

string uname = HttpContext.Current.Request.LogonUserIdentity.Name

HttpContext.Current.Request.LogonUserIdentity содержит:

{System.Security.Principal.WindowsIdentity}
    base: {System.Security.Principal.WindowsIdentity}
    AccessToken: {Microsoft.Win32.SafeHandles.SafeAccessTokenHandle}
    AuthenticationType: "Bearer"
    Claims: {System.Security.Principal.WindowsIdentity.get_Claims}
    DeviceClaims: Count = 0
    Groups: {System.Security.Principal.IdentityReferenceCollection}
    ImpersonationLevel: Impersonation
    IsAnonymous: false
    IsAuthenticated: true
    IsGuest: false
    IsSystem: false
    Name: "IIS APPPOOL\\DefaultAppPool"
    Owner: {S-1-5-82-3006700770-424185619-1745488364-794895919-4004696415}
    Token: 2436
    User: {S-1-5-82-3006700770-424185619-1745488364-794895919-4004696415}
    UserClaims: Count = 11

Вы заметите, что Name - это имя пула приложений.

Вот как выглядит Startup.CS:

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuth(app);
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
                Provider = new SimpleAuthorizationServerProvider(), 
                
            };
            
            
            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }

Это класс SimpleAuthorizationServerProvider:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

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

            using (AuthRepository _repo = new AuthRepository())
            {
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

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

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
    }

Как я могу получить имя аутентифицированный пользователь API, отправляющий запрос?

1 Ответ

0 голосов
/ 14 июля 2020

Мне удалось это сделать, обновив класс SimpleAuthorizationServerProvider: изменено:

identity.AddClaim(new Claim("sub", context.UserName));

на

identity.AddClaim(new Claim("userName", context.UserName));

Затем я использовал утверждения для получения свойства userName:

var identity = (ClaimsIdentity)User.Identity;
string userName = (from c in identity.Claims
                   where c.Type == "userName"
                   select c.Value).FirstOrDefault();

Я не уверен, единственный ли это способ сделать это или самый эффективный, но он работает

...