authentication without identity asp.net core code example

Example 1: asp net core identity bearer token authentication example

[HttpPost]
public async Task<IActionResult> AccessToken([FromForm]string code, [FromForm]string grant_type, [FromForm]string redirect_uri, [FromForm]string client_id, [FromForm]string client_secret)
{
    // Check if code is correct and if client credentials are correct.
    if (grant_type != "authorization_code")
    {
        return Redirect(redirect_uri + "?error=unsupported_response_type");
    }
    
    if (!clientValidator.Valid(client_id, client_secret))
    {
        return Redirect(redirect_uri + "?error=access_denied");
    }
    
    // Extract the URI and user
    string previous_uri = codeAndURIStorage.Load(code);
    string user = codeAndUserStorage.Load(code);
    codeAndURIStorage.Delete(code);
    codeAndUserStorage.Delete(code);

    // Check if the new uir is the same as the previous and that the userId was found
    if (redirect_uri != previous_uri)
    {
        return BadRequest("'redirect_uri' was inconsistent.");
    }
    
    if (user == null)
    {
        return BadRequest("Couldn't find user associated with the given code.");
    }

    // Creates the signed JWT
    var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenOptions:Key"]))
    var tokenHandler = new JwtSecurityTokenHandler();
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]
        {
            new Claim(ClaimTypes.Name, user)
        }),
        Expires = DateTime.UtcNow.AddYears(2),
        Issuer = "MyWebsite.com",
        Audience = "MyWebsite.com",
        SigningCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var access_token = tokenHandler.WriteToken(token);

    // Returns the 'access_token' and the type in lower case
    return Ok(new { access_token, token_type="bearer" });
}

Example 2: asp net web api register user identityserver4

public void ConfigureServices(IServiceCollection services)
{
...
   services.AddDbContext<AppIdentityDbContext> (options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

   services.AddIdentity<AppUser, IdentityRole>()
     .AddEntityFrameworkStores<AppIdentityDbContext>()
     .AddDefaultTokenProviders();

   services.AddIdentityServer().AddDeveloperSigningCredential()
       // this adds the operational data from DB (codes, tokens, consents)
      .AddOperationalStore(options =>
      {
        options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration.GetConnectionString("Default"));
        // this enables automatic token cleanup. this is optional.
        options.EnableTokenCleanup = true;
        options.TokenCleanupInterval = 30; // interval in seconds
      })
      .AddInMemoryIdentityResources(Config.GetIdentityResources())
      .AddInMemoryApiResources(Config.GetApiResources())
      .AddInMemoryClients(Config.GetClients())
      .AddAspNetIdentity<AppUser>();
...
}