How to write OAuth2 Web API Client in Asp.net MVC

后端 未结 1 1116
情歌与酒
情歌与酒 2020-12-13 15:04

We have developed a set of Web APIs (REST) which are protected by an Authorization server. The Authorization server has issued the client id and client secret. These can be

1条回答
  •  生来不讨喜
    2020-12-13 15:40

    To support the client credentials grant type, your best option is probably to directly use HttpClient:

    var request = new HttpRequestMessage(HttpMethod.Post, "http://server.com/token");
    request.Content = new FormUrlEncodedContent(new Dictionary {
        { "client_id", "your client_id" },
        { "client_secret", "your client_secret" },
        { "grant_type", "client_credentials" }
    });
    
    var response = await client.SendAsync(request);
    response.EnsureSuccessStatusCode();
    
    var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
    var token = payload.Value("access_token");
    

    For interactive flows (like the authorization code flow), there are two better approaches:

    • If your authorization server supports OpenID Connect (which is based on OAuth2), you can simply use the OpenID Connect middleware for OWIN/Katana 3 developed by Microsoft: https://www.nuget.org/packages/Microsoft.Owin.Security.OpenIdConnect/

    • If OpenID Connect is not supported by your authorization server, one option is to create your own OAuth2 client middleware. You can take a look at the last part of this SO answer for more information: Registering Web API 2 external logins from multiple API clients with OWIN Identity

    0 讨论(0)
提交回复
热议问题