Friday, 10 March 2023

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!

No comments:

Post a Comment

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