Thursday, 25 July 2019

JWT token generator

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Humana.Hcs.Ecom.Services.IdentityProvider.Configurations;
using Humana.Hcs.Ecom.Services.IdentityProvider.Models;
using Humana.Hcs.Ecom.Services.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Humana.Hcs.Ecom.Services.IdentityProvider.Constants;
using Humana.Hcs.Ecom.Services.IdentityProvider.Interfaces;
using Microsoft.AspNetCore.Http;

namespace Humana.Hcs.Ecom.Services.IdentityProvider.Controllers
{
    /// <summary>
    /// Identity Provider Controller
    /// </summary>
    [Route("ECOM/IdentityProvider")]
    [ApiController]
    public class IdentityProviderController : ControllerBase
    {
        private readonly IJwtHelper _jwtHelper;

        /// <summary>
        /// IdentityProviderController construtor
        /// </summary>
        /// <param name="jwtHelper"></param>
        public IdentityProviderController(IJwtHelper jwtHelper )
        {
            this._jwtHelper = jwtHelper;
        }



        /// <summary>
        /// To Get JWT Token for given User Login detail
        /// </summary>
        /// <param name="loginRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Login")]
        [ProducesResponseType(typeof(JwtResponse), 200)]
        [ProducesResponseType(typeof(ErrorMessage), 400)]
        [ProducesResponseType(typeof(ErrorMessage), 401)] // Unauthorized
        [ProducesResponseType(typeof(ErrorMessage), 403)] // Forbidden
        [ProducesResponseType(typeof(ErrorMessage), 404)] // At least one of the criteria passed was not found.Error array will give error for each failed     
        [ProducesResponseType(typeof(ErrorMessage), 406)] // Not Acceptable
        [ProducesResponseType(typeof(ErrorMessage), 429)] // Too many request
        [ProducesResponseType(typeof(ErrorMessage), 500)] // Internal server Error
        [ProducesResponseType(typeof(ErrorMessage), 503)] // Service Unavailable 
        public ActionResult GetToken(Login loginRequest)
        {
            if (loginRequest == null)
            {
                throw new ArgumentNullException(nameof(loginRequest));
            }

            JwtResponse jwtResponse = new JwtResponse();
            LoginSettings loginSettings = ConfigurationInitializer.GetUserLoginSetting(loginRequest.clientId);
            if (loginSettings == null)
                return StatusCode(401, ConfigConstants.GetHttpMessageModel(401));

            if (loginRequest.APIC_ClientId == loginSettings.APIC_ClientId && loginRequest.APIC_ClientSecret == loginSettings.APIC_ClientSecret)
            {
                List<Claim> claims = null;
                claims = new List<Claim>();
                var expiresDate = DateTime.UtcNow.AddMinutes(Convert.ToInt32(loginSettings.ExpiresInMinutes));
                var startingDate = DateTime.UtcNow;
                var createdAt = DateTime.UtcNow;
                claims.Add(new Claim(IdentityProviderConstants.ClaimName, createdAt.ToString()));

                var jwt = new JwtSecurityToken(
                    issuer: loginSettings.Issuer.ToString(),
                    audience: loginSettings.Audience.ToString(),
                    claims: claims,
                    notBefore: startingDate,
                    expires: expiresDate,
                    signingCredentials: new SigningCredentials(
                        new SymmetricSecurityKey(
                            Encoding.ASCII.GetBytes(loginSettings.clientSecret.ToString())),
                            SecurityAlgorithms.HmacSha256
                        )
                     );

                jwtResponse.Bearer = new JwtSecurityTokenHandler().WriteToken(jwt);
                return Ok(jwtResponse);
            }
            else
            {
                return StatusCode(401, ConfigConstants.GetHttpMessageModel(401));
            }
        }
        


        /// <summary>
        /// To Authorize JWT Token 
        /// </summary>
        /// <param name="loginRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Authorize")]
        [ProducesResponseType(typeof(ErrorMessage), 200)]
        [ProducesResponseType(typeof(ErrorMessage), 400)]
        [ProducesResponseType(typeof(ErrorMessage), 401)] // Unauthorized
        [ProducesResponseType(typeof(ErrorMessage), 403)] // Forbidden
        [ProducesResponseType(typeof(ErrorMessage), 404)] // At least one of the criteria passed was not found.Error array will give error for each failed     
        [ProducesResponseType(typeof(ErrorMessage), 406)] // Not Acceptable
        [ProducesResponseType(typeof(ErrorMessage), 429)] // Too many request
        [ProducesResponseType(typeof(ErrorMessage), 500)] // Internal server Error
        [ProducesResponseType(typeof(ErrorMessage), 503)] // Service Unavailable 
        public ActionResult Authorize(AuthorizeModel loginRequest)
        {
            if (loginRequest == null)
            {
                throw new ArgumentNullException(nameof(loginRequest));
            }

            JwtResponse jwtResponse = new JwtResponse();
            LoginSettings loginSettings = ConfigurationInitializer.GetUserLoginSetting(loginRequest.clientId);
            if (loginSettings == null)
                return StatusCode(401, ConfigConstants.GetHttpMessageModel(401));

            if (loginRequest.APIC_ClientId == loginSettings.APIC_ClientId && loginRequest.APIC_ClientSecret == loginSettings.APIC_ClientSecret)
            {
                if (_jwtHelper.ValidateToken(loginRequest.Bearer, loginSettings))
                {
                    return Ok(new ErrorMessage { httpCode = StatusCodes.Status200OK.ToString() , httpMessage = IdentityProviderConstants.HttpMessage200, moreInformation = IdentityProviderConstants.MoreInformation200 });
                }
                else
                {
                    return StatusCode(401, ConfigConstants.GetHttpMessageModel(401));
                }               
            }
            else
            {
                return StatusCode(401, ConfigConstants.GetHttpMessageModel(401));
            }
        }
    }
}


