向Web API提供正确的验证时,我无法获得安全令牌。
我已经制作了一个有效的Web API。我现在要添加一个j.w.t授权来访问数据。我遇到一个问题,输入正确的URL路由后,我收到HTTP 500错误,该错误旨在向我显示安全令牌。我将在下面提供代码。
Setup.cs
namespace testsitegp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICostomerRepository, CustomerRepository>();
services.AddScoped<IOrderItemRepository, OrderItemRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<ISalespersonRepository, SalespersonRepository>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var connection = "Server=tcp:testsitegp.database.windows.net,1433;Initial Catalog=H_Plus_Sports;Persist Security Info=False;" +
"User ID=-------;Password=---------;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
services.AddDbContext<H_Plus_SportsContext>(options => options.UseSqlServer(connection));
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
})
.AddJwtBearer("JwtBearer", jwtOptions =>
{
jwtOptions.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = TokenController.SIGNING_KEY,
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5)
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
}
}
TokenController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace testsitegp.Controllers
{
public class TokenController : Controller
{
private const string SECRET_KEY = "GSATDEHFG";
public static readonly SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
[HttpGet]
[Route("api/Token/{username}/{password}")]
public IActionResult Get(string username, string password)
{
if (username == password)
return new ObjectResult(GenerateToken(username));
else
return BadRequest();
}
private string GenerateToken(string username)
{
var token = new JwtSecurityToken(
claims: new Claim[]
{
new Claim(ClaimTypes.Name, username)
},
notBefore: new DateTimeOffset(DateTime.Now).DateTime,
expires: new DateTimeOffset(DateTime.Now.AddMinutes(60)).DateTime,
signingCredentials: new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
A pic of the error page after entering the right route
same page but with developer exception
这是错误消息
An unhandled exception occurred while processing the request.
ArgumentOutOfRangeException: IDX10603: Decryption failed. Keys tried: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
Exceptions caught:
'[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
token: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'
Parameter name: KeySize
Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures)
并在控制台中
HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.
GET - http://testapi.com/api/Token/yo/yo
答案 0 :(得分:0)
您的SECRET_KEY
太短,至少需要128位Not able to validate JSON Web token with .net - key to short