Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

asp.net web api - Error 500 authentication on asp net core 2.1

I want to implement authentication to get a token, but I have encountered a problem and my problem is that I get a 500 error when I use signingCredentials inside the tokenOption. How do I fix the problem?

AuthController:

 [HttpPost]
 [AllowAnonymous]
 public async Task<IActionResult> PostLogin([FromForm] LoginVM login)
 {
     if (!ModelState.IsValid)
     {
        return BadRequest();
     }
     if (!await _userRepository.IsExistsLogin(login))
     {
                return Unauthorized();
     }
     var SecretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("PWPAliakbarT"));
     var signinCredentials = new SigningCredentials(SecretKey, SecurityAlgorithms.HmacSha256);
     var tokenOption = new JwtSecurityToken(
        issuer: "http://localhost:58810",
        claims: new List<Claim>
        {
           new Claim (ClaimTypes.Role,"Admin"),
           new Claim(ClaimTypes.Name,login.UserName),
        },
        expires: DateTime.Now.AddMinutes(60),
        signingCredentials: signinCredentials
     );
     var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOption);
     var user =await _userRepository.GetUserByName(login.UserName);
     object sideMe = new
     {
        RoleId="Admin",
        UserName=user.UserName,
        Email=user.Email,
        ImageAddress=user.imageAddress,
        Token=tokenString
      };      
      return Ok(sideMe);
 }

Removing the code (signingCredentials: signinCredentials) fixes the error.

StartUp.cs:

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();
   services.AddDbContext<PWPDbContext>(options =>
   options.UseSqlServer(Configuration.GetConnectionString("PWPDbContext"))
   );
   services.AddTransient<IUserRepository, UserRepository>();
   services.AddTransient<IUserInfoRepository, UserInfoRepository>();
   services.AddTransient<ISettingFRepository, SettingFRepository>();
   services.AddTransient<IRecordRepository, RecordRepository>();
   services.AddTransient<IMessageRepository, MessageRepository>();
   services.AddTransient<IExpertiseRepository, ExpertiseRepository>();
   services.AddTransient<IDocumentRepository, DocumentRepository>();
   services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
      .AddJwtBearer(option =>
      {
         option.TokenValidationParameters = new TokenValidationParameters()
         {
           ValidateIssuer = true,
           ValidateAudience = false,
           ValidateLifetime = true,
           ValidateIssuerSigningKey = true,
           ValidIssuer = "http://localhost:58810",
           IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("PWPAliakbarT")),
         };
       });

    services.AddCors(option =>
    {
      option.AddPolicy("EnableCors", builder =>
      {
        builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
      });
     });
   }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
   if (env.IsDevelopment())
   {
     app.UseDeveloperExceptionPage();
   }
   app.UseMvcWithDefaultRoute();
   app.Run(async (context) =>
   {
     await context.Response.WriteAsync("Personal Web Site is Raning");
   });
   app.UseCors("EnableCors");
   app.UseAuthentication();
 }

Postman => Preview:

An unhandled exception occurred while processing the request.
ArgumentOutOfRangeException: IDX10603: The algorithm: 'HS256' requires the SecurityKey.KeySize to be greater than '128' bits. KeySize reported: '96'.
Parameter name: KeySize
Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider..ctor(SecurityKey key, string algorithm)

enter image description here

question from:https://stackoverflow.com/questions/65845265/error-500-authentication-on-asp-net-core-2-1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your SecretKey should be 16 character or greater than 16.

var SecretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("16CharSecretKeys"));
//16CharSecretKeys => is 16 character

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...