Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update project to that get token from the console #6

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
update project to that get token from the console
  • Loading branch information
HamidMosalla committed Sep 11, 2020
commit 555e7524e9342053dd22548c5810274bfaeee166
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"alg":"RS256","d":"HfjA-Hpo4J16HvyimhvPHMZzVy2z37aUlsRE-CpY3bd0Lo6nEO7otPzqgqSu_OtcQYURNt_qp6ybqSBtPiW5iscQeRfp99_LegE56DhxDNRUjcSQT1X4UXWjerx5U4Fxkva_98xblX7k3Hkj0CP4ooS2z2z3KWx88zN1HJlbIZ_SmlbY0ZgUyTIzactRcEpxa3bpN0FSKitJWz3B22SsMAU6P5xGxWyeddGHgEdc7EbbWTL4HU5TQXcglKDga0jw6TqefJNLMvfU5zH-NTYfRJpF5bVqcdYx2m2rVIm99DpffzVwmeB6Igy9K9qPI-Lrrm0w3OspQYY0S_Ci6MKVOQ","dp":"x28QXy5TG3dBV0i_0z5yvvBjU76lU83ONld_KlPIasuZQcvP4XzJw3NTnrqvreyQ0U_0DDE7grZ3vkV5eo9HhaIXlcV_KlEB_N-BtIe9WKVVA-XulKanMnImYF0n4BDR9iLWRA-Ge3IjVIl72zknHRwVXgO9sM1xFd6kMcbDVGU","dq":"wSNW6TzdjDvUYqHjzz6ort3kwuMijbaX1vFBKitkRQHb6eBNR8Lb4216XJGS_x2UoiOlEAhYt9XUE4sawk4vPT-TNEAdX2-rB11HqatIhMVKOpJora_fuo6V7CZC7szYSkRq2XUDCdPy2_So42oTBP2XjBZGqqwoL-Iyj4F4-NM","e":"AQAB","kid":"FE8A3DBAC27892CDA94B099117CD7DF4","kty":"RSA","n":"x-dgy03UnzHv9pahL22CBXW2Qmk7Et_bqiaNUxehlZtGctANVBl4hR9oQQITHOBMM-7FlkDBnh_fN876LdOzhUClE_eIxkJ4nybr31aVDuLojfe3kbKPfKNTpBUoLHePkIAM4nbJfhxNn1eZR26_MSv15RtsZFkqCr6dQmVkfLkXJmbpCOXJHp-Mp0-_399YuHQhUyUHR4JmadbFC1kIlFiWU6AngG6-zpuF-pbcQZo3pp2QZgdrX9Q0pihgakV0WXJw6WDKmN-ryVgmUsUlRB219VSB7a5SFQHw92avMkyeWfT12H-2d5dWdopEyViOITEGS_2FgSfxHBt5CyURTQ","p":"0GXY7BV2jMPhAVsC8m7vIbQjL3JAvyt-zf0yqYDOoR2LRGxBVHAlv8YZuTcfLdKnlqk4F5kKV8xy_pOL6jCt75C0Fjm8fKQz0DuvluRwfrV3M15nq8YWWzEsGfl0LhxFOPGgLAqXHnXs4ChL-P_z0BwG_x1c7Xkx-4JKRgGSaM8","q":"9ZDW2untevQRiL61CSpjliqAcsk4qE_FLxpjQh9KlZzNks6N0JH-l0cJCMugMGWTBd3qafFzqBXK7zbJjxNcvL4Fl2lNtYl2COlXwibHld09PdyBY3zFdiuZPv3QrJiMK8nZt6MMfriW8UMMJL9IgwAWTFMnSPeqW3cxrcOosyM","qi":"nky-0F0Bcph39BGKDuDP2hN6C2YrP0PSuSK9Q1-ae-hTAzpXXvm4ZhI8hnNJjPYUN0TJssmLYS1ksxW6if79PTLGBiI-6lUtXBX_5BgX-WUgV2YzQSvD6TfCQbLMaANZVgCQZfGEb2hFwy_gMnmgjgTQwwnaQQefktCr7-OSE3M"}
20 changes: 15 additions & 5 deletions IdentityServer4-Client-TestUser/ApiResource/ApiResource.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
@@ -12,9 +12,19 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.6.0" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.5" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.5" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.1.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.8" PrivateAssets="all" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.8" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="2.0.0-preview1-final" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.8" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.2.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
19 changes: 11 additions & 8 deletions IdentityServer4-Client-TestUser/ApiResource/Startup.cs
Original file line number Diff line number Diff line change
@@ -17,27 +17,30 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddControllers();

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

