Skip to content

GravitoLtd/gravito-client-dotnet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gravito Client Credentials Flow .Net Client

This sample demonstrates how to connect to Gravito IdentityServer using C#.Net to get the access_token.

You can download the zip or clone the repository from GitHub Repository

Table of Contents

Getting Started

We have explained how Gravito works as an Identity Provider in our detailed documentation at Gravito Docs.

Tools Required

  • Visual Studio 2019
  • Microsoft .Net Core SDK 3.1.* (Haven't tested this sample with upper versions, it might need some changes)

Usage Guide

Code required to get the access_token from server:

  • Declare private variable of IHttpClientFactory & inject it in constructor
private readonly IHttpClientFactory _httpClientFactory;
  • Create client for getting the access_token
var serverClient = _httpClientFactory.CreateClient();
  • Get the available configuration of the server
var discoveryDocument = await serverClient.GetDiscoveryDocumentAsync(_configuration.GetValue<string>("Identity:ServerAddress"));

ServerAddress parameter value can be stored in appsettings.json or Azure Key-Vault.

  • Call TokenEndpoint and get the token
var tokenResponse = await serverClient.RequestClientCredentialsTokenAsync (
new ClientCredentialsTokenRequest
{
    Address = discoveryDocument.TokenEndpoint,

    GrantType = _configuration.GetValue<string>("Identity:GrantType"),
    ClientId = _configuration.GetValue<string>("Identity:ClientId"),
    ClientSecret = _configuration.GetValue<string>("Identity:ClientSecret"),
    Scope = _configuration.GetValue<string>("Identity:Scope")
});

After Getting access_token

  • Create another client of type HttpClientFactory to use protected APIs & set the received bearer token to it
var apiClient = _httpClientFactory.CreateClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);
  • Prepare your data
var sampleModel = new
{
    Property1 = "data",
    Property2 = "data"
};

var json = JsonConvert.SerializeObject(sampleModel);
var data = new StringContent(json, Encoding.UTF8, "application/json");
  • Access the protected APIs
var response = await apiClient.PostAsync("https://protected-endpoint", data);
var content = await response.Content.ReadAsStringAsync();

References

  • appsettings.json file
"Identity": {
    "ClientId": "client_id",
    "ClientSecret": "client_secret",
    "Scope": "api",
    "GrantType": "client_credentials",
    "ServerAddress": "https://your-identityserver-address/"
}

Visit Us At

Website

About

Gravito's IdentityServer4 client for C#.Net

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages