I am trying to get a token of a dot net core 2.0 web API.
This is what I am doing:
C:\Users\danyb>curl -X POST -H 'Content-Type:application/json'^
Mehr? -d '{\"username\":\"mario\",\"password\":\"secret\"}'^
Mehr? localhost:56183/api/token
[1/2]: '"username":"mario"'localhost:56183/api/token --> <stdout>
--_curl_--'"username":"mario"'localhost:56183/api/token
curl: (3) Port number ended with '"'
[2/2]: '"password":"secret"'localhost:56183/api/token --> <stdout>
--_curl_--'"password":"secret"'localhost:56183/api/token
curl: (3) Port number ended with '"'
I already searched the web but couldn't find a working solution.
TokenController Class:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace JWT.Controllers
{
[Route("api/[controller]")]
public class TokenController : Controller
{
private IConfiguration _config;
public TokenController(IConfiguration config)
{
_config = config;
}
[AllowAnonymous]
[HttpPost]
public IActionResult CreateToken([FromBody]LoginModel login)
{
IActionResult response = Unauthorized();
var user = Authenticate(login);
if (user != null)
{
var tokenString = BuildToken(user);
response = Ok(new { token = tokenString });
}
return response;
}
private string BuildToken(UserModel user)
{
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.Name),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(JwtRegisteredClaimNames.Birthdate, user.Birthdate.ToString("yyyy-MM-dd")),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
private UserModel Authenticate(LoginModel login)
{
UserModel user = null;
if (login.Username == "mario" && login.Password == "secret")
{
user = new UserModel { Name = "Mario Rossi", Email = "[email protected]" };
}
return user;
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
private class UserModel
{
public string Name { get; set; }
public string Email { get; set; }
public DateTime Birthdate { get; set; }
}
}
}
I think the error has nothing to do with the Controller but more with the Curl call as itself.
^"instead of\"inside your string.