services.AddAuthorization(options => options.AddPolicy("Founder", policy => policy.RequireClaim("Employee", "Mosalla")));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseMvc();
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
}
}
2 changes: 1 addition & 1 deletion IdentityServer4-Client-TestUser/Client/Client.csproj
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="IdentityModel" Version="3.10.1" />
<PackageReference Include="IdentityModel" Version="4.3.1" />
</ItemGroup>

</Project>
286 changes: 145 additions & 141 deletions IdentityServer4-Client-TestUser/Client/Program.cs
Original file line number Diff line number Diff line change
@@ -1,142 +1,146 @@
using System;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;

namespace Client
{
class Program
{
static void Main(string[] args)
{
/*
More info: http://hamidmosalla.com/2017/10/19/policy-based-authorization-using-asp-net-core-2-and-json-web-token-jwt/
*/

var requestWithoutPolicyResponse = Task.Run(RequestWithClientCredentialsWithoutPolicy).Result;
var requestWithClientCredetials = Task.Run(RequestWithClientCredentialsWithPolicy).Result;
var requestWithResourceOwnerPassword = Task.Run(RequestWithResourceOwnerPasswordWithPolicy).Result;

Console.WriteLine($"{nameof(requestWithoutPolicyResponse)} : {requestWithoutPolicyResponse}");
Console.WriteLine($"{nameof(requestWithClientCredetials)} : {requestWithClientCredetials}");
Console.WriteLine($"{nameof(requestWithResourceOwnerPassword)} : {requestWithResourceOwnerPassword}");

Console.ReadLine();
}

public static async Task<string> RequestWithClientCredentialsWithoutPolicy()
{
async Task<string> GetAccessToken()
{
var openIdConnectEndPoint = await DiscoveryClient.GetAsync("http://localhost:5000");
var tokenClient = new TokenClient(openIdConnectEndPoint.TokenEndpoint, "client1", "123654");
var accessToken = await tokenClient.RequestClientCredentialsAsync("Api1");

if (accessToken.IsError)
{
Console.WriteLine(accessToken.Error);
return accessToken.Error;
}

Console.WriteLine(accessToken.Json);

return accessToken.AccessToken;
}

using (var client = new HttpClient())
{
var accessToken = await GetAccessToken();

client.SetBearerToken(accessToken);

var response = await client.GetAsync("http://localhost:5001/api/ApiResourceWithoutPolicy");

if (!response.IsSuccessStatusCode)
{
return response.StatusCode.ToString();
}

var content = await response.Content.ReadAsStringAsync();

return content;
}
}

public static async Task<string> RequestWithClientCredentialsWithPolicy()
{
async Task<string> GetAccessToken()
{
var openIdConnectEndPoint = await DiscoveryClient.GetAsync("http://localhost:5000");
var tokenClient = new TokenClient(openIdConnectEndPoint.TokenEndpoint, "client1", "123654");
var accessToken = await tokenClient.RequestClientCredentialsAsync("Api1");

if (accessToken.IsError)
{
Console.WriteLine(accessToken.Error);
return accessToken.Error;
}

Console.WriteLine(accessToken.Json);

return accessToken.AccessToken;
}

using (var client = new HttpClient())
{
var accessToken = await GetAccessToken();

client.SetBearerToken(accessToken);

var response = await client.GetAsync("http://localhost:5001/api/ApiResourceWithPolicy");

if (!response.IsSuccessStatusCode)
{
return response.StatusCode.ToString();
}

var content = await response.Content.ReadAsStringAsync();

return content;
}
}

public static async Task<string> RequestWithResourceOwnerPasswordWithPolicy()
{
async Task<string> GetAccessToken()
{
var discoveryResponse = await DiscoveryClient.GetAsync("http://localhost:5000");
// request token
var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "ro.client1", "123654");
var accessToken = await tokenClient.RequestResourceOwnerPasswordAsync("mosalla", "password", "Api1");

if (accessToken.IsError)
{
Console.WriteLine(accessToken.Error);
return accessToken.Error;
}

Console.WriteLine(accessToken.Json);

return accessToken.AccessToken;
}

using (var client = new HttpClient())
{
var accessToken = await GetAccessToken();

client.SetBearerToken(accessToken);

var response = await client.GetAsync("http://localhost:5001/api/ApiResourceWithPolicy");

if (!response.IsSuccessStatusCode)
{
return response.StatusCode.ToString();
}

var content = await response.Content.ReadAsStringAsync();

return content;
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel;
using IdentityModel.Client;

namespace Client
{
class Program
{
static async Task Main(string[] args)
{
/*
More info: http://hamidmosalla.com/2017/10/19/policy-based-authorization-using-asp-net-core-2-and-json-web-token-jwt/
*/

var requestWithoutPolicyResponse = await RequestWithClientCredentialsWithoutPolicy();
var requestWithClientCredetials = await RequestWithClientCredentialsWithPolicy();
var requestWithResourceOwnerPassword = await RequestWithResourceOwnerPasswordWithPolicy();

Console.WriteLine($"{nameof(requestWithoutPolicyResponse)} : {requestWithoutPolicyResponse}");
Console.WriteLine($"{nameof(requestWithClientCredetials)} : {requestWithClientCredetials}");
Console.WriteLine($"{nameof(requestWithResourceOwnerPassword)} : {requestWithResourceOwnerPassword}");

Console.ReadLine();
}

private static async Task<string> GetAccessToken()
{
var httpClient = new HttpClient();

var openIdConnectEndPoint = await httpClient.GetDiscoveryDocumentAsync("http://localhost:5000");

var accessToken = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = openIdConnectEndPoint.TokenEndpoint,
ClientId = "client1",
ClientSecret = "123654",
Scope = "api1.read",
});

if (accessToken.IsError)
{
Console.WriteLine(accessToken.Error);
return accessToken.Error;
}

Console.WriteLine(accessToken.Json);

return accessToken.AccessToken;
}

private static async Task<string> GetAccessTokenPasswordTokenRequest()
{
var httpClient = new HttpClient();

var openIdConnectEndPoint = await httpClient.GetDiscoveryDocumentAsync("http://localhost:5000");

PasswordTokenRequest passwordTokenRequest = new PasswordTokenRequest()
{
Address = openIdConnectEndPoint.TokenEndpoint,
ClientId = "ro.client1",
ClientSecret = "123654",
GrantType = OidcConstants.GrantTypes.AuthorizationCode,
Scope = "Api1",
UserName = "mosalla",
Password = "password"
};

var accessToken = await httpClient.RequestPasswordTokenAsync(passwordTokenRequest);

if (accessToken.IsError)
{
Console.WriteLine(accessToken.Error);
return accessToken.Error;
}

Console.WriteLine(accessToken.Json);

return accessToken.AccessToken;
}

public static async Task<string> RequestWithClientCredentialsWithoutPolicy()
{
using (var client = new HttpClient())
{
var accessToken = await GetAccessToken();

client.SetBearerToken(accessToken);

var response = await client.GetAsync("http://localhost:5001/api/ApiResourceWithoutPolicy");

if (!response.IsSuccessStatusCode)
{
return response.StatusCode.ToString();
}

var content = await response.Content.ReadAsStringAsync();

return content;
}
}

public static async Task<string> RequestWithClientCredentialsWithPolicy()
{
using (var client = new HttpClient())
{
var accessToken = await GetAccessToken();

client.SetBearerToken(accessToken);

var response = await client.GetAsync("http://localhost:5001/api/ApiResourceWithPolicy");

if (!response.IsSuccessStatusCode)
{
return response.StatusCode.ToString();
}

var content = await response.Content.ReadAsStringAsync();

return content;
}
}

public static async Task<string> RequestWithResourceOwnerPasswordWithPolicy()
{
using (var client = new HttpClient())
{
var accessToken = await GetAccessTokenPasswordTokenRequest();

client.SetBearerToken(accessToken);

var response = await client.GetAsync("http://localhost:5001/api/ApiResourceWithPolicy");

if (!response.IsSuccessStatusCode)
{
return response.StatusCode.ToString();
}

var content = await response.Content.ReadAsStringAsync();

return content;
}
}
}
}
Loading