===============================


using Humana.Hcs.Ecom.Services.IdentityProvider.Configurations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;
using Humana.Hcs.Ecom.Services.IdentityProvider.Swagger;
using Humana.Hcs.Ecom.Services.IdentityProvider.Models;
using Humana.Hcs.Ecom.Services.Utility;
using Humana.Hcs.Ecom.Services.IdentityProvider.Interfaces;
using Humana.Hcs.Ecom.Services.IdentityProvider.Helpers;

namespace Humana.Hcs.Ecom.Services.IdentityProvider
{
    /// <summary>
    /// Startup Class
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// Configuration
        /// </summary>
        public IConfiguration Configuration { get; set; }

        /// <summary>
        /// Constructor of Startup
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="env"></param>
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddEnvironmentVariables();

            builder.AddUserSecrets<Startup>();

            Configuration = builder.Build();
            ConfigurationInitializer.Initialiation(Configuration);
        }

        /// <summary>
        /// Configure Services
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<Secrets.Rootobject>(Configuration.GetSection("IdentityProvider"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            services.AddTransient<IJwtHelper, JwtHelper>();
   
            // Reference for Audit Log Utility - Begin
            services.AddTransient<IAuditLogRepository, AuditLogRepository>();
            services.AddTransient<IDaoBase, DaoBase>();
            services.Configure<ConfigurationSetting>(options => Configuration.GetSection("AuditLog").Bind(options));
            // Reference for Audit Log Utility - End

            var swaggerConfig = ConfigurationInitializer.SwaggerConfiguration;
            if (swaggerConfig.Enabled)
            {
                services.AddSwagger(swaggerConfig);
            }
        }

        /// <summary>
        ///  This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseDeveloperExceptionPage();
            app.UseHttpsRedirection();

            // Reference for Audit Log Utility - Begin
            app.UseMiddleware(typeof(AuditLogMiddleware));
            app.UseMiddleware(typeof(ErrorHandlerMiddleware));
            // Reference for Audit Log Utility - End

            app.UseMvc();

            //Use Swagger
            var swaggerConfig = ConfigurationInitializer.SwaggerConfiguration;
            if (swaggerConfig.Enabled)
            {
                app.UseSwagger(swaggerConfig);
            }

            //Added for clickjacking checkmarx issue
            app.Use(async (context, next) =>
            {
                context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
                await next();
            });
        }
    }
}


======================


using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using System.Diagnostics.CodeAnalysis;

namespace Humana.Hcs.Ecom.Services.IdentityProvider
{
    /// <summary>
    /// Program class
    /// </summary>
    [ExcludeFromCodeCoverage] 
    public static class Program
    {
        /// <summary>
        /// main Method
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        /// <summary>
        /// Create web Host
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

=================================

using Humana.Hcs.Ecom.Services.IdentityProvider.Constants;
using Humana.Hcs.Ecom.Services.IdentityProvider.Interfaces;
using Humana.Hcs.Ecom.Services.IdentityProvider.Models;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;

namespace Humana.Hcs.Ecom.Services.IdentityProvider.Helpers
{
    /// <summary>
    /// JWT Helper class
    /// </summary>
    public class JwtHelper : IJwtHelper
    {
        /// <summary>
        /// To Validate JWT Token for given Service Login setting
        /// </summary>
        /// <param name="request"></param>
        /// <param name="loginSettings"></param>
        /// <returns></returns>
        public bool ValidateToken(string request, LoginSettings loginSettings)
        {
            if (!request.ToLowerInvariant().StartsWith(IdentityProviderConstants.JwtPrefix.ToLower()))
            {
                return false;
            }

            var authorization = request.Split(' ');
            var bearerToken = authorization.Length > 1 ? authorization[1] : string.Empty;
            var signingKey =
                      new SymmetricSecurityKey(
                          Encoding.ASCII.GetBytes(loginSettings.clientSecret));

            var tokenValidationParameters = new TokenValidationParameters
            {

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                ValidateIssuer = true,
                ValidIssuer = loginSettings.Issuer,

                ValidateAudience = true,
                ValidAudience = loginSettings.Audience,

                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
            };

            try
            {
                var principal = new JwtSecurityTokenHandler().ValidateToken(bearerToken, tokenValidationParameters, out _);
                return principal.Claims.Any();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }
    }
}