【问题标题】:How to use bearer token with two asp.net web api如何将不记名令牌与两个 asp.net web api 一起使用
【发布时间】:2016-12-17 11:44:17
【问题描述】:

我有两个项目都是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;

      }

创建不记名令牌并在此 Web api 上使用它的一切工作正常

我想知道如何将在 web api 1 上创建的相同不记名令牌与另一个 asp.net web api 一起使用,以便在控制器上使用相同的授权规则(假设它们具有相同的功能)

谢谢!

【问题讨论】:

  • 嘿伙计,它老了,但是......你能提供解决方案吗?我也是这种情况……
  • 我还是老样子

标签: c# asp.net asp.net-web-api token bearer-token


【解决方案1】:

有帮助吗

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);

更新

拿到token后就可以这样使用了

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);

【讨论】:

  • 让我明白我只是从 web api 2 向 web api 1 请求新令牌?如何使用已经在 web api 1 上创建的令牌?
猜你喜欢
  • 2020-08-31
  • 2023-03-11
  • 2018-01-24
  • 2012-12-10
  • 1970-01-01
  • 2016-01-09
  • 2014-10-29
  • 2015-10-10
  • 2018-02-01
相关资源
最近更新 更多