1
0
mirror of https://github.com/bitwarden/server.git synced 2025-03-02 04:11:04 +01:00
bitwarden-server/src/Api/Startup.cs

192 lines
7.4 KiB
C#
Raw Normal View History

2015-12-09 04:57:38 +01:00
using System;
using System.Security.Claims;
2016-05-20 01:10:24 +02:00
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
2015-12-09 04:57:38 +01:00
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
2016-05-20 01:10:24 +02:00
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
2015-12-09 04:57:38 +01:00
using Bit.Api.Utilities;
using Bit.Core;
using Bit.Core.Domains;
using Bit.Core.Identity;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Repos = Bit.Core.Repositories.SqlServer;
2016-05-20 01:10:24 +02:00
using System.Text;
using StackExchange.Redis.Extensions.Core;
using StackExchange.Redis.Extensions.Newtonsoft;
2016-06-21 06:30:36 +02:00
using Loggr.Extensions.Logging;
using Newtonsoft.Json;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
2015-12-09 04:57:38 +01:00
namespace Bit.Api
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
2016-05-20 01:10:24 +02:00
.SetBasePath(env.ContentRootPath)
2015-12-09 04:57:38 +01:00
.AddJsonFile("settings.json")
.AddJsonFile($"settings.{env.EnvironmentName}.json", optional: true);
if(env.IsDevelopment())
{
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
2016-05-20 01:10:24 +02:00
var provider = services.BuildServiceProvider();
2015-12-09 04:57:38 +01:00
// Options
services.AddOptions();
// Settings
2016-05-20 01:10:24 +02:00
var globalSettings = new GlobalSettings();
ConfigurationBinder.Bind(Configuration.GetSection("GlobalSettings"), globalSettings);
2015-12-09 04:57:38 +01:00
services.AddSingleton(s => globalSettings);
// Caching
ISerializer serializer = new NewtonsoftSerializer(new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
services.AddSingleton(s => serializer);
ICacheClient cacheClient = new StackExchangeRedisCacheClient(serializer,
globalSettings.Cache.ConnectionString, globalSettings.Cache.Database);
services.AddSingleton(s => cacheClient);
2015-12-09 04:57:38 +01:00
// Repositories
services.AddSingleton<IUserRepository, Repos.UserRepository>();
services.AddSingleton<ICipherRepository, Repos.CipherRepository>();
services.AddSingleton<IDeviceRepository, Repos.DeviceRepository>();
2015-12-09 04:57:38 +01:00
// Context
services.AddScoped<CurrentContext>();
// Identity
services.AddTransient<ILookupNormalizer, LowerInvariantLookupNormalizer>();
services.AddJwtBearerIdentity(options =>
{
options.User = new UserOptions
{
RequireUniqueEmail = true,
AllowedUserNameCharacters = null // all
};
options.Password = new PasswordOptions
{
RequireDigit = false,
RequireLowercase = false,
RequiredLength = 8,
2016-05-20 01:10:24 +02:00
RequireNonAlphanumeric = false,
2015-12-09 04:57:38 +01:00
RequireUppercase = false
};
options.ClaimsIdentity = new ClaimsIdentityOptions
{
SecurityStampClaimType = "securitystamp",
UserNameClaimType = ClaimTypes.Email
};
options.Tokens.ChangeEmailTokenProvider = TokenOptions.DefaultEmailProvider;
}, jwtBearerOptions =>
{
jwtBearerOptions.Audience = "bitwarden";
jwtBearerOptions.Issuer = "bitwarden";
jwtBearerOptions.TokenLifetime = TimeSpan.FromDays(10 * 365);
jwtBearerOptions.TwoFactorTokenLifetime = TimeSpan.FromMinutes(10);
2016-05-20 01:10:24 +02:00
var keyBytes = Encoding.ASCII.GetBytes(globalSettings.JwtSigningKey);
jwtBearerOptions.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256);
2015-12-09 04:57:38 +01:00
})
.AddUserStore<UserStore>()
.AddRoleStore<RoleStore>()
.AddTokenProvider<AuthenticatorTokenProvider>("Authenticator")
.AddTokenProvider<EmailTokenProvider<User>>(TokenOptions.DefaultEmailProvider);
var jwtIdentityOptions = provider.GetRequiredService<IOptions<JwtBearerIdentityOptions>>().Value;
2015-12-31 00:49:43 +01:00
services.AddAuthorization(config =>
2015-12-09 04:57:38 +01:00
{
2015-12-31 00:49:43 +01:00
config.AddPolicy("Application", new AuthorizationPolicyBuilder()
2015-12-09 04:57:38 +01:00
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().RequireClaim(ClaimTypes.AuthenticationMethod, jwtIdentityOptions.AuthenticationMethod).Build());
2015-12-31 00:49:43 +01:00
config.AddPolicy("TwoFactor", new AuthorizationPolicyBuilder()
2015-12-09 04:57:38 +01:00
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().RequireClaim(ClaimTypes.AuthenticationMethod, jwtIdentityOptions.TwoFactorAuthenticationMethod).Build());
});
services.AddScoped<AuthenticatorTokenProvider>();
// Services
services.AddSingleton<IMailService, MailService>();
services.AddSingleton<ICipherService, CipherService>();
2015-12-09 04:57:38 +01:00
services.AddScoped<IUserService, UserService>();
services.AddScoped<IPushService, PushService>();
2015-12-09 04:57:38 +01:00
// Cors
2015-12-31 00:49:43 +01:00
services.AddCors(config =>
{
config.AddPolicy("All", policy =>
policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().SetPreflightMaxAge(TimeSpan.FromDays(1)));
2015-12-31 00:49:43 +01:00
});
2015-12-09 04:57:38 +01:00
// MVC
2015-12-31 00:49:43 +01:00
services.AddMvc(config =>
2015-12-09 04:57:38 +01:00
{
2015-12-31 00:49:43 +01:00
config.Filters.Add(new ExceptionHandlerFilterAttribute());
config.Filters.Add(new ModelStateValidationFilterAttribute());
// Allow JSON of content type "text/plain" to avoid cors preflight
var textPlainMediaType = MediaTypeHeaderValue.Parse("text/plain");
foreach(var jsonFormatter in config.InputFormatters.OfType<JsonInputFormatter>())
{
jsonFormatter.SupportedMediaTypes.Add(textPlainMediaType);
}
2015-12-09 04:57:38 +01:00
});
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
GlobalSettings globalSettings)
2015-12-09 04:57:38 +01:00
{
loggerFactory.AddConsole();
loggerFactory.AddDebug();
if(!env.IsDevelopment())
{
2016-06-21 06:30:36 +02:00
loggerFactory.AddLoggr(
LogLevel.Error,
globalSettings.Loggr.LogKey,
globalSettings.Loggr.ApiKey);
}
2015-12-09 04:57:38 +01:00
// Add static files to the request pipeline.
app.UseStaticFiles();
// Add Cors
app.UseCors("All");
// Add Jwt authentication to the request pipeline.
app.UseJwtBearerIdentity();
// Add MVC to the request pipeline.
app.UseMvc();
}
}
}