Adding Endpoints with Authorization in separate PublicApi project (#413)
* Adding tests for GetById endpoint * Updating tests and messages * Adding paged endpoint and also AutoMapper * Authenticate endpoint works as bool with tests * Got JWT token security working with Create and Delete endpoints and Swashbuckle. * Working on getting cookie and jwt token auth working in the same app All tests are passing * Creating new project and moving APIs Build succeeds; tests need updated. * all tests passing after moving services to PublicApi project * Fix authorize attributes * Uncomment and update ApiCatalogControllerLists tests Co-authored-by: Eric Fleming <eric-fleming18@hotmail.com>
This commit is contained in:
193
src/PublicApi/Startup.cs
Normal file
193
src/PublicApi/Startup.cs
Normal file
@@ -0,0 +1,193 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using AutoMapper;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.eShopWeb.ApplicationCore.Constants;
|
||||
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
|
||||
using Microsoft.eShopWeb.ApplicationCore.Services;
|
||||
using Microsoft.eShopWeb.Infrastructure.Data;
|
||||
using Microsoft.eShopWeb.Infrastructure.Identity;
|
||||
using Microsoft.eShopWeb.Infrastructure.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Models;
|
||||
|
||||
namespace Microsoft.eShopWeb.PublicApi
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public Startup(IConfiguration configuration)
|
||||
{
|
||||
Configuration = configuration;
|
||||
}
|
||||
|
||||
public IConfiguration Configuration { get; }
|
||||
|
||||
public void ConfigureDevelopmentServices(IServiceCollection services)
|
||||
{
|
||||
// use in-memory database
|
||||
ConfigureInMemoryDatabases(services);
|
||||
|
||||
// use real database
|
||||
//ConfigureProductionServices(services);
|
||||
}
|
||||
|
||||
private void ConfigureInMemoryDatabases(IServiceCollection services)
|
||||
{
|
||||
// use in-memory database
|
||||
services.AddDbContext<CatalogContext>(c =>
|
||||
c.UseInMemoryDatabase("Catalog"));
|
||||
|
||||
// Add Identity DbContext
|
||||
services.AddDbContext<AppIdentityDbContext>(options =>
|
||||
options.UseInMemoryDatabase("Identity"));
|
||||
|
||||
ConfigureServices(services);
|
||||
}
|
||||
|
||||
public void ConfigureProductionServices(IServiceCollection services)
|
||||
{
|
||||
// use real database
|
||||
// Requires LocalDB which can be installed with SQL Server Express 2016
|
||||
// https://www.microsoft.com/en-us/download/details.aspx?id=54284
|
||||
services.AddDbContext<CatalogContext>(c =>
|
||||
c.UseSqlServer(Configuration.GetConnectionString("CatalogConnection")));
|
||||
|
||||
// Add Identity DbContext
|
||||
services.AddDbContext<AppIdentityDbContext>(options =>
|
||||
options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));
|
||||
|
||||
ConfigureServices(services);
|
||||
}
|
||||
|
||||
public void ConfigureTestingServices(IServiceCollection services)
|
||||
{
|
||||
ConfigureInMemoryDatabases(services);
|
||||
}
|
||||
|
||||
|
||||
// This method gets called by the runtime. Use this method to add services to the container.
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddIdentity<ApplicationUser, IdentityRole>()
|
||||
.AddEntityFrameworkStores<AppIdentityDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
services.AddScoped(typeof(IAsyncRepository<>), typeof(EfRepository<>));
|
||||
services.Configure<CatalogSettings>(Configuration);
|
||||
services.AddSingleton<IUriComposer>(new UriComposer(Configuration.Get<CatalogSettings>()));
|
||||
services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
|
||||
services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>();
|
||||
|
||||
// Add memory cache services
|
||||
services.AddMemoryCache();
|
||||
|
||||
// https://stackoverflow.com/questions/46938248/asp-net-core-2-0-combining-cookies-and-bearer-authorization-for-the-same-endpoin
|
||||
var key = Encoding.ASCII.GetBytes(AuthorizationConstants.JWT_SECRET_KEY);
|
||||
services.AddAuthentication(config =>
|
||||
{
|
||||
//config.DefaultScheme = "smart";
|
||||
//config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
//config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
|
||||
config.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
config.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddJwtBearer(x =>
|
||||
{
|
||||
x.RequireHttpsMetadata = false;
|
||||
x.SaveToken = true;
|
||||
x.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(key),
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
services.AddControllers();
|
||||
|
||||
services.AddAutoMapper(typeof(Startup).Assembly);
|
||||
|
||||
services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
|
||||
c.EnableAnnotations();
|
||||
c.SchemaFilter<CustomSchemaFilters>();
|
||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||
{
|
||||
Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n
|
||||
Enter 'Bearer' [space] and then your token in the text input below.
|
||||
\r\n\r\nExample: 'Bearer 12345abcdef'",
|
||||
Name = "Authorization",
|
||||
In = ParameterLocation.Header,
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
Scheme = "Bearer"
|
||||
});
|
||||
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference
|
||||
{
|
||||
Type = ReferenceType.SecurityScheme,
|
||||
Id = "Bearer"
|
||||
},
|
||||
Scheme = "oauth2",
|
||||
Name = "Bearer",
|
||||
In = ParameterLocation.Header,
|
||||
|
||||
},
|
||||
new List<string>()
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// 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();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
// 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.UseEndpoints(endpoints =>
|
||||
{
|
||||
endpoints.MapControllers();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user