/// <summary> /// Constructor of <see cref="ServiceCollectionHelper{TUser}"/>. /// /// <para> If you use this constructor, <see cref="IServiceCollection"/> and <see cref="IJsonOperations"/> objects are created as a singleton. </para> /// /// </summary> public ServiceCollectionHelper() { if (_services == null) { _services = new ServiceCollection(); } if (_jsonOperations == null) { _jsonOperations = new JsonOperations(); } Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); }
/// <summary> /// Creates a new <see cref="Startup"/> instances. /// </summary> /// <param name="configuration"></param> /// <param name="env"></param> public Startup(IConfiguration configuration, IWebHostEnvironment env) { WebHostEnvironment = env; Configuration = configuration; JsonOperations = new JsonOperations(); }
/// <summary> /// Using this method, you can configure the database. /// </summary> /// <param name="jsonOperations"></param> /// <param name="configuration"></param> protected abstract void ConfigureDatabase(IJsonOperations jsonOperations = null, IConfiguration configuration = null);
/// <summary> /// Constructor of <see cref="ServiceCollectionHelper{TUser}"/>. /// /// <para> If you use this constructor, you have to send <paramref name="services"/> and <paramref name="jsonOperations"/> objects. </para> /// /// </summary> /// <param name="services"></param> /// <param name="jsonOperations"></param> public ServiceCollectionHelper(IServiceCollection services, IJsonOperations jsonOperations) { _services = services; _jsonOperations = jsonOperations; }
public LockWriter(IFileSystem fileSystem, IJsonOperations jsonSerializer, ILockBuilder lockBuilder) { FileSystem = fileSystem ?? throw new ArgumentException(nameof(fileSystem)); JsonOperations = jsonSerializer ?? throw new ArgumentException(nameof(jsonSerializer)); LockBuilder = lockBuilder ?? throw new ArgumentException(nameof(lockBuilder)); }
/// <summary> /// Configures JWT Token Authentication. /// </summary> /// <param name="services"></param> /// <param name="jSONFile"></param> private static void ConfigureJWT(this IServiceCollection services, IJsonOperations jSONFile) { var tokenManagement = jSONFile.GetCryptedContentAsync <TokenManagement>(Path.Combine(GlobalConstants.RootPath, "StaticFiles", "JSON", "tokenmanagement.json")).Result; services.AddSingleton <ITokenManagement>(tokenManagement); //var tokenOptions = configuration.GetSection("tokenManagement").Get<TokenManagement>(); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { IStringLocalizer <SharedResource> GetLocalizerInstance(HttpContext httpContext) { return(httpContext.RequestServices.GetRequiredService <IStringLocalizer <SharedResource> >()); } Task ReturnResponse(HttpContext httpContext, string localizerKey, int statusCode) { if (!httpContext.Response.HasStarted) { var localizer = GetLocalizerInstance(httpContext); ExceptionResponse validationResponse = new() { Message = localizer["Unauthorized"], Success = false, StatusCode = statusCode }; httpContext.Response.ContentType = "application/json"; httpContext.Response.StatusCode = MilvaStatusCodes.Status200OK; return(httpContext.Response.WriteAsync(JsonConvert.SerializeObject(validationResponse))); } return(Task.CompletedTask); } x.Events = new JwtBearerEvents() { //Token içinde name kontrol etme OnTokenValidated = (context) => { if (string.IsNullOrWhiteSpace(context.Principal.Identity.Name) || context.SecurityToken is not JwtSecurityToken accessToken) //|| !SignedInUsers.SignedInUserTokens.ContainsKey(context.Principal.Identity.Name) //|| SignedInUsers.SignedInUserTokens[context.Principal.Identity.Name] != accessToken.RawData) { var localizer = GetLocalizerInstance(context.HttpContext); context.Fail(localizer["Unauthorized"]); ReturnResponse(context.HttpContext, "Unauthorized", MilvaStatusCodes.Status401Unauthorized); } return(Task.CompletedTask); }, OnForbidden = context => { return(ReturnResponse(context.HttpContext, "Forbidden", MilvaStatusCodes.Status403Forbidden)); }, OnChallenge = context => { // Skip the default logic. context.HandleResponse(); return(ReturnResponse(context.HttpContext, "Unauthorized", MilvaStatusCodes.Status401Unauthorized)); }, OnAuthenticationFailed = context => { string localizerKey = "Unauthorized"; if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { localizerKey = "TokenExpired"; } return(ReturnResponse(context.HttpContext, localizerKey, MilvaStatusCodes.Status401Unauthorized)); } }; x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenManagement.Secret)), ValidIssuer = tokenManagement.Issuer, ValidAudience = tokenManagement.Audience, //ClockSkew = TimeSpan.Zero // remove delay of token when expire }; }); /* Token ile ilgili * issuer: kısacası tokenin oluşturulmasıyla ilintili servis. * audience: tokenin kullanılacağı servis. * exp: tokenin son valid olduğu tarih. * nbf: tokenin aktif olmaya başlayacağı tarih. * iat: tokenin oluşturulduğu tarih */ } #endregion }
/// <summary> /// Configures AspNetCore.Identity.Mongo and JWT. /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <param name="jsonOperations"></param> public static void ConfigureIdentity(this IServiceCollection services, IConfiguration configuration, IJsonOperations jsonOperations) { Action <IdentityOptions> identityOptions = setupAction => { //Kullanıcı locklama süresi setupAction.Lockout.DefaultLockoutTimeSpan = new TimeSpan(3, 1, 0); //buradaki 3 saaat ekleme veri tabanı saati yanlış olduğundan dolayı // 1 ise 1 dakka kitleniyor setupAction.Lockout.MaxFailedAccessAttempts = 5; //Başarısız deneme sayısı setupAction.User.RequireUniqueEmail = true; setupAction.Password.RequireDigit = false; setupAction.Password.RequiredLength = 1; setupAction.Password.RequireLowercase = false; setupAction.Password.RequireNonAlphanumeric = false; setupAction.Password.RequireUppercase = false; setupAction.User.AllowedUserNameCharacters = "abcçdefghiıjklmnoöpqrsştuüvwxyzABCÇDEFGHIİJKLMNOÖPQRSŞTUÜVWXYZ0123456789-._"; }; services.AddIdentity <AppUser, AppRole>(identityOptions) .AddEntityFrameworkStores <EducationAppDbContext>() .AddUserValidator <MilvaUserValidation <AppUser, Guid, IStringLocalizer <SharedResource> > >() .AddErrorDescriber <MilvaIdentityDescriber <IStringLocalizer <SharedResource> > >() .AddUserManager <UserManager <AppUser> >() .AddDefaultTokenProviders(); services.ConfigureJWT(jsonOperations); }
/// <summary> /// Configures JWT for test. /// </summary> /// <param name="jSONFile"></param> private void ConfigureJWT(IJsonOperations jSONFile) { var localizer = _services.BuildServiceProvider().GetRequiredService <IStringLocalizer <SharedResource> >(); var tokenManagement = jSONFile.GetCryptedContentAsync <TokenManagement>(Path.Combine(FakeGlobalConstants.RootPath, "StaticFiles", "JSON", "tokenmanagement.json")).Result; _services.AddSingleton(tokenManagement); //var tokenOptions = configuration.GetSection("tokenManagement").Get<TokenManagement>(); _services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.Events = new JwtBearerEvents() { //Token içinde name kontrol etme OnTokenValidated = (context) => { var accessToken = context.SecurityToken as JwtSecurityToken; if (string.IsNullOrWhiteSpace(context.Principal.Identity.Name) || accessToken is null) { context.Fail(localizer["Unauthorized"]); } return(Task.CompletedTask); }, OnChallenge = context => { ExceptionResponse validationResponse = new ExceptionResponse() { Message = localizer["Forbidden"], Success = false, StatusCode = MilvaStatusCodes.Status403Forbidden }; if (context.HttpContext.Response.StatusCode == MilvaStatusCodes.Status401Unauthorized) { // Skip the default logic. context.HandleResponse(); context.HttpContext.Response.StatusCode = MilvaStatusCodes.Status200OK; context.HttpContext.Response.ContentType = "application/json"; if (context.HttpContext.Items.ContainsKey("Token-Expired")) { validationResponse.Message = localizer["AccountTimeOut"]; validationResponse.Success = false; validationResponse.StatusCode = MilvaStatusCodes.Status401Unauthorized; return(context.Response.WriteAsync(JsonConvert.SerializeObject(validationResponse))); } else { validationResponse.Message = localizer["Unauthorized"]; validationResponse.Success = false; validationResponse.StatusCode = MilvaStatusCodes.Status401Unauthorized; return(context.Response.WriteAsync(JsonConvert.SerializeObject(validationResponse))); } } else if (context.HttpContext.Response.StatusCode == MilvaStatusCodes.Status403Forbidden) { // Skip the default logic. context.HandleResponse(); context.HttpContext.Response.StatusCode = MilvaStatusCodes.Status200OK; context.HttpContext.Response.ContentType = "application/json"; validationResponse.Message = localizer["Forbidden"]; validationResponse.Success = false; validationResponse.StatusCode = MilvaStatusCodes.Status403Forbidden; return(context.Response.WriteAsync(JsonConvert.SerializeObject(validationResponse))); } return(Task.CompletedTask); }, OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.HttpContext.Items.Add("Token-Expired", "true"); } context.Response.StatusCode = MilvaStatusCodes.Status401Unauthorized; return(Task.CompletedTask); } }; x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenManagement.Secret)), ValidIssuer = tokenManagement.Issuer, ValidAudience = tokenManagement.Audience, //ClockSkew = TimeSpan.Zero // remove delay of token when expire }; }); /* Token ile ilgili * issuer: kısacası tokenin oluşturulmasıyla ilintili servis. * audience: tokenin kullanılacağı servis. * exp: tokenin son valid olduğu tarih. * nbf: tokenin aktif olmaya başlayacağı tarih. * iat: tokenin oluşturulduğu tarih */ }
public SampleDataController() { jsonOperations = new JsonOperations("./Assets/Pet.json"); }
public LockReader(IFileSystem fileSystem, ILockFinder lockFinder, IJsonOperations jsonOperations) { FileSytem = fileSystem ?? throw new ArgumentException(nameof(fileSystem)); LockFinder = lockFinder ?? throw new ArgumentException(nameof(lockFinder)); JsonOperations = jsonOperations ?? throw new ArgumentException(nameof(jsonOperations)); }