Friday 10 March 2023

Making Authenticated Requests to a REST API using API Key Authentication

 As my previous article we have seen example of basic authentication in REST api using .net, now today we get an idea about API key authentication in REST api using .net using ‘HttpClient’

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
static async Task Main(string[] args)
{
// Set the API endpoint URL and the API key
var url = “https://api.example.com/endpoint";
var apiKey = “my_api_key”;

// Create the HttpClient instance
var client = new HttpClient();

// Set the API Key header
client.DefaultRequestHeaders.Add(“X-API-Key”, apiKey);

// Make a GET request to the API endpoint
var response = await client.GetAsync(url);

// Get the response content as a string
var responseContent = await response.Content.ReadAsStringAsync();

// Print the response
Console.WriteLine(responseContent);
}
}

In this example, we create a HttpClient instance and set the API Key header with the Add method. We then make a GET request to the API endpoint with GetAsync and await the response. Finally, we get the response content as a string with ReadAsStringAsync and print it to the console.

Making Authenticated Requests to a REST API using OAuth authentication

 In the continuation with previous post which is like “Making Authenticated Requests to a REST API using API Key Authentication” and “Secure REST API Requests in .NET with Basic Authentication”. now i am going to share my knowledge about authentication request to a REST API using OAuth Authentication which is basically depend on server on which we are getting authentication, in this article we are going to use google api server.

So, now lets begin:

OAuth authentication in REST APIs using .NET Core can be implemented using the following steps:

  1. Register the application with the authentication server: Register the application with the authentication server to obtain a client ID and client secret.
  2. Configure the authentication middleware: In your .NET Core application, configure the authentication middleware to use OAuth authentication by specifying the authentication scheme, client ID, client secret, and the OAuth endpoints for the authentication server.
  3. Add the authentication middleware to the pipeline: Add the authentication middleware to the middleware pipeline in your application’s Startup.cs file.
  4. Protect the API endpoints: Protect the API endpoints by applying the [Authorize] attribute to the relevant controller or action methods.
  5. Obtain an access token: To access the protected API endpoints, the client application needs to obtain an access token from the authentication server by redirecting the user to the OAuth authorization endpoint and exchanging the authorization code for an access token.
  6. Use the access token to call the API endpoints: After obtaining the access token, the client application can use it to call the API endpoints by including the access token in the Authorization header of the HTTP request.

These are the general steps to implement OAuth authentication in REST APIs using .NET Core. The specific implementation details may vary depending on the authentication server and API framework used.

Now lets make this proof with working example.

A. Register the application with the authentication server :

In this example, we’ll use Google as the authentication server. To register the application with Google, follow these steps:

  • Go to the Google API Console and create a new project.
  • Enable the Google+ API for the project.
  • Create OAuth credentials for the project, selecting “Web application” as the application type.
  • Add the authorized redirect URI for the application.

After completing these steps, you should have a client ID and client secret for the application.

B. Configure the authentication middleware:

In the Startup.cs file of your .NET Core application, add the following code to configure the authentication middleware:

services.AddAuthentication(options =>
{
options.DefaultScheme = “Cookies”;
options.DefaultChallengeScheme = “Google”;
})
.AddCookie(“Cookies”)
.AddOAuth(“Google”, options =>
{
options.ClientId = Configuration[“Google:ClientId”];
options.ClientSecret = Configuration[“Google:ClientSecret”];
options.CallbackPath = “/signin-google”;
options.AuthorizationEndpoint = “https://accounts.google.com/o/oauth2/auth";
options.TokenEndpoint = “https://accounts.google.com/o/oauth2/token";
options.UserInformationEndpoint = “https://www.googleapis.com/plus/v1/people/me";
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, “id”);
options.ClaimActions.MapJsonKey(ClaimTypes.Name, “displayName”);
options.ClaimActions.MapJsonKey(ClaimTypes.Email, “email”);
options.SaveTokens = true;
});

This code configures the authentication middleware to use Cookies as the default authentication scheme and Google as the default challenge scheme. It also specifies the client ID and client secret for the Google OAuth authentication, as well as the endpoints for authorization, token exchange, and user information.

C. Add the authentication middleware to the pipeline:

In the same Startup.cs file, add the following code to add the authentication middleware to the pipeline:

app.UseAuthentication(); /* to register pipeline with pipeline */

This code adds the authentication middleware to the middleware pipeline.

D. Protect the API endpoints:

To protect the API endpoints with OAuth authentication, apply the [Authorize] attribute to the relevant controller or action methods:

[ApiController]
[Route(“[controller]”)]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
[Authorize]
public IEnumerable<WeatherForecast> Get()
{
// …
}
}

This code applies the [Authorize] attribute to the Get method, requiring the user to be authenticated with OAuth in order to access the method.

E. Obtain an access token:

To obtain an access token from the authentication server, redirect the user to the OAuth authorization endpoint and exchange the authorization code for an access token. Here’s an example of how to do this in a controller action method:

