如何使用承载令牌与两个asp.net web api

本文关键字:两个 asp net api web 何使用 令牌 | 更新日期: 2023-09-27 18:01:43

我有两个项目,它们都是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相同的承载令牌,我在控制器上使用相同的授权规则(假设它们具有相同的功能)

谢谢!

如何使用承载令牌与两个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);

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