Tuesday, January 30, 2018

Get Files from localstorage and download via click



public async Task<string> GetFilesAsync()
        {
            /// when bytearray need to be write to localfile
            //string localfileName = "C:\\logs\\Report.pptx";
            //File.WriteAllBytes(localfileName, byteArray);

/// when read file and convert to memory stream
            MemoryStream ms = new MemoryStream();
            string localfileName = "C:\\logs\\Report.pptx";
            using (FileStream file = new FileStream(localfileName, FileMode.Open, FileAccess.Read))
            {
                file.CopyTo(ms);
            }

            await _azureRepository.SaveFileAsync(ms, "Report_.pptx");

            var result = await _azureRepository.GetFileAsync("Report_.pptx");
/// when on click file need to be downloaded
            if (result != null)
            {
                string fileName = "Report_" + DateTime.Now.ToString("ddmmyyyyhhmmss") + ".pptx";
                HttpContext context = System.Web.HttpContext.Current;
                context.Response.Clear();
                context.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName));
                result.WriteTo(context.Response.OutputStream);
                result.Close();
                context.Response.End();
                return fileName + "downloaded for ";
            }
            return "No File";
        }

ByteArrayConverter

Convert object to  byte array and vice versa,

public static class ByteArrayConverter
    {
        public static byte[] Serialize<T>(T obj) where T : class
        {
            if (obj != null)
            {
                var ser = new XmlSerializer(typeof(T));
                using (var ms = new MemoryStream())
                {
                    ser.Serialize(ms, obj);
                    var bytes = ms.ToArray();
                    return bytes;
                }
            }
            return null;
        }

        public static T Deserilize<T>(byte[] byteArray) where T : class
        {
            if (byteArray != null && byteArray.Length!=0)
            {             
                var ser = new XmlSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream(byteArray))
                {
                    XmlReaderSettings readerSettings = new XmlReaderSettings();
                    readerSettings.IgnoreWhitespace = false;
                    return (T)ser.Deserialize(XmlReader.Create(ms, readerSettings));                   
                }               
            }
            return null;
        }
    }

API Authentication using Azure AD and generating new jwt token using another token

How add Authentication for Azure AD beare token and generate token:

In Web API startup.cs,
private void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                    {
                        Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                        TokenValidationParameters = new TokenValidationParameters
                        {   SaveSigninToken=true,
                            ValidAudience = ConfigurationManager.AppSettings["ida:Audience"] },
                            AuthenticationType = "WebApi"
                    });
        }

Config key:
 <add key="ida:Tenant" value="EYEXTSTG.onmicrosoft.com" />
    <add key="ida:Audience" value="https://EYEXTSTG.onmicrosoft.com/taxtrmdev-app" />


How to generate token for web api using another jwttoken

In Startup.cs,

 app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                SaveToken = true,
                Authority = ConfigurationHelper.AzureAdAuthority(),
                TokenValidationParameters =
                new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = issuer,
                    ValidateAudience = true,
                    ValidAudiences = new string[] { clientId },
                    ValidateLifetime = true,
                    SaveSigninToken=true
                },
                Events = new TRMJwtBearerEvents(loggerFactory.CreateLogger<TRMJwtBearerEvents>())
            });


In UserController class,


  string authorityUrl = ConfigurationHelper.AzureAdAuthority() + ConfigurationHelper.AzureAdTenant();   
        string clientId = ConfigurationHelper.AzureAdClientId();
        string clientSecret = ConfigurationHelper.AzureAdClientSecret();
        string webApiResourceId = ConfigurationHelper.AzureAdWebApiResourceId();
        string graphResourceId = ConfigurationHelper.AzureAdGraphApiResourceId();
        string graphResourceUri = ConfigurationHelper.AzureAdGraphApiResourceUri();

        [HttpGet]
        [Route("GetToken")]
        public async Task<string> GetToken()
        {
            try
            {
                string jwtToken = await GetJWTTokenFromRequest();

                if (string.IsNullOrWhiteSpace(jwtToken))
                    return string.Empty;

                AuthenticationResult authResult = await GetAutheticationResultByResourceId(jwtToken, webApiResourceId);

                if (!string.IsNullOrWhiteSpace(authResult.AccessToken))
                    return authResult.AccessToken;
                else
                    return string.Empty;


            }
            catch (Exception ex)
            {
                //                throw;
                return string.Empty;
            }
        }   

        private async Task<AuthenticationResult> GetAutheticationResultByResourceId(string jwtToken, string apiResourceId)
        {
            try
            {
                UserAssertion userAssertion = new UserAssertion(jwtToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", string.Empty);
                ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
                AuthenticationContext authContext = new AuthenticationContext(authorityUrl, true);
                AuthenticationResult authResult = await authContext.AcquireTokenAsync(apiResourceId, clientCred, userAssertion);
                return authResult;
            }
            catch (Exception ex)
            {

                //throw;
                return null;
            }
        }

        private async Task<string> GetJWTTokenFromRequest()
        {
            var authenticateInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync("Bearer");
            string accessToken = authenticateInfo.Properties.Items[".Token.access_token"];
            string jwtToken = accessToken;
            return jwtToken;
        }
    }