Single Sign-On (SSO) in .NET
Adiel Alfonso Cordovi
Software Engineer .NET+ | ASP.NET | ANGULAR | RESTFUL | gRPC | WEB | SQL SERVER
?? Single Sign-Out (SSO) is an authentication system that allows users to access multiple systems with a single instance of identification. ??
?? With SSO, users can enter their data, such as username and password, only once, thus freeing up any remaining access between related software systems.
?? Let's analyze the following case.
?? If you have a JWT authentication service where all the users of a company are stored and you want to integrate it into several independent backend applications written in .NET to access their resources, you can do this by configuring each application to accept and validate issued JWT tokens.
???? If the tokens are issued using an X509 certificate you can validate that it belongs to a chain of trust. The use of certificates is recommended for this type of operations.
?? Here is a basic configuration of how to achieve it.
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
public void ConfigureServices(IServiceCollection services) {?
// Load the root certificate of the trust chain from a file
var rootCertificate = new X509Certificate2("root_certificate.cer");
// Create an X509Chain object to validate the certificate chain
var chain = new X509Chain();
chain.ChainPolicy.ExtraStore.Add(rootCertificate);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;?
// Configure the JWT authentication middleware
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true, ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKeyResolver = (token, securityToken, kid, parameters) =>
{
// Get the security token as a JWT token
var jwtToken = (JwtSecurityToken)securityToken;
// Get the issuer's certificate from the JWT token
var base64EncodedCert = jwtToken.Header["x5c"][0].ToString();
var issuerCertificate = new X509Certificate2(Convert.FromBase64String(base64EncodedCert));
// Validate the issuer's certificate chain
if (!chain.Build(issuerCertificate))
{
throw new SecurityTokenInvalidIssuerException("La cadena de certificados del emisor no es válida");
}
// Return the public key of the issuer's certificate
return new[] { new X509SecurityKey(issuerCertificate) };
}
};
});
// ...
}?
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Habilitar la autenticación app
app.UseAuthentication();
// ...
}
??You can apply the same settings to all apps that authenticate using the same provider.
?? In this example, a root certificate is loaded from a file and used to validate the certificate chain of the issuer of the JWT token. The root certificate is loaded using the X509Certificate2 class and added to the ExtraStore of the object X509Chain that is used to validate the certificate chain.
?? The JWT authentication middleware is then configured to use a custom function (IssuerSigningKeyResolver) to resolve the issuer's signing key. This function is called every time a JWT token is received and is responsible for getting the issuer's certificate from the token, validate its certificate chain using the X509Chain object, and return the public key of the issuer's certificate.
领英推荐
?? Once you have configured the JWT authentication middleware in your backend application, you can use the attribute [Authorize] in your controller actions to restrict access to protected resources. You can also use the [Authorize] attribute with the Roles parameter to restrict access based on user roles.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MyApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
[Authorize(Roles = "Admin")]
public IActionResult GetProtectedResource()
{
// Action protected by the [Authorize] attribute
// Only authenticated users with the "Admin" role can access this resource
// ...
}
}
}
?? In this example, the [Authorize] attribute with the Roles parameter is applied to the GetProtectedResource action of the controller MyController. This means that only authenticated users with the "Admin" role can access this resource. If a user does not authenticated user or an authenticated user without the "Admin" role attempts to access this resource, a 401 Unauthorized response is returned.
?? It remains to be clarified that the role can travel in a claim in the payload of a JWT token.
?? Basic overview of how to integrate a JWT authentication service into several standalone backend applications written in .NET to access their resources using an X509 certificate that belongs to a chain of trust and authorization by roles.
?? If you log into a system and are already authenticated, the authentication system will issue a JWT token that contains information about your identity and permissions. This token will be sent to the client (for example, your web browser) and stored there for later use.
?? When you try to access a protected resource in another application that is configured to accept and validate tokens issued by the authentication system, the client will send the stored JWT token along with the request to the protected resource. The app will receive the token and validate it to make sure it's valid and issued by the trusted authentication system. If the token is valid and you have the necessary permissions to access the requested resource, the application will process the request and allow you to access the resource.
?? In short, when you log into a system and are already authenticated, the authenticating system issues a JWT token that is stored on the client and sent along with requests to protected resources in other applications. These applications validate the token to ensure that it is valid and you have been authenticated by the authentication system before allowing you to access the protected resources.
Marketing Manager at ICode Breakers
1 年Discover the privacy implications of Single Sign-On (SSO), the significance of implementing strong data protection measures, and the necessity of aligning SSO systems with diverse regulations. To learn more, read this blog at https://www.loginradius.com/blog/identity/legal-implications-of-sso/.