public AccessToken CreateAccessToken(User user) { var accessTokenExpiration = DateTime.Now.AddMinutes(tokenOptions.AccessTokenExpiration); //token expire zamanı belirlenir var securityKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey); //tokenı imazalamk için secirtykey oluşturulur SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); //secuirtykey seçilen algoritma ile şifrelenir JwtSecurityToken jwtSecurityToken = new JwtSecurityToken( issuer: tokenOptions.Issuer, audience: tokenOptions.Audience, expires: accessTokenExpiration, notBefore: DateTime.Now, signingCredentials: signingCredentials, claims: GetClaims(user) ); var handler = new JwtSecurityTokenHandler(); var token = handler.WriteToken(jwtSecurityToken); return(new AccessToken() { Token = token, Expiration = accessTokenExpiration, RefreshToken = CreateRefreshToken() }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <IUserService, UserService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IProductService, ProductService>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddSwaggerGen(C => { C.SwaggerDoc("v1", new OpenApiInfo { Title = "SwaggerTestCore", Version = "v1" }); }); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); //options.AddPolicy("abcpolicy", builder => //{ // builder.WithHeaders("content-type","...").WithMethods("POST","GET").WithOrigins(); //}); }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidAudience = tokenOptions.Audience, ValidateIssuer = true, ValidIssuer = tokenOptions.Issuer, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddControllers(); services.AddDbContext <apitokendbContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddPersistence(Configuration); services.AddRepository(); services.AddServices(); services.AddTokens(); services.AddControllers(); var tokenopts = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtopt => { jwtopt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenopts.Issuer, ValidAudience = tokenopts.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenopts.SecurityKey), ClockSkew = TimeSpan.Zero }; }); Microsoft.OpenApi.Models.OpenApiInfo inf = new Microsoft.OpenApi.Models.OpenApiInfo(); inf.Title = "Authentication API"; inf.Description = "SWAGGER DOCUMENT"; var config = new MapperConfiguration(cfg => { cfg.AddProfile <DomainToResponseProfile>(); }); IMapper mapper = config.CreateMapper(); services.AddSingleton(mapper); services.AddSwaggerGen(c => { c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.OperationFilter <SecurityRequirementsOperationFilter>(); c.SwaggerDoc("v1", inf); var xmlPath = System.AppDomain.CurrentDomain.BaseDirectory + @"Authentication.xml"; c.IncludeXmlComments(xmlPath); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <IUserService, UserService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IAnnouncementService, AnnouncementService>(); services.AddScoped <IAnnouncementRepository, AnnouncementRepository>(); services.AddScoped <ILikeService, LikeService>(); services.AddScoped <ILikeRepository, LikeRepository>(); services.AddScoped <IInteractionRepository, InteractionRepository>(); services.AddScoped <IInteractionService, InteractionService>(); services.AddScoped <IRecommendationRepository, RecommendationRepository>(); services.AddScoped <IRecommendationService, RecommendationService>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddHttpContextAccessor(); services.AddHttpClient(); services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext <AnnouncAppDBContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddScoped(typeof(IGenericService <>), typeof(GenericService <>)); services.AddScoped <IUserService, UserService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IProductService, ProductService>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped(typeof(IGenericRepositories <>), typeof(GenericRepositories <>)); services.AddScoped(typeof(IGenericsService <>), typeof(GenericsService <>)); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); /* * opts.AddPolicy("abcPolicy", builder => * { * builder.WithOrigins("http://www.abc.com").AllowAnyHeader().AllowAnyMethod(); * }); */ }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddDbContext <ApiWithTokenDBContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserService, UserService>(); services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddDbContext <AppIdentityDbContext>(opts => { opts.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionStrings")); }); services.AddMvc(); services.AddIdentity <AppUser, AppRole>(opts => { opts.User.RequireUniqueEmail = true; opts.User.AllowedUserNameCharacters = "qwertyuýopðüiþlkjhgfdsazxcvbnmöçQWERTYUIOPÐÜÝÞLKJHGFDSAZXCVBNMÖÇ=._"; opts.Password.RequiredLength = 4; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequireLowercase = false; opts.Password.RequireUppercase = false; opts.Password.RequireDigit = false; }).AddEntityFrameworkStores <AppIdentityDbContext>(); services.Configure <CustomTokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <CustomTokenOptions>(); services.AddAuthentication(opts => { opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtOpt => { jwtOpt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddControllers(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.AddAutoMapper(typeof(Startup)); //services.AddCors(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticateService, AuthenticateService>(); services.AddScoped(typeof(IRepository <>), typeof(Repository <>)); services.AddScoped(typeof(IService <>), typeof(Service <>)); services.AddScoped <IStudentService, StudentService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IDepartmentService, DepartmentService>(); services.AddScoped <IUnitOfwork, UnitOfWork>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddMvc() .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddCors(configs => { configs.AddPolicy("Cemcir", bldr => { bldr.AllowAnyHeader(). AllowAnyMethod(). AllowAnyOrigin(); }); }); services.AddDbContext <AppDbContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:SqlConStr"].ToString(), o => { o.MigrationsAssembly("FullCRUDImplementsWithJquery.Data"); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserService, UserService>(); services.AddCors(opt => { opt.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddDbContext <AppIdentityDbContext>(op => { op.UseSqlServer(Configuration["ConnectionString:Default"]); }); services.AddIdentity <AppUser, AppRole>(opt => { opt.User.RequireUniqueEmail = true; opt.User.AllowedUserNameCharacters = "qüertyuiopöğasdfghjklıəzxcvbnmQÜERTYUİOPÖĞASDFGHJKLIƏZXCVBNM0123456789._"; opt.Password.RequireDigit = true; opt.Password.RequiredLength = 4; opt.Password.RequireLowercase = true; opt.Password.RequireUppercase = false; opt.Password.RequireNonAlphanumeric = false; }) .AddEntityFrameworkStores <AppIdentityDbContext>(); services.Configure <CustomTokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <CustomTokenOptions>(); services.AddAuthentication(op => { op.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; op.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtbearer => { jwtbearer.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidAudience = tokenOptions.Audience, ValidIssuer = tokenOptions.Issuer, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <UdemyApiWithTokenDBContext>(options => options.UseMySql(Configuration["ConnectionStrings:DefaultConnectionString"])); services.AddControllers(); services.AddScoped <Domain.Services.IAuthenticationService, Services.AuthenticationService>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IProductService, ProductService>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); /* * opts.AddPolicy("abc", builder => { * * builder.WithOrigins("https://www.abc.com").AllowAnyHeader().AllowAnyMethod(); * * }); */ }); //eğer projemin Herhangi bir yerinde TokenOptions görürse bunu appsettings.json dosyasında ki TokenOptions olarak alıcak //daha iyi anlatmak gerekirse bunun bir aşağısında yazdığım getSection kısmını her yerde yazmama gerek kalmiyacak services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey) }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //User. services.AddScoped <IUserServices, UserServices>(); services.AddScoped <IUserRepository, UserRepository>(); //Token la karsilasmaı icin bir services ekliyoruz services.AddScoped <ITokenHandler, TokenHandler>(); //Authentication services eklenmesi services.AddScoped <IAuthenticationServices, AuthenticationServices>(); //Product services.AddScoped <IProductServices, ProductServices>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); }); services.AddControllers(); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtBearOptions => { jwtBearOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddDbContext <WebApiContext>(options => { options.UseSqlServer(Configuration["ConnectionString:DefaultConnectionString"]); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); // uygulamanın her yerinde kullanmak için. TokenOptions tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddScoped <ICategoryService, CategoryService>(); services.AddScoped <IProductService, ProductService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ICategoryRepository, CategoryRepository>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddCors(corsops => { corsops.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, // ValidIssuer = "www.myapi.com" uzun yol bunu kısa yolda yapalım OOP mantığına uygun olarak. ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey) }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext <ApiWithTokenDBContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserService, UserService>(); services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddDbContext <AppIdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <AppUser, AppRole>(options => { options.User.RequireUniqueEmail = true; options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.Password.RequiredLength = 4; options.Password.RequireNonAlphanumeric = false; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequireDigit = false; }).AddEntityFrameworkStores <AppIdentityDbContext>(); services.Configure <CustomTokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <CustomTokenOptions>(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtbaeareroptions => { jwtbaeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
public AccessToken CreateAccessToken(AppUser user) { var accessTokenExpiration = DateTime.Now.AddMinutes(_tokenOption.AccessTokenExpiration); var securityKey = SignHandler.GetSecurityKey(_tokenOption.SecurityKey); SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); JwtSecurityToken jwtSecurityToken = new JwtSecurityToken( issuer: _tokenOption.Issuer, audience: _tokenOption.Audience, expires: accessTokenExpiration, notBefore: DateTime.Now, signingCredentials: signingCredentials, claims: GetTokenClaims(user) ); var handler = new JwtSecurityTokenHandler(); var token = handler.WriteToken(jwtSecurityToken); return(new AccessToken(token, accessTokenExpiration, CreateRefreshToken())); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddControllers(); services.AddCors(opt => { opt.AddDefaultPolicy(builder => { //all data accepted. //if some get request allowanyheader method into can be defineable. //AllowAnyMethod=>Post,Put,Delete,Get accepted. builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); //Example=>addpolicy //opt.AddPolicy("abcPolicy", builder => //{ // builder.WithOrigins("https://www.abc.com").AllowAnyHeader().AllowAnyMethod(); //}); }); services.Configure <TokenOptions>(_Configuration.GetSection("TokenOptions"));// Uygulamanýn tamamýnda kullanmak için created. var tokenOptions = _Configuration.GetSection("TokenOptions").Get <TokenOptions>(); //OAuth 2.0 protokolünü kullanýlýyor.Ýki kaynak arasýnda kimlik dogrulama için kullanýlýr.Bu token bicimini kullanýyor.Bu sayede services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt => { opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, //For another server is important.Gecikme için tölere edilebilir. ClockSkew = TimeSpan.FromMinutes(1), IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey) }; }); services.AddDbContext <DatabaseContext>(options => options.UseSqlServer(_Configuration.GetConnectionString("DatabaseContext"))); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(opt => { opt.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); }); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, //ClockSkew =TimeSpan.Zero, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey) }; }); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ITokenHandler, TokenHandlers>(); services.AddScoped <IProductService, ProductService>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <IUserService, UserService>(); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); services.AddDbContext <DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("db"))); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "ApiWithToken", Version = "v1" }); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddControllers().AddNewtonsoftJson(); services.AddDbContext <ApiWithTokenDBContext>(); services.AddScoped(typeof(IService <>), typeof(Service <>)); services.AddScoped(typeof(IRepository <>), typeof(Repository <>)); services.AddScoped <IUserService, UserService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(typeof(ProductMapping)); services.AddAutoMapper(typeof(UserMapping)); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwt => { jwt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddDbContext <TokenContext>(opt => { opt.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); services.AddScoped <IUserService, UserService>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddTransient <IProductService, ProductService>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddCors(opt => { opt.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwt => { jwt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience }; }); }
public static void AddJWTTokenOption(this IServiceCollection services, IConfiguration configuration) { var jwtTokenSection = configuration.GetSection("TokenOption"); services.Configure <TokenOption>(jwtTokenSection); var tokenOption = jwtTokenSection.Get <TokenOption>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(jwtOption => { jwtOption.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOption.Issuer, ValidAudience = tokenOption.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOption.SecurityKey), ClockSkew = TimeSpan.Zero, }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); TokenOptions tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(JwtBearerOptions => { JwtBearerOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, //Json ValidateAudience alalnýnda belirtildiði yerden mi geliyor ValidateIssuer = true, //Json ValidateIssuer alalnýnda belirtildiði yerden mi geliyor ValidateLifetime = true, ValidateIssuerSigningKey = true, //ValidIssuer = Configuration["TokenOptions:Isuuer"], ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, //IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)); IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContextPool <AppIdentityContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("IdentityCon")); }); services.AddIdentity <AppUser, AppRole>(opts => { opts.User.RequireUniqueEmail = true; opts.User.AllowedUserNameCharacters = "1234567890*-qwertyuýopðüasdfghjklþi,<zxcvbnmöç.QWERTYUIOPÐÜASDFGHJKLÞÝ,<ZXCVBNMÖÇ."; opts.Password.RequiredLength = 4; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequireLowercase = false; opts.Password.RequireUppercase = false; opts.Password.RequireDigit = false; }).AddEntityFrameworkStores <AppIdentityContext>(); //service containerýna tokenoptions eklendi böylece applicationda her yerde ctor injection ile bu deðerlere ulaþýlabilecek services.Configure <AppTokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <AppTokenOptions>(); #region JWT services.AddAuthentication(opts => { opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; //identity ile token sisteminin eþleþmesi için bu arkadaþ önemli tam olarak bakacaðým ne iþe yaradýðýna opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { //bu bilgiler token ile gelecek her requestte kontrol edilecek ValidateAudience = true, //dinleyiciyi doðrula tokený gönderen doðrumu ayarlardaki ile ValidateIssuer = true, //token içinde gelen issuer bilgisini valide et ayarlardaki ile aynýmý ValidateLifetime = true, //token expirationý kontrol et ValidateIssuerSigningKey = true, ValidAudience = tokenOptions.Audience, //geçerli dinleyici ValidIssuer = tokenOptions.Issuer, //geçerli issuer IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), //verify signature gerekli tipe dönüþtürülerek token optionsa deðeri atanýr ver validasyon bu keye göre yapýlýr ClockSkew = TimeSpan.Zero //farklý saat dilimlerinde token ömrünü uzatmak için kullanýlýr }; }); ///Default olarak bearer eklendikten sonra farklý tipl kullanýcýlar için farklý þemadaki tokenlar oluþturulup kullanýlabilir //services.AddAuthentication(opts => //{ // opts.DefaultAuthenticateScheme = "CustomSchema"; // opts.DefaultChallengeScheme = "CustomSchema"; // //identity ile token sisteminin eþleþmesi için tam olarak bakacaðým ne iþe yaradýðýna //}).AddJwtBearer("CustomSchema", jwtBearerOptions => //{ // jwtBearerOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() // { // //bu bilgiler token ile gelecek her requestte kontrol edilecek // ValidateAudience = true, //dinleyiciyi doðrula tokený gönderen doðrumu ayarlardaki ile // ValidateIssuer = true, //token içinde gelen issuer bilgisini valide et ayarlardaki ile aynýmý // ValidateLifetime = true,//token expirationý kontrol et // ValidateIssuerSigningKey = true, // ValidAudience = tokenOptions.Audience,//geçerli dinleyici // ValidIssuer = tokenOptions.Issuer,//geçerli issuer // IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey),//verify signature gerekli tipe dönüþtürülerek token optionsa deðeri atanýr ver validasyon bu keye göre yapýlýr // ClockSkew = TimeSpan.Zero//farklý saat dilimlerinde token ömrünü uzatmak için kullanýlýr // }; //}); #endregion #region Cors services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); #endregion services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserService, UserSerivce>(); services.AddControllers(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region Log Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200/")) { AutoRegisterTemplate = true, }) .CreateLogger(); #endregion services.AddResponseCaching(_ => { _.MaximumBodySize = 100; _.SizeLimit = 100; _.UseCaseSensitivePaths = false; }); services.AddPersistence(Configuration); services.AddRepository(); services.AddServices(); services.AddTokens(); services.AddControllers(); var tokenopts = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtopt => { jwtopt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenopts.Issuer, ValidAudience = tokenopts.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenopts.SecurityKey), ClockSkew = TimeSpan.Zero }; }); Microsoft.OpenApi.Models.OpenApiInfo inf = new Microsoft.OpenApi.Models.OpenApiInfo(); inf.Title = "Authentication API"; inf.Description = "SWAGGER DOCUMENT"; var config = new MapperConfiguration(cfg => { cfg.AddProfile <DomainToResponseProfile>(); }); IMapper mapper = config.CreateMapper(); services.AddSingleton(mapper); services.AddSwaggerGen(c => { c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.OperationFilter <SecurityRequirementsOperationFilter>(); c.SwaggerDoc("v1", inf); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddDbContext <TokenApiDBContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); services.AddScoped(typeof(IBaseService <>), typeof(BaseService <>)); services.AddScoped(typeof(IRepository <>), typeof(BaseRepository <>)); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IProductService, ProductService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); //services.AddScoped<ProductRepository>(); //automapper service services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); #region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("CoreApi", new OpenApiInfo { Title = "APINation", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Name = "Authorization", Type = SecuritySchemeType.ApiKey, Scheme = "Bearer", BearerFormat = "JWT", In = ParameterLocation.Header, Description = "JWT Authorization header using the Bearer scheme." }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] {} } }); }); #endregion #region CORS services.AddCors(c => { c.AddDefaultPolicy(builder => { builder.WithOrigins("https://localhost:44304") .AllowAnyMethod() .AllowAnyHeader(); }); } ); #endregion #region JWT services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); //dependency injection ile service containerına bu sınıf eklenerek uygulamanın heryerinden ctor injectipn yaparak TokenOptions değerlerine ulaşılabilecek. var issuer = Configuration["TokenOptions:Issuer"]; //ile appsettings.json içeriğine ulaşılabilir var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { //bu bilgiler token ile gelecek her requestte kontrol edilecek ValidateAudience = true, //dinleyiciyi doğrula tokenı gönderen doğrumu ayarlardaki ile ValidateIssuer = true, //token içinde gelen issuer bilgisini valide et ayarlardaki ile aynımı ValidateLifetime = true, //token expiretionı kontrol et ValidateIssuerSigningKey = true, ValidAudience = tokenOptions.Audience, //geçerli dinleyici ValidIssuer = tokenOptions.Issuer, //geçerli issuer IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), //verify signature gerekli tipe dönüştürülerek token optionsa değeri atanır ver validasyon bu keye göre yapılır ClockSkew = TimeSpan.Zero //farklı saat dilimlerinde token ömrünü uzatmak için kullanılır }; }); //c.AddPolicy("FrontEnd", builder => // builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); //c.AddPolicy("FrontEnd", builder => // builder.WithOrigins("https://www.abc.com").AllowAnyMethod().AllowAnyHeader() //); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromSeconds(10); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddAutoMapper(typeof(Startup)); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped(typeof(IRepository <>), typeof(Repository <>)); services.AddScoped(typeof(IService <>), typeof(Service <>)); services.AddScoped <IPostService, PostService>(); services.AddScoped <ILikeService, LikeService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <ICommentService, CommentService>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddDbContext <AppDbContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:SqlConStr"].ToString(), o => { o.MigrationsAssembly("HelpingHandProject.Data"); }); }); services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, builder => { builder.WithOrigins("http://localhost:3000").AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddControllers(); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareoptions => { jwtbeareoptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, //token dinleyicisini doðrula ValidateIssuer = true, //yayýnlayaný doðrula ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); services.AddDirectoryBrowser(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(_ => _.SwaggerDoc("docname", new Info { Title = "Doc Title", Version = "v1" })); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title = "AracTakip API", Version = "v1" }); options.DocInclusionPredicate((docName, description) => true); }); services.AddMvc(); //services.AddSwaggerGen(swagger => //{ // swagger.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "My First Swagger" }); //}); //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //services.AddSwaggerGen( //{ // c.SwaggerDoc("v1", new Info { Title = "MyTestService", Version = "v1" }); //}); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserService, UserService>(); services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddDbContext <AppIdentityDbContext>(opts => { opts.UseSqlServer("Data Source=.;Initial Catalog=True;Persist Security Info=True; User ID=sa; Password=ea3981"); }); services.AddIdentity <Users, Roles>(opts => { opts.User.RequireUniqueEmail = true; opts.User.AllowedUserNameCharacters = "ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZQWXabcçdefgğhıijklmnoöprsştuüvyzqwx0123456789.-_"; opts.Password.RequiredLength = 6; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequireLowercase = false; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequireUppercase = false; opts.Password.RequireDigit = false; }).AddEntityFrameworkStores <AppIdentityDbContext>(); services.Configure <CustomTokenOptions>(Configuration.GetSection("TokenOptions")); var TokenOptions = Configuration.GetSection("TokenOptions").Get <CustomTokenOptions>(); services.AddAuthentication(opts => { opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; } ).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = TokenOptions.Issuer, ValidAudience = TokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(TokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddMvc(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserService, UserService>(); //disaridan her istegi aciyoruz services.AddCors(opt => { opt.AddDefaultPolicy(builder => { //AllowAnyMethod get,post gibi tum metodlari kabul et //AllowAnyOrigin backend tarafindan her yerden istek yapilmasina izin veriyor builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddControllers() // sonuclar json formatinda gozukecektir .AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = true; options.JsonSerializerOptions.WriteIndented = true; }); services.AddHealthChecks(); var connectionString = Configuration["ConnectionString:DBConnectionString"]; services.AddDbContext <ApplicationDbContext>(o => o.UseSqlServer(connectionString)); services.AddIdentity <ApplicationUser, ApplicationRole>(opt => { opt.User.RequireUniqueEmail = true; opt.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz0123456789._-"; opt.Password.RequiredLength = 4; opt.Password.RequireNonAlphanumeric = false; opt.Password.RequireUppercase = false; opt.Password.RequireLowercase = false; opt.Password.RequireDigit = false; }).AddEntityFrameworkStores <ApplicationDbContext>(); services.Configure <CustomTokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <CustomTokenOptions>(); //package manager : Microsoft.AspNetCore.Authentication.JwtBearer indirilmeli services.AddAuthentication(opt => { opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; //üyelik sistemi ile tokený birbirine baðlayan ortak bir þema belirtmemizi saðlýyor //üyeler ve bayiler olarak iki üye giriþi olduðunda birbirini ayýrt etmek için scheme yý kullanýyoruz. }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions => { //token schemasý ile uygulamanýn semasý ayný olmasý için bir üsteki kodda ayný þeymayý belirtiyorum jwtBearerOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecuntyKey), //uygun bir token olup olmadýgýnýn kontrolünü yapýyor ClockSkew = TimeSpan.Zero }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped(typeof(IGenericRepository <>), (typeof(GenericRepository <>))); services.AddScoped(typeof(IGenericService <>), (typeof(GenericService <>))); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <ITokenHandler, TokenHandler>(); //-------------------------------------------------------------------------- services.AddScoped <IUserService, UserServices>(); services.AddScoped <IUserRepository, UserRepository>(); //------------------------------------------------------------------------- //services.AddScoped<IProductService, ProductServices>(); //services.AddScoped<IProductRepository, ProductRepository>(); //-------------------------------------------------------------------------- services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); opts.AddPolicy("zudunyaPolicy", builder => { // artýk api uygulamasý sadece aþþagýdaki orjinden gelen tüm isteklere cevap verecek //ilerde baþka orjinlerde eklene bilir builder.WithOrigins("http://wwww.zudunya.com").AllowAnyHeader().AllowAnyMethod(); }); }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddControllers(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddDbContext <UdemyApiWithTokenDBContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddDefaultAWSOptions(Configuration.GetAWSOptions()); services.AddLogging(); services.AddSingleton <IAwsS3HelperService, AwsS3HelperService>(); services.Configure <AwsS3BucketOptions>(Configuration.GetSection(nameof(AwsS3BucketOptions))) .AddSingleton(x => x.GetRequiredService <IOptions <AwsS3BucketOptions> >().Value); services.AddHttpContextAccessor(); //services.AddScoped<IGeocoder, Address>(); //services.AddCors(opts => //{ // opts.AddDefaultPolicy(builder => // { // builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); // }); //}); services.AddCors(options => { options.AddPolicy("testPolicy", builder => { builder.WithOrigins("http://localhost:53607", "https://cp7u0uz8r9.execute-api.eu-west-2.amazonaws.com/Prod", "http://localhost:53583", "http://geo.tezmaksan.net").AllowAnyMethod().AllowAnyHeader(); }); }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); //services.AddCors(options => //{ // options.AddPolicy("testPolicy", builder => // { // builder.WithOrigins("http://localhost:53607", "https://cp7u0uz8r9.execute-api.eu-west-2.amazonaws.com/Prod", "http://localhost:53583").AllowAnyHeader().AllowAnyMethod(); // }); //}); //services.AddCors(options => // options.AddPolicy("testPolicy", builder => // { // builder // .AllowAnyHeader() // .AllowAnyMethod() // .WithOrigins("http://localhost:53607", "https://cp7u0uz8r9.execute-api.eu-west-2.amazonaws.com/Prod", "http://localhost:53583") // .AllowCredentials() // .SetIsOriginAllowed((host) => true); // })); //services.AddCors(options => //{ // options.AddPolicy("testPolicy", builder => // { // builder.WithOrigins("http://localhost:53607", "https://cp7u0uz8r9.execute-api.eu-west-2.amazonaws.com/Prod").AllowAnyMethod().AllowAnyHeader(); // }); //}); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //services.AddCors(opts => //{ // opts.AddDefaultPolicy( // builder => // { // builder.WithOrigins("http://localhost:53607", // "https://cp7u0uz8r9.execute-api.eu-west-2.amazonaws.com/Prod"); // }); //}); services.AddDbContext <LocationDBContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); services.AddControllers(); // Add S3 to the ASP.NET Core dependency injection framework. services.AddAWSService <Amazon.S3.IAmazonS3>(); }
public void ConfigureServices(IServiceCollection services) { var tokenOptions = Configuration.GetSection("TokenOptions").Get <JwtTokenOptionsDto>(); if (tokenOptions != null) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, // Token gönderen kişi doğrula. App dosyası içindeki Audience bilgisini ValidateIssuer = true, // Token gönderen kişi doğrula. App dosyası içindeki Issuer bilgisini ValidateLifetime = true, // Token ömrünü kontrol et ediyoruz. ValidateIssuerSigningKey = true, // Token app setting içindeki security key ile mi imzalanmış onu kontrol eder ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), // Gelen token bizim security key'imiz ile işaretlenmiş mi onun kontrolünü sağladık ClockSkew = TimeSpan.Zero // Uygulamanın atılan sunucular arasındaki zaman farkını gidermek için verilir tanımlanan değer kadar mevcut token süresine ekler }; }); } services.AddMvc(); services.AddRazorPages(); services.AddDbContext <QuizContext>(contextOptions => contextOptions .UseSqlServer(Configuration.GetConnectionString("QuizContextConString"))); services.AddScoped <IQuizService, QuizManager>(); services.AddScoped <IQuizDal, QuizDal>(); services.AddScoped <IUserDal, UserDal>(); services.AddScoped <IUserService, UserManager>(); services.AddScoped <IToken, Token>(); services.AddScoped <IUnitOfWork, BaseUnitOfWork>(); services.AddScoped <IAuthenticationService, AuthenticationManager>(); services.AddScoped <QuizContext>(); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new QuizMapper()); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); /* * Tüm isteklere cevap vermesi için gerekli Cors tanımı. */ services.AddCors(option => option.AddDefaultPolicy (builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod())); #region Cors servis tanım 2 /* * Sadece wwww.evrenaktas.com'dan gelen isteklere cevap vermesi için gerekli Cors tanımı */ //services.AddCors(option => option.AddPolicy("Policy", // builder => // { // builder.WithOrigins("http://wwww.evrenaktas.com") // .AllowAnyHeader().AllowAnyOrigin(); // })); #endregion services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Quiz Web Api", Version = "1.0.0", Description = "Try Swagger on (ASP.NET Core 3.1)", Contact = new OpenApiContact { Name = "Swagger Implementation Evren Aktaş", Url = new Uri("http://evrenaktas.com"), Email = "*****@*****.**" }, TermsOfService = new Uri("http://swagger.io/terms/") }); }); services.Configure <JwtTokenOptionsDto>(Configuration.GetSection("TokenOptions")); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IKategoriRepository, KategoriRepository>(); services.AddScoped <IKategoriService, KategoriService>(); services.AddScoped <ISiparisRepository, SiparisRepository>(); services.AddScoped <ISiparisService, SiparisService>(); services.AddScoped <IUrunService, UrunService>(); services.AddScoped <IUrunRepository, UrunRepository>(); services.AddScoped <ISiparisDetayRepository, SiparisDetayRepository>(); services.AddScoped <ISiparisDetayService, SiparisDetayService>(); services.AddScoped <IBayiRepository, BayiRepository>(); services.AddScoped <IBayiService, BayiService>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddDbContext <ToptanciCRMContext>(options => { options.UseSqlServer(Configuration["ConnecitonStrings:DefaultConnectionString"]); }); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //services.AddSwaggerGen(options => { // options.SwaggerDoc("ToptanciApi", // new Microsoft.OpenApi.Models.OpenApiInfo() // { // Title = "Toptanci Api", // Version = "1" // }); /// }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); var server = Configuration["DBServer"] ?? "mssqldb"; var port = Configuration["DBPort"] ?? "1433"; var user = Configuration["DBUser"] ?? "SA"; var password = Configuration["DBPassword"] ?? "Hd!1234!!"; var database = Configuration["database"] ?? "Altamira"; services.AddDbContext <AltamiraContext>(options => { //options.UseLazyLoadingProxies().UseSqlServer(Configuration["ConnectionString:DefaultConnectionString"]); //options.UseLazyLoadingProxies().UseSqlServer($"Server={server},{port};Initial Catalog={database};User ID={user};Password={password}"); options.UseLazyLoadingProxies().UseSqlServer("Server=mssqldb,1433;Initial Catalog=Altamira;User ID=SA;Password=Altamira1111!!"); //options.UseLazyLoadingProxies().UseSqlServer("Server=localhost,1433;Initial Catalog=Altamira;User ID=SA;Password=Hd!1234!!"); }); services.AddControllersWithViews() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddScoped(typeof(IGenericService <>), typeof(GenericService <>)); services.AddScoped <IUserManagerService, UserService>(); services.AddScoped <IUserManagerRepository, UserManagerRepository>(); services.AddScoped <ITokenHandler, TokenHandler>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); //services.AddSingleton<RedisService>(); services.AddSingleton <RedisServer>(); services.AddSingleton <ICacheService, RedisCacheService>(); //AddScoped = her request //AddSingleton = ugulama ayaða kalktýðýnda bir tane nesne örneði alýr //services.AddScoped < IUnitOfWork, typeof(UnitOfWork<>) > (); services.AddScoped(typeof(IUnitOfWork <>), typeof(UnitOfWork <>)); // Auto Mapper Configurations var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new UserManagerMapping()); mc.AddProfile(new UserMapping()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); services.AddCors(opts => { opts.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); }); services.Configure <TokenOptions>(Configuration.GetSection("TokenOptions")); var tokenOptions = Configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtbeareroptions => { jwtbeareroptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, IssuerSigningKey = SignHandler.GetSecurityKey(tokenOptions.SecurityKey), ClockSkew = TimeSpan.Zero }; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Altamira Task 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.AddScoped <IDbInitializer, DbInitializer>(); }