8

I want to implement OAuth2.0 token in ASP.NET Core Web API. I have seen many tutorials and videos but all are doing the traditional way or in ASP.NET only not in Core. So I want the way to implement in visual studio 2022 with latest version of ASP.NET Core. Please help

I have seen many tutorials and videos but all are doing the traditional way or in ASP.NET only not in Core. So I want the way to implement in visual studio 2022 with latest version of ASP.NET Core. Please help

pratapsingh845
  • 103
  • 1
  • 1
  • 5
  • sorry to put it bluntly but there are hundreds of examples available on internet. you have to try out and if still it is not working then you should ask question for specific issue. – CodingMytra Sep 09 '22 at 11:18

2 Answers2

11

You can use Jwt authentication to protect your web api and this is one of the method based on OAuth2.0. Here's a blog and the following codes are based on it.

OAuth2.0 is a protocol but not the implement. So you can't find samples for it. But when you searched Jwt auth, Azure AD into .net 6 or some other products, you will find many doucuments.

Let's see some additional information which may also help you:

enter image description here

Let's go back to the sample, in this scenario, you have to integrate the authentication first. In .net 6, going to program.cs and adding these code:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);
//adding jwt auth
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            //define which claim requires to check
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            //store the value in appsettings.json
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });
    
...

app.UseRouting();
//adding UseAuthentication
app.UseAuthentication();
app.UseAuthorization();

In appsettings.json:

"Jwt": {
    "Key": "ThisismySecretKey",
    "Issuer": "Test.com"
  }

Then, pls add [Authorize] before the api controller, then you've established the authentication and when accessing the api without the correct jwt token, you will get 401 error:

enter image description here

Let's generate an access token then test calling the api with the token. In another Controller without [Authorize], adding code like this:

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

private IConfiguration _config;

public HomeController(IConfiguration config)
{
    _config = config;
}

public IActionResult Index()
{
    ViewBag.accessToken = generateJwt();
    return View();
}

private string generateJwt() {
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

    //If you've had the login module, you can also use the real user information here
    var claims = new[] {
        new Claim(JwtRegisteredClaimNames.Sub, "user_name"),
        new Claim(JwtRegisteredClaimNames.Email, "user_email"),
        new Claim("DateOfJoing", "2022-09-12"),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };

    var token = new JwtSecurityToken(_config["Jwt:Issuer"],
        _config["Jwt:Issuer"],
        claims,
        expires: DateTime.Now.AddMinutes(120),
        signingCredentials: credentials);

    return new JwtSecurityTokenHandler().WriteToken(token);
}

Then calling the api with the token, you can decode the token first:

enter image description here enter image description here

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
0

According to this okta developer blog article, the .Net Core team decided not to include the UseOAuthAuthorizationServer class.

"which means that you’ll need to plug something else in"

The above article links to this stackoverflow.