Я хочу реализовать защиту на основе JWT в ASP. NET Core 3.1. Мой код работает, когда я использую Visual Studio и запускаю свой проект api оттуда. Но когда я собираюсь запустить проект из VS Code, используя do tnet cli dotnet run
, тогда мой метод входа в систему работает только, и я могу видеть токен в куки, но остальная часть моего API, как получение пользователей, дает неавторизованные 401 для me.
Ссылки следующие:
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DatingApp.API.Data;
using DatingApp.API.Helpers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
namespace DatingApp.API {
public class Startup {
public Startup (IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices (IServiceCollection services) {
// Register the Swagger generator, defining 1 or more Swagger documents
//services.AddSwaggerGen(c =>
//{
// c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
//});
services.AddSwaggerGen (c => {
c.SwaggerDoc ("v1", new OpenApiInfo {
Title = "Dating App API",
Version = "v1"
});
c.AddSecurityDefinition ("Bearer", new OpenApiSecurityScheme {
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement (new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
services.AddMvc ().SetCompatibilityVersion (CompatibilityVersion.Version_3_0);
services.AddDbContext<DataContext> (x => x.UseSqlite (Configuration.GetConnectionString ("DefaultConnection")));
services.AddCors (options => {
options.AddPolicy ("CorsPolicy",
builder => builder.AllowAnyOrigin ()
.AllowAnyMethod ()
.AllowAnyHeader ());
});
services.Configure<CloudinarySettings> (Configuration.GetSection ("CloudinarySettings"));
services.AddAutoMapper (typeof (DatingRepository).Assembly);
services.AddScoped<IAuthRepository, AuthRepository> ();
services.AddScoped<IDatingRepository, DatingRepository> ();
services.AddAuthentication (JwtBearerDefaults.AuthenticationScheme)
.AddCookie (cfg => cfg.SlidingExpiration = true)
.AddJwtBearer (options => {
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey (Encoding.ASCII
.GetBytes (Configuration.GetSection ("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure (IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment ()) {
app.UseDeveloperExceptionPage ();
} else {
app.UseExceptionHandler (builder => {
builder.Run (async context => {
context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature> ();
if (error != null) {
context.Response.AddApplicationError (error.Error.Message);
await context.Response.WriteAsync (error.Error.Message);
}
});
});
// 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.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");
c.RoutePrefix = string.Empty;
});
// app.UseHttpsRedirection();
app.UseRouting ();
app.UseCors ("CorsPolicy");
app.UseAuthentication ();
app.UseAuthorization ();
app.UseEndpoints (endpoints => {
endpoints.MapControllers ().RequireCors ("CorsPolicy");
});
}
}
}
UserController.cs