[HttpGet]
public IActionResult Login()
{
var properties = new AuthenticationProperties
{
RedirectUri = Url.Action(“GoogleCallback”),
Items =
{
{ “scheme”, “Google” },
{ “returnUrl”, “/” },
}
};

return Challenge(properties, “Google”);
}

[HttpGet]
public async Task<IActionResult> GoogleCallback()
{
var authenticateResult = await HttpContext.AuthenticateAsync(“Google”);
// …
}

The Login method redirects the user to the Google authorization endpoint, and the GoogleCallback method exchanges the authorization code for an access token.

F. Use the access token to call the API endpoints:

After obtaining the access token, the client application can use it to call the API endpoints by including the access token in the Authorization header of the HTTP request. Here’s an example of how to do this in a client application:

var accessToken = await GetAccessTokenAsync();
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, accessToken);
var response = await httpClient.GetAsync(“https://localhost:5001/weatherforecast");

The GetAccessTokenAsync method uses the access token obtained in the previous step to authenticate the user with the API. The httpClient sends an HTTP GET request to the /weatherforecast endpoint, including the access token in the Authorization header of the request.

And that’s it! This is a basic example of how to implement OAuth authentication in a REST API using .NET Core. The specific implementation details may vary depending on the authentication server and API framework used, but the general steps should be similar.

After this i will also share how to implement oAuth with Azure AD.

I hope you’re enjoying my latest article on how to write compelling content. If you found this article helpful, I would really appreciate it if you could give it a like and follow me for more content like this.

By liking and following my articles, you’ll be the first to know when I publish new content, and you’ll have access to exclusive articles and tips that I don’t share anywhere else.

If you have any questions or feedback, please don’t hesitate to leave a comment below. I love hearing from my readers and I always try to respond as quickly as possible.

Thank you for your support, and I look forward to connecting with you all!

Missing Helper ‘__spreadArray’:Upgrading ‘tslib’ Required or This syntax requires an imported helper named ‘__spreadArray’ which does not exist in ‘tslib’. Consider upgrading your version of ‘tslib’.ts

Fixing Console Error: Troubleshooting Loom Chrome Extension for Running Projects

 As the colors of Holi fade, I extend my warmest greetings to all. May you be blessed with good health and happiness in the days ahead.

Today, we’ll explore the purpose of the ‘__spread’ array and why it causes errors in TypeScript (while it works fine in JavaScript). I’ll provide an example to illustrate the issue and then share the solution I found while developing this feature in TypeScript.

Let’s start by discussing the purpose of the __spreadArray function.

The ‘__spreadArray’ helper function is used in TypeScript code that uses the spread operator (…) on an array. The spread operator is used to “spread” the elements of an array into a new array.

However, when using the spread operator with an empty array, it can sometimes cause issues in TypeScript. For example, consider the following code:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr = […arr1, …arr2];

This code will work fine in JavaScript, but in TypeScript, it will produce an error,

error TS2532: Object is possibly ‘undefined’.

Now that we have a better understanding of the __spreadArray function, we can delve into the reasons why this error occurs specifically in TypeScript.

This error occurs because TypeScript is not sure if the arrays being spread are empty or not. To avoid this issue, the ‘__spreadArray’ helper function can be used instead of the spread operator when combining arrays. The ‘__spreadArray’ function takes two arguments: the first is the initial array, and the second is the array to be added.

Now, let’s move on to the solution. There are two ways to resolve this issue when working with TypeScript and Angular.

  1. By importing __spreadArray in our .ts file: Here is an example of how ‘__spreadArray’ can be used to combine arrays safely in TypeScript:
    import { __spreadArray } from ‘tslib’;

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr = __spreadArray(__spreadArray([], arr1), arr2);

In this example, we use ‘__spreadArray’ to create a new array by first creating an empty array with ‘__spreadArray([], arr1)’, then adding ‘arr1’ to it, and finally adding ‘arr2’ to the result. The ‘__spreadArray’ function ensures that TypeScript understands that the first argument is an array and not undefined, which avoids the error that was produced earlier.

Now come to second solution.

2. By installing tslib library in our angular node module by following command.

npm install tslib@latest

Alternatively, if you are using a package manager other than npm, you can upgrade tslib using the appropriate command for your package manager.

Once you have upgraded tslib, you should no longer see this error message.

I hope you found this article informative and useful! If you know someone else who might be struggling with the same error, please share this article with them so they can benefit from this solution too. Thank you for reading!



Wednesday 22 February 2023

Step-by-Step Guide: Adding Swagger to a .NET Core Web API Latest Version

 Swagger to a .NET Core Web API project is a great way to document your API endpoints and allow developers to easily interact with your API. Here’s how you can add Swagger to your .NET Core Web API project:

  1. Install the necessary NuGet packages:

Microsoft.AspNetCore.Mvc.Versioning
Swashbuckle.AspNetCore

2. In the  method of your  file, add the following code:

services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
});

