.NET 8,身份,承载问题

问题描述 投票:0回答:1

我正在使用 ASP.NET Core 8 构建一个 Web 应用程序(一个将用于我正在构建的游戏的权威服务器),并且我正在利用 Microsoft 的 Identity 来完成所有授权和身份验证。

使用 Postman 测试 Identity 的

AddIdentityApiEndpoints
端点,我能够成功登录注册用户,并返回:

{
    "tokenType": "Bearer",
    "accessToken": "CfDJ8...",
    "expiresIn": 3600,
    "refreshToken": "CfDJ8..."
}

使用

accessToken
(我假设这是 Postman 中
Bearer
令牌值所需要的),我尝试访问一个端点,该端点现在除了控制器位于
[Authorize]
标签后面之外什么也不做。然而我总是收到未经授权的 401。

Program.cs

public class Program
{
     public static void Main(string[] args)
     {
         //CREATE WEBAPP BUILDER
         var builder = WebApplication.CreateBuilder(args);

         builder.Services.AddIdentityApiEndpoints<IdentityUser>(options =>
         {
             options.Password.RequiredLength = 6;
             options.Password.RequireNonAlphanumeric = false;
             options.Password.RequireDigit = false;
             options.Password.RequireUppercase = false;
             options.Password.RequireLowercase = false;
         })
            // .AddRoles<IdentityRole>()
             .AddEntityFrameworkStores<MM_DbContext>();

         builder.Services.AddAuthentication(options =>
         {
             options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
             options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
             //options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
         }).AddJwtBearer(options =>
         {
             options.TokenValidationParameters = new TokenValidationParameters
             {
                 ValidateIssuer = true,
                 ValidateAudience = false,
                 ValidateLifetime = true,
                 ValidateIssuerSigningKey = true,
                 ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:Key"]!))
             };
         });

         // ADD SERVICES - DI ALLOWS TEST / NONTEST SERVICES
         builder.Services

             .AddScoped<Services.IArmouryService, Services.TestArmouryService>()
             //.AddScoped<Services.IAuthenticationService, Services.TestAuthenticationService>()
             .AddScoped<Services.IBattleboardService, Services.TestBattleboardService>()
             .AddScoped<Services.ICharacterService, Services.TestCharacterService>()
             .AddScoped<Services.IKingdomService, Services.TestKingdomService>()
             .AddScoped<Services.ISoupkitchenService, Services.TestSoupkitchenService>()
             .AddScoped<Services.ITreasuryService, Services.TestTreasuryService>();

         // POSTGRESQL CONNECTION
         builder.Services.AddDbContext<MM_DbContext>(options =>
             options.UseNpgsql(builder.Configuration.GetConnectionString("Db")));
         System.Diagnostics.Debug.WriteLine($"Connection String: {builder.Configuration.GetConnectionString("Db")}");

         // ADD CONTROLLERS
         builder.Services.AddControllers().AddNewtonsoftJson(o => { });

         // ADD SWASHBUCKLE/SWAGGER
         builder.Services.AddEndpointsApiExplorer();
         builder.Services.AddSwaggerGen();

         // NEW WEBAPP
         var app = builder.Build();

         app.MapIdentityApi<IdentityUser>();

         // USE SWAGGER IF DEVELOPING
         if (app.Environment.IsDevelopment())
         {
             app.UseSwagger();
             app.UseSwaggerUI();
         }

         // MISC
         app.UseAuthentication();
         app.UseAuthorization();
         app.MapControllers();

         // RUN
         app.Run();
     }
}

KingdomController

[Authorize]
[HttpPost("newmap")]
public async Task<ActionResult<IMapNewResponse>> NewMap([FromBody] MapNewPayload payload)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    try
    {
        var result = await _kingdomService.NewMap(payload);

        if (result is IMapNewResponse)
        {
            return Ok(result);
        }
        else
        {
            return StatusCode(500, "Unexpected error occurred"); //incorrect error code - unsure how to handle 
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine($"New map failed: {ex.Message}");
        return StatusCode(500, "Internal server error");
    }
}

我对网络服务器和身份框架相当陌生,正如你在我提交的代码块中看到的那样,我已经实现了一个基本的身份验证系统,但是我需要时间来解决所有问题Identity 已经提供的开箱即用的功能似乎不值得,我想继续开发游戏,而不是身份验证/授权系统。

我不确定还可以尝试什么或如何继续。

web-applications asp.net-core-webapi
1个回答
0
投票

我的工作如下

基本上生成的代币是为了

Identity.Bearer

builder.Services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = IdentityConstants.BearerScheme;
    options.DefaultChallengeScheme = IdentityConstants.BearerScheme;
    options.DefaultScheme = IdentityConstants.BearerScheme;
}).AddBearerToken(IdentityConstants.BearerScheme);

Debug

© www.soinside.com 2019 - 2024. All rights reserved.