I'm working on the latest ASP.NET Core 3.0 Angular template. What I need to know is how we can get authenticated user, username in ActionFilterAttribute
.
The ClaimTypes.NameIdentifier
returns the current user id, and ClaimTypes.Name
returns the username which is null.
Here is my code:
where getUser
has a UserId
of d15f997a-6f65-4eb2-aecb-8b525361ae50
I've also register IHttpContextAccessor in the Startup class as follows:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
//Database Setup
services.AddDbContext<HashooDBContext>(Configuration.GetConnectionString("DefaultConnection"));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllersWithViews();
services.AddRazorPages();
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
return ContainerSetup.InitializeWeb(Assembly.GetExecutingAssembly(), services);
}
Controller.cs:
[Authorize]
[ApiController]
[Route("api/[controller]/{companycode}")]
public class DashboardTransactionsController : ControllerBase
{
[CustomAuthorizationFilter("companycode")]
public string Get()
{
return "Welcome";
}
}
Please let me know what am I doing wrong?
Getting Current UserName in Controller Getting UserName in Controller is easy as you can directly access the HttpContext object within Controller. You need to access HttpContext.User.Identity.Name property to access the username.
GetCurrent(). Name; Returns: NetworkName\Username. Gets the user's Windows logon name.
Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an . aspx page without using the fully qualified class reference to HttpContext. For example, you can use User.Identity.Name to get the name of the user on whose behalf the current process is running.
You can use IHttpContextAccessor
private readonly IHttpContextAccessor _httpContextAccessor;
public UserService(
IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
And to get user name you can use
_httpContextAccessor?.HttpContext?.User?.Identity?.Name;
Or
_httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
Then register in your Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With