简体   繁体   中英

WEB API .NET 6.0 - current user

I'm having troubles with .NET 6.0 REST Web API. I managed to do figure out just about everything, except authorizations. For my logic I need to get current user.

This is how I create Authentication, I am using JWT:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options =>
{
   options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
   options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
    o.SaveToken = true;
    o.RequireHttpsMetadata = false;
    o.TokenValidationParameters = new TokenValidationParameters
    {
    ValidIssuer = builder.Configuration["Jwt:Issuer"],
    ValidAudience = builder.Configuration["Jwt:Audience"],
    IssuerSigningKey = new SymmetricSecurityKey
        (Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = false,
    ValidateIssuerSigningKey = true
    };
 });

builder.Services.AddAuthorization();

var app = builder.Build();

this works OK.

I love this concept of app.MapGet, but for the love of god can't figure it out how to get current user.

problem:

app.MapGet("/Locations",[Authorize] () =>{

   //string user = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
   string user = ""; // <- how to get user -> problem :( 
   return MyMethods.GetLocations(builder, user);});

this.User.FindFirst(ClaimTypes.NameIdentifier).Value doesnt work here..

I figure it out, how I can get a user in controller, user is in ControllerBase. Like this:

[Authorize]
[ApiController]
[Route("[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class AppDataController : ControllerBase
{
    [HttpGet(Name = "GetAppData")]
    public IEnumerable<AppData> Get()
    {
        var currentUserID = this.User.FindFirst(ClaimTypes.NameIdentifier).Value; //<-- this is working OK
  ... 

This is working just fine. But the same code is not working in app.MapGet

So my question is, how do I read user (stored in claim)?

Just figure it out.. :|

app.MapGet("/Locations",[Authorize] (ClaimsPrincipal user) =>{ return MyMethods.GetLocations(builder,   user.FindFirst(ClaimTypes.NameIdentifier).Value);});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM