How to consume JWT access token and user claims using RestSharp

孤街醉人 提交于 2019-12-10 13:46:24

问题


I'm using below code to consume JWT access token from an Asp.net Web Api 2.2 service. I have followed this article to setup an authorization server in Web Api service. I'm using RestSharp in the client.

client code:

            var client = new RestClient(http://localhost:58030);
            client.Timeout = 30000;
            var request = new RestRequest(@"/Oauth/Token", Method.POST);
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddHeader("grant_type", "password");
            request.AddHeader("username", "admin@example.com");
            request.AddHeader("password", "Admin@456");
            IRestResponse response = client.Execute(request);
            result = response.Content;

As a result I'm getting following error:

{
  "error_description":"grant type not supported",
  "error":"unsupported_grant_type"
}
  1. Why I'm getting this error and how can I fix this?
  2. How can I access the Claims such as username in client?
  3. Alternatively how can I use Identity Model to consume the service?

回答1:


You added grant_type ,username and password to the Header of the http request , it should be in Body part.




回答2:


It's an old question and you probably have an implementation by now but fwiw here is the solution that worked for me

var client = new RestClient("http://blahblah/");
var request = new RestRequest("/token", Method.POST);
// all parameters need to go in body as string
var encodedBody = string.Format("username={0}&password={1}&grant_type=password", model.Username, model.Password);
request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
var response = client.Execute(request);


来源:https://stackoverflow.com/questions/34968854/how-to-consume-jwt-access-token-and-user-claims-using-restsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!