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

时间:2017-09-09 14:43:10

标签: asp.net-web-api asp.net-core claims-based-identity asp.net-core-webapi

这个问题此刻让我非常努力。 Web API 2中从来没有出现问题,现在在Core中,我无法获取登录用户的当前声明或身份。

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

    public async Task<IActionResult> Index()
    {
        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.Name, "CA19207"),
            new Claim(ClaimTypes.Actor, "2770"),
            new Claim(ClaimTypes.DateOfBirth, "User")
        };

        var identity = new ClaimsIdentity(claims, "TNEVP");
        var principal = new ClaimsPrincipal(identity);

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

      var isIn = principal.Identity.IsAuthenticated;//returns true
      var isAuthed = (HttpContext.User.Identity as ClaimsIdentity).IsAuthenticated;//returns false

        return Ok();
    }

然后从我的Angular 2服务中,我打电话给api / user以获取登录用户的声明。但是,声明集为空,用户未经过身份验证。

    [HttpGet("claims")]
    public async Task<IEnumerable<Claim>> Get()
    {
        var claims = (User as ClaimsPrincipal).Claims;
        return await Task.FromResult(claims);
    }

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}");
        });
    }

那我在这里错过了什么?这应该是一个简单的实现来构造声明,然后通过API调用返回它们。谢谢!〜

更新 我现在在Core 1.1中工作了大约30分钟。我很想知道我在Core 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);
    } 

0 个答案:

没有答案