示例#1
0
        public void D()
        {
            byte[] certPrivateKeyData = null;
            var    assembly           = Assembly.GetExecutingAssembly();

            using (MemoryStream memoryStream = new MemoryStream())
            {
                assembly.GetManifestResourceStream("Celsus.Client.Admin.Resources.EbdysCert.pfx").CopyTo(memoryStream);
                certPrivateKeyData = memoryStream.ToArray();
            }

            Celsus.Types.NonDatabase.LicenseData license = new Celsus.Types.NonDatabase.LicenseData();
            license.CreatedBy         = CreatedBy.Text;
            license.CreatedDate       = CreatedDate.SelectedDate.Value;
            license.Customer          = Customer.Text;
            license.Description       = Description.Text;
            license.ExpireDate        = ExpireDate.SelectedDate.Value;
            license.Id                = new Guid(Id.Text);
            license.IsTrial           = IsTrial.IsChecked.GetValueOrDefault();
            license.ServerId          = ServerId.Text;
            license.LicenseProperties = new List <Celsus.Types.NonDatabase.LicenseProperty>();
            AddProperty(license, LicencePropertiesKey1, LicencePropertiesValue1);
            AddProperty(license, LicencePropertiesKey2, LicencePropertiesValue2);
            AddProperty(license, LicencePropertiesKey3, LicencePropertiesValue3);
            AddProperty(license, LicencePropertiesKey4, LicencePropertiesValue4);
            AddProperty(license, LicencePropertiesKey5, LicencePropertiesValue5);
            var serial = SignHandler.GenerateSignedSerial(license, certPrivateKeyData);

            Clipboard.SetText(serial);
            MessageBox.Show(serial);
        }
示例#2
0
        // 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"]);
            });
        }
示例#3
0
 /// <summary>
 /// Initializes a new instance of the KeyedSignatureProvider class.
 /// </summary>
 /// <param name="signHandler">The signature handler.</param>
 /// <param name="secret">The secret.</param>
 /// <param name="name">The signature algorithm name.</param>
 public KeyedSignatureProvider(SignHandler signHandler, byte[] secret, string name)
 {
     secretBytes = secret;
     Name        = name;
     sign        = signHandler;
     CanSign     = true;
 }
示例#4
0
 /// <summary>
 /// Initializes a new instance of the KeyedSignatureProvider class.
 /// </summary>
 /// <param name="signHandler">The signature handler.</param>
 /// <param name="secret">The secret.</param>
 /// <param name="name">The signature algorithm name.</param>
 public KeyedSignatureProvider(SignHandler signHandler, string secret, string name)
 {
     secretBytes = Encoding.ASCII.GetBytes(secret);
     Name        = name;
     sign        = signHandler;
     CanSign     = true;
 }
示例#5
0
        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()
            });
        }
示例#6
0
        // 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);
            });
        }
示例#7
0
        // 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"]);
            });
        }
示例#8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Session.Remove("errorText");
            string result = Request["result"];

            if (result != null && result.Length % 4 == 0)
            {
                result = SignHandler.Base64Decode(result);
            }
            if (result != null && "ok" == result.ToLower())
            {
                var loginData              = Request["signature"];
                var textToBeSigned         = (string)Session["signText"];
                var signTextTransformation = (string)Session["signTransformation"];
                var logonto        = ConfigurationManager.AppSettings["logonto"];
                var signTextFormat = (String)Session["signTextFormat"];

                if (logonto == null || "".Equals(logonto.Trim()))
                {
                    throw new ConfigurationErrorsException("Fejl: Logonto / friendlyname mangler, eller er tom i konfigurationen");
                }



                SignatureValidationStatus status = null;
                if ("pdf".Equals(signTextFormat))
                {
                    status = SignHandler.validateSignatureAgainstAgreementPDF(loginData, textToBeSigned, Challenge(), logonto);
                }
                else
                {
                    status = SignHandler.ValidateSignatureAgainstAgreement(loginData, textToBeSigned, signTextTransformation, Challenge(), logonto);
                }

                if (!(status.Certificate is MocesCertificate))
                {
                    Session.Add("errorText", "Det benyttede certifikat er ikke af korrekt type. Forventede medarbejdercertifikat, fik " + ErrorHandler.CertificateType(status));
                }
                else if (status.CertificateStatus != CertificateStatus.Valid)
                {
                    Session.Add("errorText", "Certifikatet er " + ErrorHandler.GetCertificateStatusText(status.CertificateStatus));
                }
                else if (status.SignatureMatches)
                {
                    Response.Redirect("signeringskvittering.aspx");
                }
                else
                {
                    Session.Add("errorText", "Signaturen matcher ikke teksten '" + textToBeSigned + "'.");
                }
            }
            else
            {
                Session.Add("errorText", ErrorHandler.GetErrorText(String.IsNullOrEmpty(result) ? "cancelsign" : result));
            }
        }
示例#9
0
        // 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"]);
            });
        }
示例#10
0
        // 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();
        }
示例#11
0
        // 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);
        }
