简体   繁体   中英

what will be the solution with asp.net core 3.1 web api

I am implementing jwt security using asp.net web api app along with owin like below,

 using Microsoft.Owin;
 using Owin;
 using System.Web.Http;
 using Microsoft.Owin.Security;
 using Microsoft.Owin.Security.Jwt;

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

  namespace solution 
 {
 public class Startup
 {
public void Configuration(IAppBuilder app)
{
  app.MapSignalR();
  HttpConfiguration config = new HttpConfiguration();
  config.MapHttpAttributeRoutes();
  ConfigureOAuth(app);
  app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
  app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
  var issuer = "issuer";
  var audience = "audience";
  var secret = JwtSecurityKey.Create("SecurityKey").GetSymmetricKey();

  // Api controllers with an [Authorize] attribute will be validated with JWT
  var option =
      new JwtBearerAuthenticationOptions
      {
        AuthenticationMode = AuthenticationMode.Active,
        AllowedAudiences = new[] { audience },
        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
          {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
          }
      };
  app.UseJwtBearerAuthentication(
        option
    );
 }
}
  }

Any guideline or tutorial how to convert this to asp.net core web api application?

In the startup file you could do something similar to this:

ConfigureServices method


            // Configure JWT authentication
            var key = Encoding.UTF8.GetBytes(AppConfig.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = false,      //or true
                    ValidateAudience = false,    //or true
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    //ValidIssuer = "somewhere.com",
                    //ValidAudience = "somewhere.com",
                    IssuerSigningKey = new SymmetricSecurityKey(key)
                };
            });

...and in the Configure method

            app.UseAuthentication();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM