Identity Server 4

From Logic Wiki
Jump to: navigation, search

Sample Usage

Nuget

install IdentityServer4 Nuget package.

Startup.cs

ConfigureServices

services.AddIdentityServer()
   .AddDevelopmentSigningCredential()
   .AddInMemoryApiResources(Config.GetAllApiResources())
   .AddInMemoryClients(Config.GetClients());

Last two lines are explained below in Config class.

Configure

app.UseIdentityServer();

Config.cs

Resources

Here we list our Api's

public static IEnumerable<ApiResource> GetAllApiResources()
{
  return new List<ApiResource>
  {
     new ApiResource("MyFirstApi", "Test api" 
  };
}


Clients

We list clients and the list of APi's which they can access

public static IENumerable<Client> GetClients()
{
  return new List<Client>
  {
     new Client
    {
        ClientId = "client",
        AllowedGrantTypes = GrantTypes.ClientCredentials, 
        ClientSecrets = 
        { 
           new Secret("secret".Sha256())
        }
       AllowedScopes = { "MyFirstApi" }
     }
  };
}

AllowedScopes

List of Api's the client can access


Discovery Page

http://localhost:5000/.well-known/openid-configuration


Get token_endpoint from discovery page

APi

Nuget

install IdentityServer4.AccessTokenValidation

ConfigureServices

services.AddAuthentication("Bearer")
   .AddIdentityServerAuthentication(options => 
   {
       options.Authority = "http://localhost:5000";
       options.RequireHttpsMetadata = false;
       options.ApiName = "MyFirstApi";
   }

Configure

app.UseAuthentication();
app.UseMvc();

controller

in the beginning of the controller

[Authorize]

Client

Nuget

Install IdentityModel

Usage

var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
if (disco.IsError)
{
   Console.WriteLine(disco.Error);
   return;
}
//Grab a bearer token
 var tokenClient = new TokenClient(disco.tokenEndpoint, "client", "secret");
 var tokenResponse = await tokenClient.RequestClientCredentialsAsync("MyFirstApi");
if (tokenResponse.IsError)
{
   Console.WriteLine(tokenResponse.Error);
  return;
}
Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n"); 

Consume Token

POST

var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);

var customerInfo = new StringContent(
 JsonConvert.SerializeObject(
    new {Id = 10, Firstname = "Ali" }), Encoding.UTF8, "application/json);
 
 var createCustomerResponse = await client.PostAsync("https://localhost:59337/api/customers", customerInfo);
 if (!createCustomerResponse.IsSuccessStatusCode)
{
   Console.WriteLine(createCustomerResponse.StatusCode);
}

GET

 var getCustomerResponse = await client.GetAsync("https://localhost:59337/api/customers");
 if (!getCustomerResponse.IsSuccessStatusCode)
{
   Console.WriteLine(getCustomerResponse.StatusCode);
}else
{
   var content = await getCustomerResponse.Content.ReadAsStringAsync();
  Console.WriteLine(JArray.Parse(content));
}
Console.Read();

Details

GrantTypes

ClientCredentials

This type can be used Machine to Machine (Thrusted 1st party) applications

no user involved

Resource Owner Password =

This type can be used End User to Api applications

user involved, trusted 1st party apps (spa, js, native 1st party

Authorization Code

google, facebook, etc, user involved, web app (server app)

Implicit

web applications, user, server side web apps

Hybrid

Combination of implicit and authorization code, user, native apps, server side web apps, native desktop, mobile apps

Templates

To install templates

dotnet new -i identityserver4.templates

in command prompt go to IdentityServer project and type (is4ui is a template already installed with the line above)

dotnet new is4ui