API with OAuth2 App Flow Made Easy in .NET
Tags: dotnet, tutorial
Published: 2022-09-24 11:15:35

``OAuth is not an API or a service, it's an open standard for authorization. OAuth provides apps with a standard solution to secure delegate access.

When you look at the flow, it should be straight forward to implement, ... until you start implementing it for Apps.

Ex. Pinterest uses OAuth with their API, but a way to get your access code is by sendng a user to a Pinterest page and redirect to you web site.   How is this possible for Server Apps like who do Automatization?

Let me showcase a solution

## Pre Requisites
- [CodeHelper.Core.OAuth2](https://www.nuget.org/packages/CodeHelper.Core.OAuth2)

## How To Get The Access Token


## The Idea
The idea behindthe `CodeHelper.Core.OAuth2` wrapper is to reduce the workload to create the access tokens and consume the API endpoints
&nbsp; 
## Table of Contents
1. Tools to let you receive an access token
 - Online OAuth2 Tools
 - Code 
2. Easy Implementation to use the access token
  

## Tools to let you receive an access token
### Online OAuth2 Tools
Use this list of links/tools of famous platforms who require OAuth2 implementation, where you can easily generate your Accesss Token with any code
[OAuth2 Tools](https://frederik.today/codehelper/tools/oauth-app-access-tokens)
  
  
### Code Yourself
Not all companies want to use an online tool to generate Access Tokens due extra security reasons.

Therefore the flow is made accessible via the CodeHelper.Core.OAuth2 wrapper.   You can create a secure admin View in your project, accessible to the internet.

The view should request **App ID**, **App Secret** and the **scopes** and the **Redirect URL**

_Often the Redirect URL should be added to the accepted domains when creating your app on the platform.  The URL can be `localhost`_

The following code is places in your controller
```
public async Task<ActionResult> OauthAppAccessPinterest(OAuthProvider model, string code)
{
  ModelState.Clear();
  model.RedirectUri = "The URL to your View";
  if (!string.IsNullOrEmpty(code))
  {
      model.ClientId = HttpContext.Session.GetString("ID");
      model.ClientSecret = HttpContext.Session.GetString("Value");
      model.RedirectUri = HttpContext.Session.GetString("Uri");
      model.Scope = HttpContext.Session.GetString("Scope");
      model.OAuthCode = code;
                
      await model.GetAccessToken();
      if (!string.IsNullOrEmpty(model.AccessToken))
      {
        //-- CODE TO SAVE SECURELY YOUR ACCESS TOKEN --
        HttpContext.Session.Clear();                   
      }                 
  }
  else if (!string.IsNullOrEmpty(model.ClientId) && 
                  !string.IsNullOrEmpty(model.ClientSecret))
  {
    HttpContext.Session.SetString("ID", model.ClientId);
    HttpContext.Session.SetString("Value", model.ClientSecret);
    HttpContext.Session.SetString("Uri", model.RedirectUri);
    HttpContext.Session.SetString("Scope", model.Scope);
    return Redirect(model.GetOAuthTokenUrl());
  }
  return View(model);
}
```

## How to use OAuth2 Wrapper with the Access Token
All CodeHelper Packages uses the wrapper
```
using CodeHelper.Core.OAuth2;

OAuthProvider _oauthProvider = new(){ AccessCode = "ajhshjabs...."};

//-- Some Data to post in the body
MyClass _mydata;

//-- Get --
string endPointUrlGet="htps://api...";
_mydata = _oauthProvider.GetJson<MyClass>(endPointUrlGet);

//-- Post --
_mydata= new() { Name = name, Description = description, Privacy = privacy };  
string endPointUrlPost="htps://....";

var _jsonResult = _oauthProvider.PostJson<MyClass>(endPointUrlPost, _mydata.GetJsonString());
```

### Explanation
Function `GetJsonString()` is an extension method, provied by the OAuth2 Wrapper and will turn any class into a Json format and return as HttpContent type, which is needed to add the data in the request body.

Function `GetJSon<T>()` will Execute a Get Request, using the EndPoint and wil return a deserialized class,containing the data from the API


Function `PostJSon()` will Execute a Post Request, using the EndPoint and the data.  The function will return a Deserialized class, containing the data from the API

Function `DeleteRequest()` wil execute a Delete request, using the endpoint.

In general, you give the endpoint (+ body data) and the Wrapper handles the rest.