示例#12
0
        public TransitWallet(string privateKey, LyraRestClient client)
        {
            _uniqId = Guid.NewGuid().ToString();

            _privateKey = privateKey;
            _accountId  = Signatures.GetAccountIdFromPrivateKey(privateKey);

            _rpcClient = client;

            _signer = (hash) => Signatures.GetSignature(_privateKey, hash, _accountId);
        }
        // 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);
        }
示例#14
0
        // 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)
                };
            });
        }
示例#15
0
        // 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"]);
            });
        }
示例#16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Session.Remove("errorText");
            string result = Request["result"];

            if (result != null && result.Length % 4 == 0)
            {
                result = SignHandler.Base64Decode(result);
            }
            if (result != null && "ok" == result.ToLower())
            {
                var loginData                    = Request["signature"];
                var textToBeSigned               = (string)Session["signText"];
                var signTextTransformation       = (string)Session["signTransformation"];
                var signTextFormat               = (String)Session["signTextFormat"];
                SignatureValidationStatus status = null;
                if ("pdf".Equals(signTextFormat))
                {
                    status = SignHandler.validateSignatureAgainstAgreementPDF(loginData, textToBeSigned, Challenge(), "DanID Test TU");
                }
                else
                {
                    status = SignHandler.ValidateSignatureAgainstAgreement(loginData, textToBeSigned, signTextTransformation, Challenge(), "DanID Test TU");
                }

                if (!(status.Certificate is PocesCertificate))
                {
                    Session.Add("errorText", "Det benyttede certifikat er ikke af korrekt type. Forventede personligt certifikat, fik " + ErrorHandler.CertificateType(status));
                }
                else if (status.CertificateStatus != CertificateStatus.Valid)
                {
                    Session.Add("errorText", "Certifikatet er " + ErrorHandler.GetCertificateStatusText(status.CertificateStatus));
                }
                else if (status.SignatureMatches)
                {
                    Response.Redirect("signeringskvittering.aspx");
                }
                else
                {
                    Session.Add("errorText", "Signaturen matcher ikke teksten '" + textToBeSigned + "'.");
                }
            }
            else
            {
                Session.Add("errorText", ErrorHandler.GetErrorText(String.IsNullOrEmpty(result) ? "cancelsign" : result));
            }
        }
示例#17
0
        // 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"]);
            });
        }
示例#18
0
        // 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);
        }
示例#19
0
        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.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.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")));
        }
示例#22
0
        // 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
                };
            });
        }
示例#23
0
        // 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
                };
            });
        }
    private void PreDestroy()
    {
        //Debug.Log("Destroying the object");

        if (!isQuitting)
        {
            GameObject myObject = GameObject.FindWithTag("GameController");

            if (myObject != null)
            {
                SignHandler signHandler = myObject.GetComponent <SignHandler>();

                if ((signHandler != null))
                {
                    //Debug.Log("Generating new object");
                    signHandler.generateObjectOnTerrain();
                }
            }
        }

        Destroy(gameObject);
    }
        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,
                };
            });
        }
示例#26
0
        // 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
                };
            });
        }
示例#27
0
        // 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);
            });
        }
示例#28
0
        // 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()
            //);
        }
示例#29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var result = Request["result"];

            if (result.Length % 4 == 0)
            {
                result = SignHandler.Base64Decode(result);
            }
            if ("ok" == result.ToLower())
            {
                try
                {
                    String friendlyName = ConfigurationManager.AppSettings.Get("logonto");

                    if (friendlyName == null || "".Equals(friendlyName.Trim()))
                    {
                        throw new ConfigurationException("Fejl: Logonto / friendlyname mangler, eller er tom i konfigurationen");
                    }

                    string signature = SignHandler.Base64Decode(Request["signature"]);
                    CertificateAndStatus certificateAndStatus = LogonHandler.ValidateAndExtractCertificateAndStatus(signature, Challenge(), friendlyName);
                    if (certificateAndStatus.Certificate is PocesCertificate)
                    {
                        CertificateStatus status = certificateAndStatus.CertificateStatus;
                        if (status == CertificateStatus.Valid)
                        {
                            Session.Add(KeyPid, ((PocesCertificate)certificateAndStatus.Certificate).Pid);
                            if (Session[Global.CurrentUser] == null)
                            {
                                var randomUserName = ChallengeGenerator.GenerateChallenge();
                                Session.Add(Global.CurrentUser, randomUserName);
                            }

                            if (!Roles.IsUserInRole((string)Session[Global.CurrentUser], "poces"))
                            {
                                Roles.AddUserToRole((string)Session[Global.CurrentUser], "poces");
                            }
                            FormsAuthentication.RedirectFromLoginPage((string)Session[Global.CurrentUser], false);
                        }
                        else
                        {
                            Session.Add("errorText", "Certifikatet er " + ErrorHandler.GetCertificateStatusText(status));
                        }
                    }
                    else
                    {
                        Session.Add("notPoces", true);
                    }
                }
                catch (NonOcesCertificateException)
                {
                    Session.Add("errorText", "Ikke et OCES-certifikat");
                }
                catch (Exception ex)
                {
                    Session.Add("errorText", "Ukendt server-fejl: " + ex.Message);
                }
            }
            else
            {
                Session.Add("errorText", ErrorHandler.GetErrorText(result));
            }
        }
示例#30
0
        // 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();
        }