Asp net web api protecting with a token

Introduction

ASP.NET is a popular programming language used for building web applications. One requirement in web development is to APIs using tokens. In this article, we will explore how to protect an ASP.NET Web API using a token.

Step 1: Generate a Token

The first step is to generate a token that will be used for authentication. are various ways to generate a token, but for simplicity, we will use the JSON Web Token (JWT) library.


// Generate a token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your_secret_key");
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
        new Claim(ClaimTypes.Name, "John Doe"),
        new Claim(ClaimTypes.Email, "john.doe@example.com")
    }),
    Expires = DateTime.UtcNow.AddHours(1),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);

In the above code, we first create a token handler and define a secret key. We then create a token descriptor with the necessary claims, expiration time, and signing credentials. Finally, we generate the token and convert it to a string.

Step 2: Protect the API

Now that we have a token, we can protect our ASP.NET Web API by validating the token on each request. We can achieve this by creating a authorization filter.


// Custom authorization filter
 class TokenAuthorizationFilter : 
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("your_secret_key");

        if (actionContext.Request..Authorization != null)
        {
            var tokenString = actionContext.Request.Headers.Authorization.Parameter;
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };

            try
            {
                var claimsPrincipal = tokenHandler.ValidateToken(tokenString, tokenValidationParameters, out SecurityToken validatedToken);
                Thread.CurrentPrincipal = claimsPrincipal;
            }
            catch (Exception)
            {
                actionContext. = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
        }
        else
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        }
    }
}

In the above code, we create a custom authorization filter by inheriting from the AuthorizeAttribute class. Inside the OnAuthorization method, we validate the token by checking the request headers. If the token is valid, we set the current principal to the claims principal. Otherwise, we return an unauthorized response.

Step 3: Apply the Authorization Filter

Finally, we need to apply the authorization filter to our API endpoints. We can do this by the controller or specific action methods with the [TokenAuthorizationFilter] attribute.


// Apply the authorization filter
[TokenAuthorizationFilter]
public class ApiController : ControllerBase
{
    // API endpoints
}

By applying the [TokenAuthorizationFilter] attribute, the authorization filter will be executed before any action method in the controller. This ensures that the token is validated for each request.

Conclusion

In this article, we have learned how to protect an ASP.NET Web API using a token. By generating a token, creating a custom authorization filter, and applying the filter to our API endpoints, we can ensure that only authenticated requests are access to our API.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents