Asp .net core authentication via IdentityServer4
There will not be anything unusual, one framework "IdentityServer4" will perform authentication by login and password on a certain Api, plus still process refresh_token.
It will work with the existing IdentityDbContext, IdentityUser.
The result will be a scenario in which, for each authentication, one refresh_token will be issued and saved in the PersistedGrants table. This is one of four types of OAuth 2.0 permissions:
Resource Owner Password Credentials: Used by trusted applications, such as applications that are part of the service itself.
All work on the maintenance of tokens takes on the framework.
So, let's begin.
“Clients” are set to specify the resolution method, I will have one:
DataLayer.Config
Then we sit this client in the database when it is created:
TestIdentityServer.Program
In the Initialize method, code has been added to create the necessary databases and data inserts, including the client. But before that you need to perform migrations, because you will have to create a database of 3 contexts, where the first context is IdentityDbContext ApplicationUser, and the rest for IdentityServer4:
DataLayer.DbInitializer
Migrations:
The link to the code will be at the end.
Go ahead. After setting the client and creating the database, the server can already process requests "/ connect / token" by login with a password and issue access_token with refresh_token.
According to it, with the indication of the refresh_token, refresh them.
Login password:
refresh_token
/ connect / userinfo
Now add an api which will be authorized by IdentityServer4. His connection with him will be as follows:
DataApi.Startup
The api itself will be deployed on another port.
Authorization will now be checked as usual with the attribute "[Authorize]".
/ api / Default
That's all, write who che thinks or what is missing.
Link to code .
UPD: Signature of jwt tokens
Added signature methods: RSA which is generated at start and * .pfx certificate file. The corresponding method can be switched to “appsettings.json”, the “SigningCredentialConfig” property.
It will work with the existing IdentityDbContext, IdentityUser.
The result will be a scenario in which, for each authentication, one refresh_token will be issued and saved in the PersistedGrants table. This is one of four types of OAuth 2.0 permissions:
Resource Owner Password Credentials: Used by trusted applications, such as applications that are part of the service itself.
All work on the maintenance of tokens takes on the framework.
So, let's begin.
“Clients” are set to specify the resolution method, I will have one:
DataLayer.Config
new Client
{
ClientId = _configurationManager.Value.ClientId,
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, //основной сценарий входа
RequireClientSecret = false, //Client Secret в браузере не понадобится, выключаем
AllowedScopes = { _configurationManager.Value.ApiName,
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile},//для получения инфы о пользователе по /connect/userinfo
AllowOfflineAccess = true//включает рефреш-токен
}
Then we sit this client in the database when it is created:
TestIdentityServer.Program
services.GetRequiredService<DbInitializer>().Initialize();
In the Initialize method, code has been added to create the necessary databases and data inserts, including the client. But before that you need to perform migrations, because you will have to create a database of 3 contexts, where the first context is IdentityDbContext ApplicationUser, and the rest for IdentityServer4:
DataLayer.DbInitializer
_context.Database.Migrate();
_configurationDbContext.Database.Migrate();
_persistedGrantDbContext.Database.Migrate();
if (!_configurationDbContext.Clients.Any())
{
foreach (var client in _config.GetClients().ToList())
{
_configurationDbContext.Clients.Add(client.ToEntity());
}
_configurationDbContext.SaveChanges();
}
Migrations:
dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -cPersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -cConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
dotnet ef migrations add InitialAuthMigration -cAuthContext -o Data/Migrations/IdentityServer/Auth
The link to the code will be at the end.
Go ahead. After setting the client and creating the database, the server can already process requests "/ connect / token" by login with a password and issue access_token with refresh_token.
According to it, with the indication of the refresh_token, refresh them.
Login password:
refresh_token
/ connect / userinfo
Now add an api which will be authorized by IdentityServer4. His connection with him will be as follows:
DataApi.Startup
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = settings.Authority; //Адресс сервера http://localhost:5000
options.RequireHttpsMetadata = false;
options.ApiName = settings.ApiName;//api1
});
The api itself will be deployed on another port.
Authorization will now be checked as usual with the attribute "[Authorize]".
/ api / Default
That's all, write who che thinks or what is missing.
Link to code .
UPD: Signature of jwt tokens
Added signature methods: RSA which is generated at start and * .pfx certificate file. The corresponding method can be switched to “appsettings.json”, the “SigningCredentialConfig” property.