0

i have a www.api.com and a www.client.com all registration will be done at api.com and login will be done at api.com. client.com will only be able to see the UI of the login form.

after user login and api.com return a token to user. How to i use the token to access the rest of the webapi in the api.com? i want to access the GetExployeeByID method. after use login. i stored the token in the sessionStorage.setItem('token', data.access_token)

api method

[RoutePrefix("api/Customer")]
public class CustomerController : ApiController
{
    List<customer> list = new List<customer>() { new customer {id=1 ,customerName="Marry",age=13},
        new customer { id = 2, customerName = "John", age = 24 } };

    [Route("GetExployeeByID/{id:long}")]
    [HttpGet]
    [Authorize]
    public customer GetExployeeByID(long id)
    {       
        return list.FirstOrDefault(x=>x.id==id);
    }

}

update 1 this is my ajax post to call the api after login

function lgetemp() {
    $.ajax({
        url: 'http://www.azapi.com:81/api/customer/GetExployeeByID/1',
        datatype:"json",
        type: 'get',
        headers: {
            "access_token":sessionStorage.getItem("token")  
        },
        crossDomain: true,
        success: function (data) {
            debugger
            alert(data.customerName)
        },
        error: function (err) {
            debugger
            alert('error')
        }

    })
}
MVC newbie
  • 579
  • 3
  • 9
  • 26

2 Answers2

0

You should pass the token in the header of the request from the client to the api

Authorization Basic yJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY=

The from your API you can query the headers and pull out the token.

string authorizationHeader = HttpContext.Current.Request.Headers["Authorization"];
string toke =  authorizationHeader.Replace("Bearer ", String.Empty);

What I've done on my latest project is have a class AuthToken that does a lot of this for me

public class AuthToken : IAuthToken
{
    private string _raw;
    private IDictionary<string, string> _deserialized;

    public string Raw
    {
        get
        {
            if (String.IsNullOrWhiteSpace(_raw))
            {
                string authorizationHeader = HttpContext.Current.Request.Headers["Authorization"];
                _raw =  authorizationHeader.Replace("Bearer ", String.Empty);
            }
            return _raw;
        }
    }

    public IDictionary<string, string> Deserialized
    {
        get
        {
            if (_deserialized == null)
            {
                string[] tokenSplit = Raw.Split('.');
                string payload = tokenSplit[1];
                byte[] payloadBytes = Convert.FromBase64String(payload);
                string payloadDecoded = Encoding.UTF8.GetString(payloadBytes);
                _deserialized =  JsonConvert.DeserializeObject<IDictionary<string, string>>(payloadDecoded);
            }
            return _deserialized;
        }
    } 
}

Then I inject that into a UserContext class that I can inject into my controllers etc. The user context can then pull out claims from the token as needed. (assuming its a JWT)

public class UserContext : IUserContext
{
    private IList<Claim> _claims;
    private string _identifier;
    private string _email;
    private string _clientId;

    public IAuthToken Token { get; }

    public IList<Claim> Claims
    {
        get
        {
            return _claims ?? (_claims = Token.Deserialized.Select(self => new Claim(self.Key, self.Value)).ToList());
        }
    } 

    public string Identifier => _identifier ?? (_identifier = Token.Deserialized.ContainsKey("sub") ? Token.Deserialized["sub"] : null);

    public string Email => _email ?? (_email = Token.Deserialized.ContainsKey(ClaimTypes.Email) ? Token.Deserialized[ClaimTypes.Email] : null);

    public UserContext(IAuthToken authToken)
    {
        Token = authToken;
    }
}
matt_lethargic
  • 2,706
  • 1
  • 18
  • 33
0

You need to pass the token to the request header and make the call to the API url. Below function can be called by passing the URL and token which you have.

static string CallApi(string url, string token) 
{
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
    using (var client = new HttpClient()) 
    {
        if (!string.IsNullOrWhiteSpace(token)) 
        {
            var t = JsonConvert.DeserializeObject<Token>(token);

            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
        }
        var response = client.GetAsync(url).Result;
        return response.Content.ReadAsStringAsync().Result;
    }
}

Refer- Token based authentication in Web API for a detailed explanation.

Souvik Ghosh
  • 4,456
  • 13
  • 56
  • 78