Asp.net web api .Net Core 2 API如何获取当前登录用户?

Asp.net web api .Net Core 2 API如何获取当前登录用户?,asp.net-web-api,asp.net-core,claims-based-identity,asp.net-core-webapi,Asp.net Web Api,Asp.net Core,Claims Based Identity,Asp.net Core Webapi,这个问题目前正困扰着我。Web API 2中从未出现过问题,现在在Core中,我无法获取登录用户的当前声明或身份 当应用程序启动时,将调用Index()IActionResult,用户将使用SignInAsync()方法登录 公共异步任务索引() { var索赔=新列表() { 新索赔(ClaimTypes.Name,“CA19207”), 新索赔(ClaimTypes.Actor,“2770”), 新索赔(ClaimTypes.DateOfBirth,“用户”) }; var标识=新的索赔实体

这个问题目前正困扰着我。Web API 2中从未出现过问题,现在在Core中,我无法获取登录用户的当前声明或身份

当应用程序启动时,将调用Index()IActionResult,用户将使用SignInAsync()方法登录

公共异步任务索引()
{
var索赔=新列表()
{
新索赔(ClaimTypes.Name,“CA19207”),
新索赔(ClaimTypes.Actor,“2770”),
新索赔(ClaimTypes.DateOfBirth,“用户”)
};
var标识=新的索赔实体(索赔,“TNEVP”);
var principal=新的ClaimsPrincipal(身份);
等待HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,主体);
var isIn=principal.Identity.IsAuthenticated;//返回true
var isauthenticed=(HttpContext.User.Identity as ClaimsIdentity).IsAuthenticated;//返回false
返回Ok();
}
然后,从Angular 2服务中,我调用api/user来获取登录用户的声明。但是,声明集为空,用户未经过身份验证

    [HttpGet("claims")]
    public async Task<IEnumerable<Claim>> Get()
    {
        var claims = (User as ClaimsPrincipal).Claims;
        return await Task.FromResult(claims);
    }
[HttpGet(“索赔”)]
公共异步任务Get()
{
var索赔=(用户为ClaimsPrincipal)。索赔;
返回等待任务。FromResult(索赔);
}
Startup类中的标记是基本的:

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddAuthentication(o =>
            {
                o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(o =>
            {
                o.LoginPath = "/api/login";
                o.LogoutPath = "/api/logout";
                // additional config options here
            });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}");
        });
    }
public void配置服务(IServiceCollection服务)
{
服务
.AddAuthentication(o=>
{
o、 DefaultChallengeScheme=CookieAuthenticationDefaults.AuthenticationScheme;
o、 DefaultSignenscheme=CookieAuthenticationDefaults.AuthenticationScheme;
o、 DefaultAuthenticateScheme=CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(o=>
{
o、 LoginPath=“/api/login”;
o、 LogoutPath=“/api/logout”;
//这里有其他配置选项
});
services.AddSingleton();
services.AddMvc();
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Error”);
}
app.UseAuthentication();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}”);
});
}
那么我在这里错过了什么?这应该是一个简单的实现,用于构造声明,然后通过API调用将其返回。谢谢~

更新 我现在在Core1.1中做了这个,花了大约30分钟。我很想知道我在核心2中做错了什么

代码如下: Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddAuthorization();
        services.AddAuthentication(options =>
        {
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        });

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookies",
            AutomaticAuthenticate = true,
            CookieName = "MyCookie",
            AutomaticChallenge = true,
            LoginPath = "/Home/Login"
        });

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

     HomeController.cs
    public async Task<IActionResult> SignIn()
    {
        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.Name, "Robert Lee"),
            new Claim(ClaimTypes.NameIdentifier, "CA2770"),
            new Claim(ClaimTypes.DateOfBirth, "8-8-2018")
        };

        var userIdentity = new ClaimsIdentity(claims, "SessionClaim");

        var userPrincipal = new ClaimsPrincipal(userIdentity);

        await HttpContext.Authentication.SignInAsync
        (CookieAuthenticationDefaults.AuthenticationScheme, 
         userPrincipal,
            new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                IsPersistent = false,
                AllowRefresh = false
            });

        return View();
    }

    SessionController.cs

    [HttpGet("claims", Name = "GetClaims")]
    public async Task<IEnumerable<Claim>> GetClaims()
    {
        var user = (User as ClaimsPrincipal);
        var claims = user.Claims;
        var isAuthed = user.Identity.IsAuthenticated;

        return await Task.FromResult(claims);
    } 
public void配置服务(IServiceCollection服务)
{
//添加框架服务。
services.AddAuthorization();
services.AddAuthentication(选项=>
{
options.signnscheme=CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddMvc();
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
loggerFactory.AddConsole(Configuration.GetSection(“Logging”);
loggerFactory.AddDebug();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationScheme=“Cookies”,
自动验证=真,
CookieName=“MyCookie”,
自动挑战=正确,
LoginPath=“/Home/Login”
});
app.UseStaticFiles();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}
HomeController.cs
公共异步任务登录()
{
var索赔=新列表()
{
新索赔(ClaimTypes.Name,“Robert Lee”),
新索赔(ClaimTypes.NameIdentifier,“CA2770”),
新索赔(索赔类型.出生日期,“2018年8月8日”)
};
var userIdentity=新的索赔实体(索赔,“SessionClaim”);
var userPrincipal=newclaimsprincipal(userIdentity);
等待HttpContext.Authentication.SignInAsync
(CookieAuthenticationDefaults.AuthenticationScheme,
用户负责人,
新的AuthenticationProperties
{
ExpiresUtc=DateTime.UtcNow.AddMinutes(20),
ispersist=false,
AllowRefresh=false
});
返回视图();
}
SessionController.cs
[HttpGet(“索赔”,Name=“GetClaims”)]
公共异步任务GetClaims()
{
var user=(用户作为ClaimsPrincipal);
var索赔=user.claims;
var isauthenticed=user.Identity.IsAuthenticated;
返回等待任务。FromResult(索赔);
} 

您是从浏览器调用此api吗?该api是从Angular Js服务调用的。您需要根据请求发送cookie。。。您可以配置为每个请求或所有<代码>this.http.get('http://...“,{withCredentials:true})从邮递员或浏览器中,Core 2版本始终返回本地机构标识,而不是在索引方法中创建的标识,我理解,但是angular正在发送此标识吗?
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddAuthorization();
        services.AddAuthentication(options =>
        {
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        });

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookies",
            AutomaticAuthenticate = true,
            CookieName = "MyCookie",
            AutomaticChallenge = true,
            LoginPath = "/Home/Login"
        });

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

     HomeController.cs
    public async Task<IActionResult> SignIn()
    {
        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.Name, "Robert Lee"),
            new Claim(ClaimTypes.NameIdentifier, "CA2770"),
            new Claim(ClaimTypes.DateOfBirth, "8-8-2018")
        };

        var userIdentity = new ClaimsIdentity(claims, "SessionClaim");

        var userPrincipal = new ClaimsPrincipal(userIdentity);

        await HttpContext.Authentication.SignInAsync
        (CookieAuthenticationDefaults.AuthenticationScheme, 
         userPrincipal,
            new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                IsPersistent = false,
                AllowRefresh = false
            });

        return View();
    }

    SessionController.cs

    [HttpGet("claims", Name = "GetClaims")]
    public async Task<IEnumerable<Claim>> GetClaims()
    {
        var user = (User as ClaimsPrincipal);
        var claims = user.Claims;
        var isAuthed = user.Identity.IsAuthenticated;

        return await Task.FromResult(claims);
    }