I have been trying to fix this problem, but nothing comes to mind anymore... Web application to use Tokens, but something keeps me back.
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
Here is the whole code:
namespace DutchTreat.Controllers
{
public class AccountController : Controller
{
private readonly ILogger<AccountController> _logger;
private readonly SignInManager<StoreUser> _signInManager;
private readonly UserManager<StoreUser> _userManager;
private readonly IConfiguration _config;
public AccountController(ILogger<AccountController> logger, SignInManager<StoreUser> signInManager, UserManager<StoreUser> userManager, IConfiguration config)
{
_logger = logger;
_signInManager = signInManager;
_userManager = userManager;
_config = config;
}
public IActionResult Login()
{
if (this.User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "App");
}
return View();
}
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false);
if (result.Succeeded)
{
if (Request.Query.Keys.Contains("ReturnUrl"))
{
return Redirect(Request.Query["ReturnUrl"].First());
}
else
{
return RedirectToAction("Shop", "App");
}
}
}
ModelState.AddModelError("", "Failed to login");
return View();
}
[HttpGet]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "App");
}
[HttpPost]
public async Task<IActionResult> CreateToken([FromBody] LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.UserName);
if (user != null)
{
var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (result.Succeeded)
{
//Create the token
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, new Guid().ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
}
}
}
return BadRequest();
}
}
}
The _config.Item["Tokens:Key"]
is pretty much legal task, the error seems the Iconfiguration
referenced to AutoMapper.Configuration
instead of Microsoft.Extensions.Configuration
I'm posting this because you can end up here with the same exact error message if you are accidentally using the wrong namespace for IConfiguration in dotnet core.
Use:
using Microsoft.Extensions.Configuration;
Instead of:
using Castle.Core.Configuration;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With