beewest
beewest

Reputation: 4846

asp.net core 1.0 get windows identity in webapi

I am create a Asp.net Core 1.0 (WebApi) project using Visual Studio 2015. The template is ASP.NET Core Web Application (.NET Core)\WebApi (No Authentication selected).

enter image description here

In the ValuesController, I would like to get the Windows Identity from client who is calling that method.

using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
...
[Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpGet]
        [Route("GetIdentity")]
        public string GetIdentity()
        {
            //method1
            var userId = User.GetUserId();
            //method2
            var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            return userId;
        }
    }

Currently no result returns as expected in method1 and method2 . Any thoughts pls?

Upvotes: 2

Views: 2937

Answers (1)

Ralf Bönning
Ralf Bönning

Reputation: 15415

Without any authentication no web framework will be able to determine the identity of your user.

Choose the project template "ASP.NET Core Application (.NET Core)\WebApi" and change the authentication from "No Authentication" to any authentication you find appropriate, e.g. "Windows Authentication".

Then you can access the User member of a controller, if it is annotated with the [Authorize] attribute.

[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{        
    [HttpGet]
    public string Get()
    {
        return User.Identity.Name;
    }
}

If you want to have individual user accounts, then choose the MVC template (instead of WebAPI). Then you can register individual accounts and use their credentials for authentication.

If you have started from an template without authentication, then you can enable Windows Authentication in the launchSettings.json in the Properties folder.

{
   "iisSettings": {
      "windowsAuthentication": true,
      "anonymousAuthentication": false,
      ...
    },
    ...
 }

Upvotes: 3

Related Questions