2

I am getting an error in net core 2.1:

Bearer was not authenticated.

Failure message: No SecurityTokenValidator available for token: null

The asp net output window is:

info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[7] Bearer was not authenticated. Failure message: No SecurityTokenValidator available for token: null info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4] Policy execution successful. 

The accounts controller code is here:

namespace quiz_backend.Controllers { public class Credentials { public string Email { get; set; } public string Password { get; set; } } [Produces("application/json")] [Route("api/Account")] public class AccountController : Controller { readonly UserManager<IdentityUser> userManager; readonly SignInManager<IdentityUser> signInManager; public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager) { this.userManager = userManager; this.signInManager = signInManager; } [HttpPost] public async Task<IActionResult> Register([FromBody] Credentials credentials) { var user = new IdentityUser { UserName = credentials.Email, Email = credentials.Email }; var result = await userManager.CreateAsync(user, credentials.Password); if (!result.Succeeded) return BadRequest(result.Errors); await signInManager.SignInAsync(user, isPersistent: false); // create a token var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is the secret phrase")); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var jwt = new JwtSecurityToken(signingCredentials: signingCredentials); return Ok(new JwtSecurityTokenHandler().WriteToken(jwt)); } } } 

Here is the startup.cs

namespace quiz_backend { 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.AddCors(options => options.AddPolicy("Cors", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); services.AddDbContext<QuizContext>(opt =>opt.UseInMemoryDatabase("quiz")); services.AddDbContext<UserDbContext>(opt => opt.UseInMemoryDatabase("user")); services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<UserDbContext>(); var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is the secret phrase")); services.AddAuthentication(options =>{ options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = new TokenValidationParameters() { IssuerSigningKey = signingKey, ValidateAudience = false, ValidateLifetime = false, ValidateIssuerSigningKey = true }; }); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("Cors"); app.UseMvc(); } } } 

This is the front end auth code to attach the token to the header in ts:

export class AuthInterceptor implements HttpInterceptor { constructor() {} intercept(req, next) { var token = localStorage.getItem('token') var authRequest = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) }) return next.handle(authRequest) } } 
3
  • Fail to reproduce the same error using your code . Could you please clarify in which case will the error occur ? Commented Oct 18, 2018 at 6:17
  • Thank you so much for checking my code. It happens when I register a user with angular front end. I do receive the token. I should look at my angular ts code for account Commented Oct 18, 2018 at 8:43
  • Thanks itminus, I do not know why, but it works today. I used your comment to not change anything in CORE 2.1. I reviewed my angular code and could not find anything wrong. I was stepping through my code, debugging, and it worked! I appreciage your time. Commented Oct 22, 2018 at 21:28

1 Answer 1

1

Based on your code, it seems that the issue is that the token received is not valid (NULL).

Failure message: No SecurityTokenValidator available for token: null

First of all, you should make sure the token arrives as expected.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.