Exemplo n.º 1
0
        private async Task <string> GenerateJwtMobileToken(DeliveryAccount account)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, account.MobileUserId),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, account.Id),
                new Claim(CustomClaimType.CourtId, account.CourtId.ToString()),
                new Claim(CustomClaimType.LawUnitId, account.LawUnitId.ToString()),
            };

            // var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtMobileKey"]));
            //  var creds = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256); // .EcdsaSha512); // HmacSha256);
            string privateKey = configuration["JwtMobileKey"];
            ECDsa  eCDsa      = EDCsaHelper.LoadPrivateKey(EDCsaHelper.FromHexString(privateKey));
            var    key        = new ECDsaSecurityKey(eCDsa);
            var    creds      = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha512); // .EcdsaSha512); // HmacSha256);
            var    expires    = DateTime.Now.AddDays(Convert.ToDouble(configuration["JwtMobileExpireDays"]));

            var token = new JwtSecurityToken(
                configuration["JwtMobileIssuer"],
                configuration["JwtMobileIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // За добавяне на контексти, използвайте extension метода!!!
            services.AddAppDbContext(Configuration);

            #region Identity
            services.AddIdentity <ApplicationUser, ApplicationRole>(options =>
                                                                    { options.User.RequireUniqueEmail = false; }
                                                                    )
            .AddUserStore <ApplicationUserStore>()
            .AddRoleStore <RoleStore <ApplicationRole, ApplicationDbContext, string, ApplicationUserRole, ApplicationRoleClaim> >()
            .AddDefaultTokenProviders();

            // ===== Add Jwt Authentication ========
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); //  => remove default claims
            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration["JwtIssuer"],
                    ValidAudience    = Configuration["JwtIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire,
                };
                //cfg.Events = new JwtBearerEvents()
                //{
                //    OnAuthenticationFailed = c =>
                //    {
                //        c.NoResult();

                //        c.Response.StatusCode = 401;
                //        c.Response.ContentType = "text/plain";

                //        return null;
                //    }

                //};
            });

            string privateKey = Configuration["JwtMobileKey"];
            ECDsa  eCDsa      = EDCsaHelper.LoadPrivateKey(EDCsaHelper.FromHexString(privateKey));
            var    key        = new ECDsaSecurityKey(eCDsa);

            services
            .AddAuthentication(options => {
                options.DefaultAuthenticateScheme = "MobileBearer";   //JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer("MobileBearer", cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.IncludeErrorDetails       = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration["JwtMobileIssuer"],
                    ValidAudience    = Configuration["JwtMobileIssuer"],
                    IssuerSigningKey = key,          // new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtMobileKey"])),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                };
            });
            services.AddCors();
            #endregion Identity
            // За добавяне на услуги, използвайте extension метода!!!
            services.AddApplicationServices();

            services.AddMvc();
            #region IdentityServer
            //services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            //    .AddIdentityServerAuthentication(options =>
            //    {
            //        options.Authority = Configuration.GetValue<string>("OpenIdConnect:Authority");
            //        options.RequireHttpsMetadata = false;
            //        options.ApiName = Configuration.GetValue<string>("OpenIdConnect:ApiName");
            //    });
            #endregion IdentityServer
            services.AddLogging(logging =>
            {
                logging.AddConsole();
                logging.AddDebug();
            });

            services.AddSwaggerDocument(conf =>
            {
                conf.PostProcess = document =>
                {
                    document.Info.Title       = Configuration.GetValue <string>("SwaggerUI:Title");
                    document.Info.Description = Configuration.GetValue <string>("SwaggerUI:Description");
                    document.Info.Version     = Configuration.GetValue <string>("SwaggerUI:Version");
                    document.Schemes          = new List <SwaggerSchema>()
                    {
                        SwaggerSchema.Http, SwaggerSchema.Https
                    };
                    document.SecurityDefinitions.Add("apikey", new SwaggerSecurityScheme
                    {
                        Type = SwaggerSecuritySchemeType.ApiKey,
                        Name = "Authorization",
                        In   = SwaggerSecurityApiKeyLocation.Header
                    });
                };
            });
        }