Я пишу проект веб-приложения, используя Asp. net cor 3.1, я описал возврат генерации токена, когда при отправке запроса на контроллер с атрибутом [Авторизовать] я возвращаю код состояния 401 , и я не понимаю, почему, много информации я прочитал, ничего не помогло. мой контроллер
[Authorize]
public class SchoolRequestController : BaseController
{
[HttpPost]
[ProducesResponseType(201)]
[ProducesResponseType(400)]
public async Task<ActionResult<long>> Create([FromBody] RegisterSchoolCommand command)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
try
{
var account = await Mediator.Send(command).ConfigureAwait(false);
return Ok(command);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
}
мой ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
//add AutoMapper
services.AddAutoMapper(new Assembly[] { typeof(AutoMapperProfile).GetTypeInfo().Assembly });
services.AddFluentValidation(new[] { typeof(AutoMapperProfile).GetTypeInfo().Assembly });
// add mediatr
services.AddMediatR(typeof(LoginCommandHandler).GetTypeInfo().Assembly);
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPerformanceBehaviour<,>));
services.AddControllers();
var connectionStringName = "YPSDataBase";
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My API",
Version = "v1"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
};
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme()
{
}, new string[] { }
}
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
{
c.IncludeXmlComments(xmlPath);
}
});
var key = Encoding.ASCII.GetBytes(Configuration["ApiKey"]);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthOptions.ISSUER,
ValidateAudience = true,
ValidAudience = AuthOptions.AUDIENCE,
ValidateLifetime = true,
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
ValidateIssuerSigningKey = true,
};
});
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddDbContext<IYPSDbContext, YPSDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString(connectionStringName),
x => x.MigrationsAssembly("YPS.Persistence")
));
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.Build());
});
services.AddControllersWithViews();
}
и мой класс Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
}