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

Add new quickstart: Token Management #204

Merged
merged 6 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.7" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="IdentityModel" Version="6.2.0" />
<PackageReference Include="IdentityModel" Version="7.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,6 @@ public static class Config
// where to redirect to after logout
PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },

AllowOfflineAccess = true,

AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Duende.IdentityServer" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="8.0.1" />
<PackageReference Include="Duende.IdentityServer" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="8.0.7" />

<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public async Task OnGet()
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

var content = await client.GetStringAsync("https://localhost:6001/identity");

var parsed = JsonDocument.Parse(content);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/CallApi">Call API</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Signout">Signout</a>
</li>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("api1");
options.Scope.Add("offline_access");
options.Scope.Add("verification");
options.ClaimActions.MapJsonKey("email_verified", "email_verified");
options.GetClaimsFromUserInfoEndpoint = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.7" />
</ItemGroup>

</Project>
51 changes: 51 additions & 0 deletions IdentityServer/v7/Quickstarts/3a_TokenManagement/Quickstart.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{52FE7FA2-9648-4BB9-AFF4-64C0C9A97E44}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IdentityServer", "src\IdentityServer\IdentityServer.csproj", "{CD3B4286-96ED-4840-BE39-0696D5E2529A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Api", "src\Api\Api.csproj", "{F985371A-37BF-48DB-873A-5E20802564A4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "src\Client\Client.csproj", "{1C77608B-A3F3-412D-8AE7-05549B80726F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebClient", "src\WebClient\WebClient.csproj", "{AA2D5914-6773-45B3-B1FA-AE1648FA8BE5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CD3B4286-96ED-4840-BE39-0696D5E2529A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CD3B4286-96ED-4840-BE39-0696D5E2529A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CD3B4286-96ED-4840-BE39-0696D5E2529A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CD3B4286-96ED-4840-BE39-0696D5E2529A}.Release|Any CPU.Build.0 = Release|Any CPU
{F985371A-37BF-48DB-873A-5E20802564A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F985371A-37BF-48DB-873A-5E20802564A4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F985371A-37BF-48DB-873A-5E20802564A4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F985371A-37BF-48DB-873A-5E20802564A4}.Release|Any CPU.Build.0 = Release|Any CPU
{1C77608B-A3F3-412D-8AE7-05549B80726F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1C77608B-A3F3-412D-8AE7-05549B80726F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1C77608B-A3F3-412D-8AE7-05549B80726F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1C77608B-A3F3-412D-8AE7-05549B80726F}.Release|Any CPU.Build.0 = Release|Any CPU
{AA2D5914-6773-45B3-B1FA-AE1648FA8BE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AA2D5914-6773-45B3-B1FA-AE1648FA8BE5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AA2D5914-6773-45B3-B1FA-AE1648FA8BE5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AA2D5914-6773-45B3-B1FA-AE1648FA8BE5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{CD3B4286-96ED-4840-BE39-0696D5E2529A} = {52FE7FA2-9648-4BB9-AFF4-64C0C9A97E44}
{F985371A-37BF-48DB-873A-5E20802564A4} = {52FE7FA2-9648-4BB9-AFF4-64C0C9A97E44}
{1C77608B-A3F3-412D-8AE7-05549B80726F} = {52FE7FA2-9648-4BB9-AFF4-64C0C9A97E44}
{AA2D5914-6773-45B3-B1FA-AE1648FA8BE5} = {52FE7FA2-9648-4BB9-AFF4-64C0C9A97E44}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4A8B565B-B76C-44A4-AC85-EC8FCB8ABCE1}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.7" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.


using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication()
.AddJwtBearer(options =>
{
options.Authority = "https://localhost:5001";
options.TokenValidationParameters.ValidateAudience = false;
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "api1");
});
});

var app = builder.Build();

app.UseHttpsRedirection();

app.MapGet("identity", (ClaimsPrincipal user) => user.Claims.Select(c => new { c.Type, c.Value }))
.RequireAuthorization("ApiScope");

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:6001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="IdentityModel" Version="7.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.


using IdentityModel.Client;
using System.Text.Json;

// discover endpoints from metadata
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}

// request token
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "client",
ClientSecret = "secret",
Scope = "api1"
});

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

Console.WriteLine(tokenResponse.AccessToken);

// call api
var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken!); // AccessToken is always non-null when IsError is false

var response = await apiClient.GetAsync("https://localhost:6001/identity");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
Console.WriteLine(JsonSerializer.Serialize(doc, new JsonSerializerOptions { WriteIndented = true }));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.


using Duende.IdentityServer;
using Duende.IdentityServer.Models;
using IdentityModel;

namespace IdentityServer;

public static class Config
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource()
{
Name = "verification",
UserClaims = new List<string>
{
JwtClaimTypes.Email,
JwtClaimTypes.EmailVerified
}
}
};

public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope(name: "api1", displayName: "My API")
};

public static IEnumerable<Client> Clients =>
new Client[]
{
new Client
{
ClientId = "client",

// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,

// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},

// scopes that client has access to
AllowedScopes = { "api1" }
},
// interactive ASP.NET Core Web App
new Client
{
ClientId = "web",
ClientSecrets = { new Secret("secret".Sha256()) },

AllowedGrantTypes = GrantTypes.Code,

// where to redirect to after login
RedirectUris = { "https://localhost:5002/signin-oidc" },

// where to redirect to after logout
PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },
AllowOfflineAccess = true,

AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"verification",
"api1"
}
}
};
}
Loading
Loading