[英]How to consume ASP.NET Web API 2.0 with bearer token via a desktop/console application
[英]How to use bearer token with two asp.net web api
我有两个项目,他们都是asp.net web api
使用其中一个web api,我具有创建承载令牌的功能
Web api 1:
Startup.Auth.cs文件:
public void ConfigureAuth(IAppBuilder app)
{
OAuthOptions = new OAuthAuthorizationServerOptions();
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
并创建一个新的令牌我正在使用此功能:
public static string CreateTokenForAuthUser(string username ,string role)
{
AuthList authlist = new AuthList();
var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, username));
identity.AddClaim(new Claim(ClaimTypes.Role, "SomeRule"));
var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
return token;
}
所有工作正常,以创建持有人令牌,并在此网络API上使用它
我想知道我如何使用在web api 1上创建的相同的持有者令牌与另一个asp.net web api,我在控制器上使用相同的授权规则(假设它们具有相同的功能)
谢谢 !
有帮助吗?
var client = new RestClient("http://yourhost/token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=usernameEndcode&password=passwordEncodeValue", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
UPDATE
获得令牌后,您可以像这样使用它
var token = response.accessToken; //not sure accessToken is corrected here but you can easy debug to get correct property
var client = new RestClient("http://localhost:62301/api/values");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Bearer " + token);
request.AddParameter("undefined", "{\n \n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.