How to configure tokens for Web API in C#?

Configuring Token in C# Web API requires the following steps:

  1. Install the Microsoft.AspNet.WebApi.Owin and Microsoft.Owin.Security.Jwt NuGet packages in your Web API project.
  2. Configure the Startup class in a Web API project, which will be called upon project startup. Use the following code to configure token validation.
using Microsoft.AspNet.WebApi.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;
using System.Configuration;
using System.IdentityModel.Tokens;

[assembly: OwinStartup(typeof(YourProjectNamespace.Startup))]

namespace YourProjectNamespace
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            // 获取Token的密钥
            var secretKey = ConfigurationManager.AppSettings["TokenSecret"];

            // 配置Token验证参数
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = "your_issuer",
                ValidAudience = "your_audience",
                IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(secretKey)),
            };

            // 使用Token验证中间件
            appBuilder.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                TokenValidationParameters = tokenValidationParameters
            });

            // 配置Web API路由
            HttpConfiguration configuration = new HttpConfiguration();
            configuration.MapHttpAttributeRoutes();
            appBuilder.UseWebApi(configuration);
        }
    }
}
  1. Configure the token’s key and other related settings in the Web.config file.
<configuration>
  <appSettings>
    <add key="TokenSecret" value="your_token_secret_key" />
    <!-- 其他配置项 -->
  </appSettings>
  <!-- 其他配置项 -->
</configuration>

The TokenSecret is a key used to sign and verify Tokens, which can be configured based on actual needs.

  1. Use the [Authorize] attribute to mark API methods or controllers that require token authentication.
using System.Web.Http;

namespace YourProjectNamespace.Controllers
{
    public class YourController : ApiController
    {
        [Authorize]
        [HttpGet]
        public IHttpActionResult YourApiMethod()
        {
            // Token验证通过,执行需要授权的操作
            return Ok();
        }
    }
}

After completing the steps above, the Web API will use configured token validation to protect API methods that require authorization access.

bannerAds