27

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.

3
  • please share the token controller class Commented Jun 10, 2018 at 17:23
  • Way late to the game, but ... to quote a quote on the command line, use the carat not the backslash. So ^" instead of \" inside your string. Commented Nov 17, 2018 at 2:34
  • 1
    If you copy the curl command from swagger/index.html it will put the wrong quotes around the payload value. change them to single quotes and it will work
    – StingyJack
    Commented Mar 19, 2021 at 18:27

6 Answers 6

32

I ran into something similar and was tricked by some special character single and double quotes. So my advise here, ensure that you correctly formatted your curl request on the command line. No need to escape if you stick to double quotes within your single quotes.

Try this one:

curl -X POST -H 'Content-Type:application/json' http://localhost:56183/api/token -d '{"username":"mario", "password":"secret"}'
2
  • Double quotes works on my Mac but not on my coworkers mac.... ‾_(ツ)_/‾
    – Noah Gary
    Commented Jan 31, 2020 at 19:01
  • 1
    I get glob errors when I don't use "\" for every bracket or brace. Adding "-g" before the JSON string does not work for some reason.
    – Azurespot
    Commented May 9, 2020 at 1:02
3

Nothing worked for me, while I was using Powershell (the JSON was always send as null object). However, when I switched to cmd.exe, all solutions started to work, either by escaping " with \", or with ^\^"

2

Try using " " instead of ' ' for URI string, it worked for me, while doing for supabase api:

curl "https://mhbaythrontkdturbqui.supabase.co/rest/v1/cabin?select=*" -H "apikey: eyJhbGk" -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6"

instead of:

curl 'https://mhbaythrontkdturbqui.supabase.co/rest/v1/cabin?select=*' -H "apikey: eyJhbGk" -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6"

if doesn't work in powershell or vscode, try out in old faithful cmd.

1
  • Worked for me (on Windows)
    – Tomasito
    Commented Jul 19 at 8:33
0

You should quote you json data with single quotes.

0

I ran into this error when interpolating command output to curl

bash-3.2$ curl $(jq '.a.url.prop' data.json ) > temp.zip
curl: (3) URL rejected: Port number was not a decimal number between 0 and 65535

Using jq's -r/--raw-output flag solved the issue

bash-3.2$ curl $(jq -r '.a.url.prop' data.json ) > temp.zip

The problem looks like jq was putting surrounding quotes around the json, and curl was considering it part of the url. I thought the shell would evaluate the string, but it looks like it didn't.

# This shows double quotes showing up in the output from jq

# you can use `od -a` if you don't have xxd
$ jq '.a.url.prop' data.json | xxd   

# 00000000: 2268 7474 7073 3a2f 2f78 7878 7878 7878  "https://xxxxxxx
# ...
# 00000180: 7878 7878 7878 782e 636f 6d22 0a         xxxxxxx.com".

Using -r removed the double quotes from the output

jq -r '.a.url.prop' data.json | xxd

# 00000000: 6874 7470 733a 2f2f 7878 7878 7878 7878  https://xxxxxxx
# ...
# 00000180: 7878 7878 7878 782e 636f 6d0a            xxxxxxx.com.
0

retyped the port number and the request worked as expected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.