Token Authentication

Hello, I am authenticating via a SPA redirect login, which sets the Bearer token.
What i need to do is verify that token on our backend C# API. The documentation has so many different approaches to this that I am confused at what we need set up on our Okta account.

I am using this code from the okta-auth-dotnet library:

var authClient = new AuthenticationClient(new OktaClientConfiguration()
            {
                OktaDomain = "https://domain.okta.com",
                Token = "API_Token",
                ConnectionTimeout = 360,
                DisableHttpsCheck = false
            });

            var authnOptions = new AuthenticateWithActivationTokenOptions()
            {
                ActivationToken = "token from Authorization header Bearer"
            };

            var authnResponse = authClient.AuthenticateAsync(authnOptions).Result

I receive the error: “OktaApiException: Authentication failed (401, E0000004)”. I know I am authenticated via the redirect, but I just want to be able to verify the token’s authenticity on the server before proceeding.
I have tried prefixing the API token above with SSWS (although i would think the framework would do this on its own?).

Is there a step I am missing here or is there a specific type of API we need to set up.

Any help appreciated.
Thanks.

Have you taken a look at our .NET Resource Server examples, e.g. samples-aspnetcore/samples-aspnetcore-6x/resource-server at master · okta/samples-aspnetcore · GitHub? They’re designed to handle this for you and were even created to directly work with our SPA example apps.

Yes, but we’re not using dotnetcore. I figured I could simply use this:
GitHub - okta/okta-auth-dotnet: Okta .NET Authentication SDK to call our okta service, providing the API key to verify a token.

I do not have administrator access to our okta developer account so I have to tell someone what to set up. Is there a specific type of API that we need set up for just authenticating tokens? Is that called a resource server?
I don’t know the nomenclature for which API to simply authenticate a token using the okta donet library.

I suppose first, I need to know what the API type is to verify a token using your okta .net sdk.

Just for informational purposes, the user has already validated via okta-hosted redirect login. I only need to verify the token returned to the client on our backend.

*Do I need to see about scheduling with a developer for this question?

Oh, if you’re not using Core, we also have a .NET 4.x sample

The Auth SDK is for Primary Authentication into Okta, but if you’re sending Access Tokens (granted in your SPA) over to your resource server as auth, you’ll want to use something like our sample/.NET WebAPI SDK (4.x and Core). Then your resource server will validate this Access Token and use that to determine if the user is allowed to access the requested resource.

To verify a bearer token on your backend C# API, you typically need to use a library that can handle JSON Web Tokens (JWT) authentication. Microsoft provides a library called System.IdentityModel.Tokens.Jwt for working with JWTs in C# applications. Here’s a basic outline of how you can verify the bearer token in your C# API:

  1. Install the System.IdentityModel.Tokens.Jwt package if you haven’t already. You can do this via NuGet Package Manager or Package Manager Console with the following command:
Install-Package System.IdentityModel.Tokens.Jwt
  1. In your C# API, you’ll need to implement a method to validate the token. This typically involves checking the token’s signature and expiration time. Here’s a basic example of how you might implement this:
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

public class TokenService
{
    private readonly string _secretKey; // You should replace this with your own secret key

    public TokenService(string secretKey)
    {
        _secretKey = secretKey;
    }

    public ClaimsPrincipal ValidateToken(string token)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Convert.FromBase64String(_secretKey);
        var parameters = new TokenValidationParameters
        {
            ValidateIssuer = false, // Change these settings according to your JWT configuration
            ValidateAudience = false,
            IssuerSigningKey = new SymmetricSecurityKey(key)
        };

        try
        {
            var principal = tokenHandler.ValidateToken(token, parameters, out _);
            return principal;
        }
        catch (Exception ex)
        {
            // Token validation failed
            Console.WriteLine($"Token validation failed: {ex.Message}");
            return null;
        }
    }
}
  1. You can use this TokenService class in your API controller to verify the bearer token. Here’s an example of how you might use it:
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
    private readonly TokenService _tokenService;

    public AuthController(TokenService tokenService)
    {
        _tokenService = tokenService;
    }

    [HttpGet("verify")]
    public IActionResult VerifyToken([FromHeader(Name = "Authorization")] string token)
    {
        if (string.IsNullOrWhiteSpace(token) || !token.StartsWith("Bearer "))
        {
            return BadRequest("Invalid token");
        }

        var tokenValue = token.Substring("Bearer ".Length).Trim();
        var principal = _tokenService.ValidateToken(tokenValue);

        if (principal != null)
        {
            // Token is valid
            return Ok("Token is valid");
        }
        else
        {
            // Token is invalid
            return BadRequest("Invalid token");
        }
    }
}

In this example, the VerifyToken action in the AuthController extracts the token from the Authorization header, validates it using the TokenService, and returns an appropriate response based on the validation result. golang tutorial for beginners

Remember to replace _secretKey with your actual secret key, and customize the validation parameters according to your JWT configuration.