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

Дейнов, Аткишкин, Рогачев #6

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
103 changes: 92 additions & 11 deletions IdentityServer/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using IdentityServer4.Models;
using System.Collections.Generic;
using IdentityServer4;

namespace IdentityServer
{
Expand All @@ -12,42 +13,122 @@ public static class Config
public static IEnumerable<IdentityResource> Ids =>
new IdentityResource[]
{
new IdentityResources.OpenId()
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResource("photos_app", "Web Photos", new []
{
"role", "subscription", "testing"
})
};

public static IEnumerable<ApiResource> Apis =>
new ApiResource[]
{
new ApiResource("api1", "My API")
new ApiResource("photos_service", "Сервис фотографий")
{
Scopes = { "scope1" }
Scopes = { "photos" },
ApiSecrets = { new Secret("photos_service_secret".Sha256()) }
}
};

public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("scope1", "My scope")
new ApiScope("photos", "Фотографии")
};

public static IEnumerable<Client> Clients =>
new Client[]
{
new Client
{
ClientId = "client",
ClientId = "Photos App by OAuth",
ClientSecrets =
{
new Secret("secret".Sha256())
},

// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "photos" }
},
new Client
{
AccessTokenLifetime = 2*60,
ClientId = "Photos SPA",
// NOTE: SPA не может хранить секрет, потому что полные исходники доступны в браузере
RequireClientSecret = false,
// NOTE: Поэтому для безопасного получения токена необходимо использовать Proof Key for Code Exchange
// Эта опция включена по умолчанию, но здесь пусть будет включена явно
RequirePkce = true,

// secret for authentication
ClientSecrets =
AllowedGrantTypes = GrantTypes.Code,

// NOTE: показывать ли пользователю страницу consent со списком запрошенных разрешений
RequireConsent = false,

// NOTE: куда отправлять после логина
RedirectUris = { "https://localhost:8001/authentication/login-callback" },

// NOTE: куда предлагать перейти после логаута
PostLogoutRedirectUris = { "https://localhost:8001/authentication/logout-callback" },

// NOTE: откуда могут приходить запросы из JS
AllowedCorsOrigins = { "https://localhost:8001" },

AllowedScopes = new List<string>
{
new Secret("secret".Sha256())
// NOTE: Позволяет запрашивать id token
IdentityServerConstants.StandardScopes.OpenId,
// NOTE: Позволяет запрашивать профиль пользователя через id token
IdentityServerConstants.StandardScopes.Profile,
// NOTE: Позволяет запрашивать email пользователя через id token
IdentityServerConstants.StandardScopes.Email,
"photos"
},

// NOTE: Надо ли добавлять информацию о пользователе в id token при запросе одновременно
// id token и access token, как это происходит в code flow.
// Либо придется ее получать отдельно через user info endpoint.
AlwaysIncludeUserClaimsInIdToken = true,

// NOTE: refresh token точно не будет использоваться
AllowOfflineAccess = false,
},
new Client
{
ClientId = "Photos App by OIDC",
ClientSecrets = { new Secret("secret".Sha256()) },

AccessTokenLifetime = 30,
AllowOfflineAccess = true,

AllowedGrantTypes = GrantTypes.Code,

// NOTE: показывать ли пользователю страницу consent со списком запрошенных разрешений
RequireConsent = true,

// NOTE: куда отправлять после логина
RedirectUris = { "https://localhost:5001/signin-passport" },

PostLogoutRedirectUris = { "https://localhost:5001/signout-callback-passport" },

AllowedScopes = new List<string>
{
// NOTE: Позволяет запрашивать id token
IdentityServerConstants.StandardScopes.OpenId,
// NOTE: Позволяет запрашивать профиль пользователя через id token
IdentityServerConstants.StandardScopes.Profile,
// NOTE: Позволяет запрашивать email пользователя через id token
IdentityServerConstants.StandardScopes.Email,
"photos_app",
"photos"
},

// scopes that client has access to
AllowedScopes = { "scope1" }
// NOTE: Надо ли добавлять информацию о пользователе в id token при запросе одновременно
// id token и access token, как это происходит в code flow.
// Либо придется ее получать отдельно через user info endpoint.
AlwaysIncludeUserClaimsInIdToken = true,
}
};
}
Expand Down
94 changes: 94 additions & 0 deletions IdentityServer/Data/IdentityServerDataExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using IdentityServer.Models;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace IdentityServer.Data
{
public static class IdentityServerDataExtensions
{
public static void PrepareData(this IHost host)
{
using (var scope = host.Services.CreateScope())
{
try
{
var env = scope.ServiceProvider.GetRequiredService<IWebHostEnvironment>();
if (env.IsDevelopment())
{
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
userManager.SeedWithSampleUsersAsync().Wait();
}
}
catch (Exception e)
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(e, "An error occurred while migrating or seeding the database.");
}
}
}

private static async Task SeedWithSampleUsersAsync(this UserManager<ApplicationUser> userManager)
{
// NOTE: ToList важен, так как при удалении пользователя меняется список пользователей
foreach (var user in userManager.Users.ToList())
await userManager.DeleteAsync(user);

{
var user = new ApplicationUser
{
Id = "a83b72ed-3f99-44b5-aa32-f9d03e7eb1fd",
UserName = "[email protected]",
Email = "[email protected]"
};
await userManager.RegisterUserIfNotExists(user, "Pass!2");
await userManager.AddClaimAsync(user, new Claim("testing", "beta"));
}

{
var user = new ApplicationUser
{
Id = "dcaec9ce-91c9-4105-8d4d-eee3365acd82",
UserName = "[email protected]",
Email = "[email protected]",
};
await userManager.RegisterUserIfNotExists(user, "Pass!2");
await userManager.AddClaimAsync(user, new Claim("subscription", "paid"));
}

{
var user = new ApplicationUser
{
Id = "b9991f69-b4c1-477d-9432-2f7cf6099e02",
UserName = "[email protected]",
Email = "[email protected]"
};
await userManager.RegisterUserIfNotExists(user, "Pass!2");
await userManager.AddClaimAsync(user, new Claim("subscription", "paid"));
await userManager.AddClaimAsync(user, new Claim("role", "Dev"));
}
}

private static async Task RegisterUserIfNotExists<TUser>(this UserManager<TUser> userManager,
TUser user, string password)
where TUser : IdentityUser<string>
{
if (await userManager.FindByNameAsync(user.UserName) == null)
{
var result = await userManager.CreateAsync(user, password);
if (result.Succeeded)
{
var code = await userManager.GenerateEmailConfirmationTokenAsync(user);
await userManager.ConfirmEmailAsync(user, code);
}
}
}
}
}
8 changes: 8 additions & 0 deletions IdentityServer/IdentityServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AspNetCore.Identity.Mongo" Version="8.3.3" />
<PackageReference Include="IdentityServer4" Version="4.1.2" />
<PackageReference Include="IdentityServer4.AspNetIdentity" Version="4.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
</ItemGroup>
</Project>
8 changes: 8 additions & 0 deletions IdentityServer/Models/ApplicationRole.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using AspNetCore.Identity.Mongo.Model;

namespace IdentityServer.Models
{
public class ApplicationRole : MongoRole<string>
{
}
}
8 changes: 8 additions & 0 deletions IdentityServer/Models/ApplicationUser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using AspNetCore.Identity.Mongo.Model;

namespace IdentityServer.Models
{
public class ApplicationUser : MongoUser<string>
{
}
}
3 changes: 3 additions & 0 deletions IdentityServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
using System;
using IdentityServer.Data;

namespace IdentityServer
{
Expand All @@ -31,6 +32,8 @@ public static int Main(string[] args)
var hostBuilder = CreateHostBuilder(args);
Log.Information("Building web host");
var host = hostBuilder.Build();
Log.Information("Preparing data");
host.PrepareData();
Log.Information("Running web host");
host.Run();
return 0;
Expand Down
Loading