What is Authorization? Authorization verifies whether a user has permission to use specific applications or services. While authentication and authorization are distinct processes, authentication must precede authorization, ensuring the user's identity is confirmed before determining their access rights. When logging into a system, a user must provide credentials like a username and password to authenticate. Next, the authorization process grants rights. For example, an administrative user can create a document library to add, edit, and delete documents, while a non-administrative user can only read documents in the library. Types of Authorization: Simple Authorization Role-Based Authorization Claim-Based Authorization Policy-Based Authorization I have implemented an example of role-based authorization in .NET. Step 1: Create one new MVC Web Application with the Authentication type “Individual Account”. Step 2: Register Identity with DefaultTokenProvider in the program.cs file. builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); For better understanding, I have added one page to add a new role. Create a new method in the controller and add the following code. [HttpGet] public IActionResult Admin() { return View(); } Create a new model Role.cs. namespace Authorization.Models { public class Role { public string RoleName { get; set; } } } Create html page for add role. @model Role @{ ViewData["Title"] = "Admin"; } <h1>Admin</h1> <div class="row"> <div class="col-md-12"> <form method="post" action="@Url.Action("Admin","Home")"> <div class="form-group"> <label>Role Name</label> <input type="text" class="form-control" style="width:30%;" asp-for="RoleName" placeholder="Role name" required> </div> <br /> <button class="btn btn-success" type="submit">Add</button> </form> </div> </div> I have created a simple page, You can modify the page as per your requirements. Add a new method in the controller and add the following code. And declare RoleManager<IdentityRole> and inject in the constructor. private readonly RoleManager<IdentityRole> _roleManager; public HomeController(RoleManager<IdentityRole> roleManager) { _roleManager = roleManager; } [HttpPost] public async Task<IActionResult> Admin(Role role) { var result = _roleManager.RoleExistsAsync(role.RoleName).Result; if (!result) { await _roleManager.CreateAsync(new IdentityRole(role.RoleName)); } return RedirectToAction("Admin"); } Set a new tab in _Layout.cshtml file to redirect to the Add role page. <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Admin">Add new role</a> </li> Run the project and you will see the output. Here, You can add a new role. Add a new field in register.cshtml using the following code to assign a role to the user. <div class="form-floating mb-3"> <select asp-for="Input.Role" class="form-control" aria-required="true"> <option value="">Select role</option> @foreach (var item in Model.RoleList) { <option value="@item.Name">@item.Name</option> } </select> <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span> </div> To get the list of roles you can add the following code in your register.cshtml.cs file. And Add RoleList = _roleManager.Roles in OnPostAsync method also. public IQueryable<IdentityRole> RoleList { get; set; } public async Task OnGetAsync(string returnUrl = null) { ReturnUrl = returnUrl; RoleList = _roleManager.Roles; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } Run the project and see the output. Now, Assign the role to the user, and for that add the following code in OnPostAsync after the user is created. await _userManager.AddToRoleAsync(user, Input.Role); Full code of register.cshtml.cs file. using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using System.ComponentModel.DataAnnotations; using System.Text; namespace Authorization.Areas.Identity.Pages.Account { public class RegisterModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly IUserStore<IdentityUser> _userStore; private readonly IUserEmailStore<IdentityUser> _emailStore; private readonly ILogger<RegisterModel> _logger; //private readonly IEmailSender _emailSender; public RegisterModel( UserManager<IdentityUser> userManager, IUserStore<IdentityUser> userStore, SignInManager<IdentityUser> signInManager, ILogger<RegisterModel> logger, RoleManager<IdentityRole> roleManager ) { _userManager = userManager; _userStore = userStore; _emailStore = GetEmailStore(); _signInManager = signInManager; _roleManager = roleManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public IQueryable<IdentityRole> RoleList { get; set; } public string ReturnUrl { get; set; } public IList<AuthenticationScheme> ExternalLogins { get; set; } public class InputModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [Display(Name = "Role")] public string Role { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public async Task OnGetAsync(string returnUrl = null) { ReturnUrl = returnUrl; RoleList = _roleManager.Roles; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); RoleList = _roleManager.Roles; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = CreateUser(); await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); await _userManager.AddToRoleAsync(user, Input.Role); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }); } else { await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return Page(); } private IdentityUser CreateUser() { try { return Activator.CreateInstance<IdentityUser>(); } catch { throw new InvalidOperationException($"Can't create an instance of '{nameof(IdentityUser)}'. " + $"Ensure that '{nameof(IdentityUser)}' is not an abstract class and has a parameterless constructor, or alternatively " + $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml"); } } private IUserEmailStore<IdentityUser> GetEmailStore() { if (!_userManager.SupportsUserEmail) { throw new NotSupportedException("The default UI requires a user store with email support."); } return (IUserEmailStore<IdentityUser>)_userStore; } } } Now, register one new user and assign a role to them. For example, I have created one user and assign “Admin” to them. I have added two new methods in the controller and added a default view for that. [Authorize(Roles = "User")] public IActionResult UserRoleCheck() { return View(); } [Authorize(Roles = "Admin")] public IActionResult AdminRoleCheck() { return View(); } I have set the Authorize attribute with the role name on both authorization methods. Now, I am running the project and clicking on Admin Role, It will open the page of admin because the logged user role and method role both are the same. If I click on User Role, It will give an Access denied error. Because logged user role and method role both are different. Here, I am using by default access denied page of identity. You can use custom page also, Just set this path to program.cs file. builder.Services.ConfigureApplicationCookie(options => { options.AccessDeniedPath = "/Identity/Account/AccessDenied"; // Customize this path as per your application's structure }); Using this way you will implement the role-based authorization in your application. Conclusion By properly implementing authorization in your applications, you can ensure that resources and sensitive information are accessible only to authorized users. Remember to choose the appropriate authorization technique based on your application’s requirements and complexity.
To utilize custom fonts from your Dotnet codebase in HTML or PDF documents, follow these steps: Add the fonts you intend to use for your PDF or HTML documents. Ensure they are in the .ttf extension format. <PackageReference Include="Polybioz.HtmlRenderer.PdfSharp.Core" Version="1.0.0"> Include the necessary package by adding the following line to your project file: Initialize the IServiceCollection to utilize the CustomFontResolver class. You can achieve this by adding the following extension method: public static class IServicesCollectionExtension { public static IServiceCollection InitializeDocumentProcessor(this IServiceCollection services) { GlobalFontSettings.FontResolver = new CustomFontResolver(); return services; } } Initialize the class in your program file: builder.Services.InitializeDocumentProcessor(); Specify the DefaultFontName you wish to use. You can also manage bold and italic styles. public class CustomFontResolver : IFontResolver { string IFontResolver.DefaultFontName => "Rubik"; public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic) { if (isBold) { if (isItalic) { return new FontResolverInfo("Rubik#bi"); } return new FontResolverInfo("Rubik#b"); } if (isItalic) return new FontResolverInfo("Rubik#i"); return new FontResolverInfo("Rubik"); } public byte[] GetFont(string faceName) { switch (faceName) { case "Rubik": return CustomFontHelper.Rubik; case "Rubik#b": return CustomFontHelper.RubikBold; case "Rubik#bi": return CustomFontHelper.RubikBoldItalic; case "Rubik#i": return CustomFontHelper.RubikItalic; } return GetFont(faceName); } } Define a helper class CustomFontHelper to facilitate loading font data. Ensure you have added the fonts for all the types you intend to use. public static class CustomFontHelper { public static byte[] Rubik { get { return LoadFontData("Rubik-Light.ttf"); } } public static byte[] RubikBold { get { return LoadFontData("Rubik-SemiBold.ttf"); } } public static byte[] RubikBoldItalic { get { return LoadFontData("Rubik-SemiBoldItalic.ttf"); } } public static byte[] RubikItalic { get { return LoadFontData("Rubik-Italic.ttf"); } } static byte[] LoadFontData(string name) { using (Stream stream = File.OpenRead("Fonts/" + name)) { if (stream == null) throw new ArgumentException("No resource with name " + name); int count = (int)stream.Length; byte[] data = new byte[count]; stream.Read(data, 0, count); return data; } } } By following these steps, you can seamlessly integrate custom fonts into your HTML and PDF documents from your Dotnet codebase, without needing to specify the font-family in the HTML directly. You can also pass font styles directly through code.
Introduction: In the realm of modern APIs, the provision of clear and comprehensive documentation plays a pivotal role in facilitating developer adoption and ensuring efficient utilization. Swagger, aligned with the OpenAPI Initiative, stands out as a prominent solution, offering machine-readable documentation and a user-friendly interactive interface. In this guide, we'll delve into the seamless integration of Swagger into your .NET Core API. Step 1: Install the necessary packages Add Swashbuckle.AspNetCore NuGet package to a project: dotnet add package Swashbuckle.AspNetCore Add Swashbuckle.AspNetCore.SwaggerUI NuGet package to a project: dotnet add package Swashbuckle.AspNetCore.SwaggerUI Step 2: Add services in program.cs In the program.cs file, include the following service additions: builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); Additionally, add middleware in program.cs to enable Swagger in the development environment: if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } Step 3: Run the API project and access the Swagger UI at: https://your-api-base-url/swagger Ensure the API project is running, and navigate to the provided URL to explore and interact with the Swagger UI seamlessly. Step 3: Execute the APIs and test.
What is Authentication? Authentication is the process of validating the identity of a user or system attempting to access a protected resource. In C# programming, authentication is commonly implemented in various scenarios, including web applications, desktop applications, and services. Types of Authentications Basic Authentication Password-based Authentication Multi-Factor Authentication Token-based Authentication Let’s understand authentication with example. Here I am taking one example of MFA (Two-factor authentication). Step 1: Create the MVC Web Application Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select ASP.NET Core web app (Model-View-Controller) and press Next and enter project name and click Next. Choose 'Individual Account' as the authentication type and click 'Create' to generate the project. Step 2: Adding QR Codes to configure two-factor authentication We will be using a QR code to configure and sync the Google authenticator app with our web app. Download the qrcode.js JavaScript library from https://davidshimjs.github.io/qrcodejs/ and put it into the “wwwroot\lib” folder in your application. Now, your “wwwroot” folder will have the following structure. Now, Add new scaffolded item in your project by right click on Area folder and select New scaffolded Item under Add section. Select Identity section on left sidebar and click on Add. Now, Select the identity files that you have to add to your project but select file “Account/Manage/EnableAuthenticator” is compulsory for 2FA. Select the DbContext Class of your project and click on add. Open the “Views\Manage\EnableAuthenticator.cshtml” file. You will find @section Scripts at the end of the file. Put the following code in it. @section Scripts { @await Html.PartialAsync("_ValidationScriptsPartial") <script src="~/lib/qrcode/qrcode.js"></script> <script type="text/javascript"> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 }); </script> } Note: Change your script path as per your folder structure. This “EnableAuthenticator.cshtml” file already has a div with the id “qrCode” (see the code snippet below). We are generating a QR code inside that div using the qrcode.js library. We are also defining the dimensions of the QR code in terms of width and height. So finally, your “EnableAuthenticator.cshtml” file will look like this. @page @model EnableAuthenticatorModel @{ ViewData["Title"] = "Configure authenticator app"; ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication; } <partial name="_StatusMessage" for="StatusMessage" /> <h3>@ViewData["Title"]</h3> <div> <p>To use an authenticator app go through the following steps:</p> <ol class="list"> <li> <p> Download a two-factor authenticator app like Microsoft Authenticator for <a href="https://go.microsoft.com/fwlink/?Linkid=825072">Android</a> and <a href="https://go.microsoft.com/fwlink/?Linkid=825073">iOS</a> or Google Authenticator for <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en">Android</a> and <a href="https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8">iOS</a>. </p> </li> <li> <p>Scan the QR Code or enter this key <kbd>@Model.SharedKey</kbd> into your two factor authenticator app. Spaces and casing do not matter.</p> <div class="alert alert-info">Learn how to <a href="https://go.microsoft.com/fwlink/?Linkid=852423">enable QR code generation</a>.</div> <div id="qrCode"></div> <div id="qrCodeData" data-url="@Model.AuthenticatorUri"></div> </li> <li> <p> Once you have scanned the QR code or input the key above, your two factor authentication app will provide you with a unique code. Enter the code in the confirmation box below. </p> <div class="row"> <div class="col-md-6"> <form id="send-code" method="post"> <div class="form-floating mb-3"> <input asp-for="Input.Code" class="form-control" autocomplete="off" placeholder="Please enter the code."/> <label asp-for="Input.Code" class="control-label form-label">Verification Code</label> <span asp-validation-for="Input.Code" class="text-danger"></span> </div> <button type="submit" class="w-100 btn btn-lg btn-primary">Verify</button> <div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div> </form> </div> </div> </li> </ol> </div> @section Scripts { @await Html.PartialAsync("_ValidationScriptsPartial") <script src="~/lib/qrcode/qrcode.js"></script> <script type="text/javascript"> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 }); </script> } When we execute the program, a QR code will be generated in this View. Then you can set up two factor authentication using the Google authenticator with the help of this QR code. Step 3: Configure two-factor authentication Before running the application, we need to apply migrations to our app. Navigate to Tools >> NuGet Package Manager >> Package Manager Console. It will open the Package Manager Console. Put in the “Update-Database” command and hit Enter. This will update the database using Entity Framework Code First Migrations. Run the application and click on “Register” in the top right corner of the homepage. You can see a user registration page. Fill in the details and click on the “Register” button as shown in the image below. Upon successful registration, you will be logged into the application and navigated to the home page. Here, you can see your registered Email id at the top right corner of the page. Click on it to navigate to the “Manage your account” page. Select “TwoFactorAuthentication” from the left menu. You will see a page similar to that shown below. Click on the “Set up authenticator app” button. You can see a QR code generated on your screen — it is asking for a “Verification Code”, also as shown in the image below. You need to install the Google Authenticator/Microsoft Authenticator app on your smartphone. It will allow you to scan this QR code in order to generate a Verification Code and complete a two-factor authentication setup. Open Microsoft Authenticator and click on verified IDs at the bottom. Click on “Scan a barcode” and scan the QR code generated by the web app. This will add a new account to Microsoft authenticator and generate a six-digit pin on your mobile screen. This is our two-factor authentication code. This is a TOTP ( time-based one-time password). You can observe that it keeps on changing frequently (life span of 30 seconds). Put this pin in the Verification Code textbox and click on verify. Upon successful verification, you will see a screen similar to the one shown below. This will give you the recovery codes for your account that will help to recover your account in case you are locked out. Take a note of these codes and keep them somewhere safe. Logout of the application and click on login again. Enter your registered email id and password and click on login. Now you can see a the two-factor authentication screen asking for the Authenticator code. Put in the code that is generated in your Google Authenticator app and click on Login. You will be successfully logged into the application and navigated to the home page.
Simplifying API Responses with AutoWrapper.Core in .NET Core. Handling API responses effectively is a crucial aspect of building robust and user-friendly applications. In .NET Core applications, the AutoWrapper.Core library comes to the rescue, providing a streamlined way to structure and standardize API responses. In this blog post, we'll explore how to use AutoWrapper.Core to create fixed responses for different status codes in your API. Firstly, you'll need to install the AutoWrapper.Core NuGet package. Add the following line to your project's .csproj file: <PackageReference Include="AutoWrapper.Core" Version="4.5.1" /> This package simplifies the process of handling API responses and ensures a consistent format for success, error, and data messages. Example: Login Method Let's consider a common scenario, the login method, where we want to ensure fixed responses for both successful and unsuccessful attempts. [HttpPost("Login")] public async Task<ApiResponse> Login([FromBody] Login model) { var user = await _userService.GetUserByName(model.UserName); if (user != null && await _userService.CheckUserPassword(user, model.Password)) { var userResponse = await _tokenService.GenerateToken(user); return new ApiResponse(message: "Login Successfully.", result: userResponse, statusCode: 200); } return new ApiResponse(message: "Invalid Credential.", result: null, statusCode: 401); } In this example, we're using AutoWrapper.Core's ApiResponse class to encapsulate our responses. For a successful login attempt (status code 200), we return a positive message along with the user response. In case of invalid credentials (status code 401), an appropriate error message is provided. ApiResponse Class Now, let's take a closer look at the ApiResponse class from AutoWrapper.Core: namespace AutoWrapper.Wrappers; public class ApiResponse { public string Version { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int StatusCode { get; set; } public string Message { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? IsError { get; set; } public object ResponseException { get; set; } public object Result { get; set; } [JsonConstructor] public ApiResponse(string message, object result = null, int statusCode = 200, string apiVersion = "1.0.0.0") { StatusCode = statusCode; Message = message; Result = result; Version = apiVersion; } public ApiResponse(object result, int statusCode = 200) { StatusCode = statusCode; Result = result; } public ApiResponse(int statusCode, object apiError) { StatusCode = statusCode; ResponseException = apiError; IsError = true; } public ApiResponse() { } } The ApiResponse class provides flexibility in constructing responses with different components such as the message, result, and status code. It helps maintain a standardized format for all API responses. Create a Custom Wrapper: AutoWrapper allows you to create a custom wrapper by implementing the IApiResponse interface. You can create a class that implements this interface to customize the fixed response. Here's an example: Create a Custom Wrapper: AutoWrapper allows you to create a custom wrapper by implementing the IApiResponse interface. You can create a class that implements this interface to customize the fixed response. Here's an example: using AutoWrapper.Wrappers; public class CustomApiResponse<T> : ApiResponse<T> { public string CustomProperty { get; set; } public CustomApiResponse(T result, string customProperty) : base(result) { CustomProperty = customProperty; } } Configure AutoWrapper: In your Startup.cs file, configure AutoWrapper to use your custom wrapper. You can do this in the ConfigureServices method: services.AddAutoWrapper(config => { config.UseCustomSchema<CustomApiResponse<object>>(); }); Replace CustomApiResponse<object> with the custom wrapper class you created. Use Custom Wrapper in Controller Actions: Now, you can use your custom wrapper in your controller actions. For example: [ApiController] [Route("api/[controller]")] public class MyController : ControllerBase { [HttpGet] public IActionResult Get() { // Your logic here var data = new { Message = "Hello, World!" }; // Use the custom wrapper var response = new CustomApiResponse<object>(data, "CustomProperty"); return Ok(response); } } Customize the CustomApiResponse according to your needs, and use it in your controller actions. This way, you can integrate AutoWrapper with other packages and customize the fixed response format in your .NET application. In conclusion, by incorporating AutoWrapper.Core into your .NET Core applications, you can simplify the handling of API responses, making your code more readable, maintainable, and user-friendly. Consider adopting this approach to enhance the overall developer experience and ensure consistency in your API communication.
To set up the AWS Cognito for the registration/login flow, follow these steps: First Flow: User Registration in Cognito1. Install the following NuGet packages in your .NET project: <PackageReference Include="Amazon.AspNetCore.Identity.Cognito" Version="3.0.1" /> <PackageReference Include="Amazon.Extensions.Configuration.SystemsManager" Version="5.0.0" /> <PackageReference Include="AWSSDK.SecretsManager" Version="3.7.101.27" /> Declare AWS configuration values in appsettings: "Region": "me-south-1", "UserPoolClientId": "UserPoolClientId", "UserPoolClientSecret": "UserPoolClientSecret", "UserPoolId": "me-south-pool" Additional Configuration Add authentication in program/startup files to enable sign-in with Cognito. 2. Create a CognitoUserPool with a unique ID in the controller: private readonly CognitoUserPool _pool; private readonly CognitoUserManager<CognitoUser> _userManager; var user = _pool.GetUser(registerUserRequest.LoginId); 3.Add user attributes (email, phone number, custom attributes) using user.Attributes.Add(). user.Attributes.Add(CognitoAttribute.Email.AttributeName, registerUserRequest.Email); user.Attributes.Add(CognitoAttribute.PhoneNumber.AttributeName, registerUserRequest.Mobile); user.Attributes.Add("custom:branch_code", registerUserRequest.BranchCode); user.Attributes.Add("custom:preferred_mode", preferedMode); 4. Create the user: cognitoResponse = await _userManager.CreateAsync(user, registerUserRequest.Password); Check cognitoResponse.Succeeded to determine if the user was created successfully. Second Flow: User Login with Cognito 1.Search for the user in Cognito using the login ID: var cognitoUser = await _userManager.FindByIdAsync(loginUserRequest.LoginId); 2.Set a password for the Cognito model: var authRequest = new InitiateSrpAuthRequest { Password = loginUserRequest.Password }; 3.Use StartWithSrpAuthAsync to get the session ID: var authResponse = await cognitoUser.StartWithSrpAuthAsync(authRequest); 4.Add MFA method and validate using MFA auth if needed. For MFA validation, set the MFA settings in Cognito:v ar authRequest = new RespondToMfaRequest { SessionID = validateLoginUserRequest.SessionId, MfaCode = validateLoginUserRequest.Otp, ChallengeNameType = ChallengeNameType.SMS_MFA }; authResponse = await cognitoUser.RespondToMfaAuthAsync(authRequest); Extract tokens from Cognito: authResponse.AuthenticationResult.IdToken authResponse.AuthenticationResult.RefreshToken Forgot Password Flow 1.Search for the user with LoginId in Cognito and call ForgotPasswordAsync: var user = await _userManager.FindByIdAsync(loginUserRequest.LoginId); await user.ForgotPasswordAsync(); 2.Optionally, call ConfirmForgotPassword method in Cognito. _userManager.ConfirmForgotPassword(userID, token, newPassword, CancellationToken cancellationToken) Here, understanding AWS Cognito Authentication Methods and Utilizing Them as Needed.
In this blog, I will be sharing insights on how to effectively manage Conditional Authorization and Swagger Customization. Case 1 I'm currently working on a problem our QA team found while testing our website. Specifically, there's an issue with one of the features in the application that uses an API. In the QA environment, we need to allow access without authentication, but in the production environment, authentication is required. To fix this, I added a feature called Conditional Authorize Attribute with help of Environment Variable. This feature lets us control access to the API based on the environment. It allows anonymous access when necessary. In my situation, I've added a environment variable setting called "ASPNETCORE_ENVIRONMENT" to "QA" in the testing site's pipeline. Because of this, I can use the API on the QA server without requiring authentication. This method also helps specific authorization rules for the API based on the environment. Case 2 Additionally, I've added Swagger requests into a value object to meet specific requirements on swagger. By extending the Swashbuckle Swagger IOperationFilter, I integrated logic tailored to our needs. This approach allows us to customize requests in Swagger for all APIs directly. Furthermore, I've implemented a middleware designed to handle responses and here's how it works. In my case, there are three kinds of response class in my code that specify the response type (like ApiErrorResponse, ValidatorResponse, ResponseModel). According to the requirements, when we get a 200-status code with the correct response class model, I need to wrap the response object in a value format. I created a middleware for this. It figures out which endpoint we're dealing with through the HttpContext. Using that endpoint, I grab the metadata related to the ProducesResponseTypeAttribute class and check for a status code of OK (Metadata Extraction). If I manage to get the metadata with a status code of 200, I include that response in value format. Otherwise, I stick with the same model response. This helps you to modify the response as per needed outcome. These implementations provide a flexible solution for conditionally authorizing API access and wrapping request/response in an object according to specified requirements.
In this article, we will review how to create a data flow task package of SSIS in Console Application with an example. Requirements Microsoft Visual Studio 2017 SQL Server 2014 SSDT Article Done with the above requirements? Let's start by launching Microsoft Visual Studio 2017. Create a new Console Project with .Net Core. After creating a new project, provide a proper name for it. In Project Explorer import relevant references and ensure that you have declared namespaces as below: using Microsoft.SqlServer.Dts.Pipeline.Wrapper; using Microsoft.SqlServer.Dts.Runtime; using RuntimeWrapper = Microsoft.SqlServer.Dts.Runtime.Wrapper; To import above namespaces we need to import below refrences. We need to keep in mind that, above all references should have same version. After importing namespaces, ask user for the source connection string, destination connection string and table that will be copied to destination. string sourceConnectionString, destinationConnectionString, tableName; Console.Write("Enter Source Database Connection String: "); sourceConnectionString = Console.ReadLine(); Console.Write("Enter Destination Database Connection String: "); destinationConnectionString = Console.ReadLine(); Console.Write("Enter Table Name: "); tableName = Console.ReadLine(); After Declaration, create instance of Application and Package. Application app = new Application(); Package Mipk = new Package(); Mipk.Name = "DatabaseToDatabase"; Create OLEDB Source Connection Manager to the package. ConnectionManager connSource; connSource = Mipk.Connections.Add("ADO.NET:SQL"); connSource.ConnectionString = sourceConnectionString; connSource.Name = "ADO NET DB Source Connection"; Create OLEDB Destination Connection Manager to the package. ConnectionManager connDestination; connDestination= Mipk.Connections.Add("ADO.NET:SQL"); connDestination.ConnectionString = destinationConnectionString; connDestination.Name = "ADO NET DB Destination Connection"; Insert a data flow task to the package. Executable e = Mipk.Executables.Add("STOCK:PipelineTask"); TaskHost thMainPipe = (TaskHost)e; thMainPipe.Name = "DFT Database To Database"; MainPipe df = thMainPipe.InnerObject as MainPipe; Assign OLEDB Source Component to the Data Flow Task. IDTSComponentMetaData100 conexionAOrigen = df.ComponentMetaDataCollection.New(); conexionAOrigen.ComponentClassID = "Microsoft.SqlServer.Dts.Pipeline.DataReaderSourceAdapter, Microsoft.SqlServer.ADONETSrc, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"; conexionAOrigen.Name = "ADO NET Source"; Get Design time instance of the component and initialize it. CManagedComponentWrapper instance = conexionAOrigen.Instantiate(); instance.ProvideComponentProperties(); Specify the Connection Manager. conexionAOrigen.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(connSource); conexionAOrigen.RuntimeConnectionCollection[0].ConnectionManagerID = connSource.ID; Set the custom properties. instance.SetComponentProperty("AccessMode", 0); instance.SetComponentProperty("TableOrViewName", "\"dbo\".\"" + tableName + "\""); Reinitialize the source metadata. instance.AcquireConnections(null); instance.ReinitializeMetaData(); instance.ReleaseConnections(); Now, Add Destination Component to the Data Flow Task. IDTSComponentMetaData100 conexionADestination = df.ComponentMetaDataCollection.New(); conexionADestination.ComponentClassID = "Microsoft.SqlServer.Dts.Pipeline.ADONETDestination, Microsoft.SqlServer.ADONETDest, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"; conexionADestination.Name = "ADO NET Destination"; Get Design time instance of the component and initialize it. CManagedComponentWrapper instanceDest = conexionADestination.Instantiate(); instanceDest.ProvideComponentProperties(); Specify the Connection Manager. conexionADestination.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(connDestination); conexionADestination.RuntimeConnectionCollection[0].ConnectionManagerID = connDestination.ID; Set the custom properties. instanceDest.SetComponentProperty("TableOrViewName", "\"dbo\".\"" + tableName + "\""); Connect the source to destination component: IDTSPath100 union = df.PathCollection.New(); union.AttachPathAndPropagateNotifications(conexionAOrigen.OutputCollection[0], conexionADestination.InputCollection[0]); Reinitialize the destination metadata. instanceDest.AcquireConnections(null); instanceDest.ReinitializeMetaData(); instanceDest.ReleaseConnections(); Map Source input Columns and Destination Columns foreach (IDTSOutputColumn100 col in conexionAOrigen.OutputCollection[0].OutputColumnCollection) { for (int i = 0; i < conexionADestination.InputCollection[0].ExternalMetadataColumnCollection.Count; i++) { string c = conexionADestination.InputCollection[0].ExternalMetadataColumnCollection[i].Name; if (c.ToUpper() == col.Name.ToUpper()) { IDTSInputColumn100 column = conexionADestination.InputCollection[0].InputColumnCollection.New(); column.LineageID = col.ID; column.ExternalMetadataColumnID = conexionADestination.InputCollection[0].ExternalMetadataColumnCollection[i].ID; } } } Save Package into the file system. app.SaveToXml(@"D:\Workspace\SSIS\Test_DB_To_DB.dtsx", Mipk, null); Execute package. Mipk.Execute(); Conclusion In this article, we have explained one of the alternatives for creating SSIS packages using .NET console application. In case you have any questions, please feel free to ask in the comment section below. RELATED BLOGS: Basics of SSIS(SQL Server Integration Service)