Example #1
0
        /// <summary>
        /// Generates JWT token for a valid user
        /// </summary>
        /// <param name="user"></param>
        /// <returns>The token string</returns>
        private String GetToken(ApplicationUser user, string role)
        {
            var utcNow = FormattableString.Invariant($"{DateTime.UtcNow}");
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, user.Id.ToString()),
                new Claim(ClaimTypes.Role, role)
            };
            var tokenHandler = new JwtSecurityTokenHandler();

            //Keyvault get key
            string encryptionKey = KeyVaultManagement.GetKey("TokenEncryptionKey");
            var    signingKey    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(encryptionKey));


            //For Custom test use this
            //var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.configuration.GetValue<String>("Tokens:Key")));

            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(
                signingCredentials: signingCredentials,
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(5),
                audience: this.configuration.GetValue <String>("Tokens:Audience"),
                issuer: this.configuration.GetValue <String>("Tokens:Issuer")
                );

            return(tokenHandler.WriteToken(jwt));
        }
        public static string Post(System.Uri uri, string stringData, string token = null)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    if (token != null)
                    {
                        string bearerToken = token;
                        bearerToken = $"Bearer {bearerToken}";

                        //KeyVault
                        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", KeyVaultManagement.GetKey("ocpApimSubscriptionKey"));
                        client.DefaultRequestHeaders.Add("GatewayAuthorization", KeyVaultManagement.GetKey("gatewayAuthorization"));

                        //Local
                        //client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Constants.OcpApimSubscriptionKey);
                        //client.DefaultRequestHeaders.Add("GatewayAuthorization", Constants.GatewayAuthorization);

                        client.DefaultRequestHeaders.Add("Authorization", bearerToken);
                    }
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    using (HttpResponseMessage response = client.PostAsJsonAsync(uri, stringData).Result)
                    {
                        response.EnsureSuccessStatusCode();
                        var result = response.Content.ReadAsStringAsync().Result;
                        return(result);
                    }
                }
            }

            catch (WebException wex)
            {
                throw new WebException(wex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Example #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Add CORS
            services.AddCors(options => options.AddPolicy("Cors", builder => {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
            #endregion

            #region Add Entity Framework and Identity Framework

            //For Locally Run
            services.AddDbContext <IDTPDBContext>(options =>
                                                  options.UseSqlServer(Constants.Azuresqldbconnectionstring));

            //For Running With KeyVault
            //services.AddDbContext<IDTPDBContext>(options =>
            //options.UseSqlServer(KeyVaultManagement.GetKey("azuresqldbconnectionstring")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <IDTPDBContext>();

            #endregion

            #region Add Authentication
            //Added JWT based Authentication Middleware.This will validate every API call. API will return
            //“401 Un - Authorized” error if valid authentication token is not provided in the HTTP request header.
            string encryptionKey = KeyVaultManagement.GetKey("TokenEncryptionKey");
            var    signingKey    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(encryptionKey));

            //For local pc use this
            //var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]));

            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(config => {
                config.RequireHttpsMetadata      = false;
                config.SaveToken                 = true;
                config.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = signingKey,
                    ValidateAudience         = true,
                    ValidAudience            = this.Configuration["Tokens:Audience"],
                    ValidateIssuer           = true,
                    ValidIssuer              = this.Configuration["Tokens:Issuer"],
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true
                };
            });
            #endregion

            services.AddControllers().AddNewtonsoftJson();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title   = "IDTP Partner API",
                    Version = "v1"
                });
            });


            services.AddMvc();
            services.AddTransient <IBusinessLayer, BusinessLayer>();
        }