services.AddSwaggerGen(c =>
{
c.SwaggerDoc(“v1”, new OpenApiInfo { Title = “My API”, Version = “v1” });
});

This code enables API versioning and adds Swagger to your project.

3. In the  method of your  file, add the following code:

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint(“/swagger/v1/swagger.json”, “My API V1”);
});

This code adds the Swagger UI to your project, which provides a user interface for interacting with your API.

4. Decorate your controller classes and methods with Swagger annotations to provide additional information about your API. For example:

[ApiController]
[Route(“api/[controller]”)]
[ApiVersion(“1.0”)]
[SwaggerTag(“Operations about Products”)]
public class ProductsController : ControllerBase
{
[HttpGet]
[SwaggerOperation(“GetAllProducts”)]
[SwaggerResponse(StatusCodes.Status200OK, “Success”, typeof(IEnumerable<Product>))]
[SwaggerResponse(StatusCodes.Status404NotFound, “Not Found”)]
public async Task<IActionResult> GetAllProducts()
{
// Code to get all products
}
}

In this example, the  annotation provides a friendly name for the operation, and the  annotations provide information about the possible responses to the operation.

5. Build and run your project, and navigate to  to view the Swagger UI and interact with your API.

now have Swagger integrated into your .NET Core Web API project.

“I would appreciate it if you could follow me, like my content, and share it with others.”

Tuesday 21 February 2023

how to establish a connection between a .NET Core Web API 3.1 application and a SQL Server database using the Dapper ORM?

1.     In your Startup.cs file, add the following code to the ConfigureServices method to register the connection string with the dependency injection container:

 

                Install-Package Dapper /* Run this command on package manager console */

2.     In your appsettings.json file, add a connection string for your SQL Server database. Here's an example:

 

"ConnectionStrings":

{

"MyDb": "Server=myserver;Database=mydatabase;User      Id=myusername;Password=mypassword;"

}

3.     In your Startup.cs file, add the following code to the ConfigureServices method to register the connection string with the dependency injection container:

 

services.AddScoped<IDbConnection>(c =>

    new SqlConnection(Configuration.GetConnectionString("MyDb")));

 

4.     In your controller or service class, inject the IDbConnection using constructor injection:

                private readonly IDbConnection _db;

                public MyController(IDbConnection db)

{

    _db = db;

}

 

5.     To execute a SQL query, you can use the Query or QueryAsync method of the IDbConnection object. Here's an example:

 

var customers = await _db.QueryAsync<Customer>("SELECT * FROM Customers");

 

In this example, we're selecting all the rows from the Customers table and mapping them to a list of Customer objects.


Write a SQL query to find the total revenue generated by each customer in the month of January 2022.

 Suppose you have a table called "orders" with the following columns: "order_id" (integer), "customer_id" (integer), "order_date" (date), and "total_price" (decimal). and we want to find out the total revenue generated by each customer in the month of Jan 2022.

Solution 1:

SELECT customer_id, SUM(total_price) AS total_revenue FROM orders WHERE order_date BETWEEN '2022-01-01' AND '2022-01-31' GROUP BY customer_id;


In this solution, we use the SUM() function to add up the "total_price" column for each customer, and the GROUP BY clause to group the results by customer_id. We also use the BETWEEN operator to filter the results to only include orders made in the month of January 2022. The resulting output will show the customer_id and the total revenue generated by each customer during that time period.

Solution 2:

SELECT customer_id, SUM(CASE WHEN order_date BETWEEN '2022-01-01' AND '2022-01-31' THEN total_price ELSE 0 END) AS total_revenue FROM orders GROUP BY customer_id;

This solution also calculates the total revenue generated by each customer in the month of January 2022. However, instead of using a WHERE clause to filter the data, it uses a CASE expression inside a SUM function to only include orders made within the specific time period. The GROUP BY clause groups the results by customer_id.

what is crawl request

 


A crawl request is a request made by a webmaster or website owner to a search engine's crawler to visit and crawl a specific web page or URL on their website.


Search engine crawlers (also known as spiders, bots or robots) are programs that scan the web, discovering and indexing new pages, and updating the search engine's index with new or updated content. When a website is crawled, the search engine's crawler visits the website and analyses the content of the pages to determine what the website is about and how relevant it is to specific search queries.


A crawl request can be useful for ensuring that a new or updated page on your website is indexed quickly by search engines. If you have made changes to a page that you want search engines to know about, you can submit a crawl request to the search engine so that it will visit the updated page and reindex it. This can help to ensure that the updated content is reflected in search results as quickly as possible.

It's worth noting that submitting a crawl request does not guarantee that the search engine will crawl your page immediately, but it can speed up the process. In general, search engines will crawl pages based on their own algorithms and schedule, so it's important to ensure that your website is optimized for search engines and that you regularly publish new and relevant content.

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow