Certificate for AddSigningCredential - identityserver4

I am new in IdentityServer4 and trying to create JSON Web token. For development I have used AddDeveloperSigningCredential but for other environments I need to use AddSigningCredential but I do not know how to get certificate. I don't have any certificate actually and not sure how can I generate it? Can anyone provide some inputs how to generate certificate and use with AddSigningCredential and then after creation of token, how can I validate token using same certificate in API
After generation of certificate as described in comments. I have added following code
Code in identity server
services.AddIdentityServer() .AddAspNetIdentity() .AddConfigurationStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, opt => opt.MigrationsAssembly(migrationAssembly)); }) .AddOperationalStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, opt => opt.MigrationsAssembly(migrationAssembly)); }) .AddSigningCredential(certificate);
Code in API
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "localhost:44339"; });
Issuer is
{"issuer":"localhost:44339","jwks_uri":"https://…" I have fetched this information from
https://localhost:44339/.well-known/openid-configuration
I am getting 401 error in postman and getting error is WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'policyservice' is invalid"

You can use any tool that can generate a private/public key pair.
In the example below I use openssl.
First we create a RSA private key:
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -aes256 -out rsa-private-key.pem
Then you can create a certificate using :
openssl req -new -x509 -key rsa-private-key.pem -days 365 -subj "/CN=MyRSACert" -out rsa-cert.crt
Then you can package up the cert and private key into a .pfx file:
openssl pkcs12 -export -inkey rsa-private-key.pem -in rsa-cert.crt -out rsa.pfx
Then in code you can load the cert using:
var rsaCert = new X509Certificate2("rs256.pfx", "yourpassword");
Then to add it to IdentityServer you can use:
services.AddIdentityServer()
...
.AddSigningCredential(rsaCert)

Related

axios bypass TLS certificates error. No solution at all for FRONT END (React)

[EDIT] : one answer below
trying to call my node https backend from react using axios (of fetch)...
Always facing certificate errors for self signed ones. Can "by pass" the REJECT_UNAUTORIZED error by setting NODE_TLS_REJECT_UNAUTHORIZED=0 when starting the react app, but this is clearly not the solution. I'm also facing different messages such as ERR_CERT_COMMON_NAME_INVALID.
Worth to mention that everything is running fine when using postman, when activating the certificate verification and uploading my self signed CA PEM certificate in postman.
I tried to do the same in chrome (uploading the self signed CA PEM certificate in the root CA Store) but without luck. Still the warning...
Of course I tried the solution to add an https agent (see code below), but this is also not fixing the issue.
That solution seems to be fine for NODE apps, but not from Front End apps in React or any other language,..
So what is the solution ? How we can request a local self signed https backend server from react without these warnings ?
There are millions of issues like this reported here or in axios github, but still no viable solution ?
Thks
axios.defaults.httpsAgent = new https.Agent({
rejectUnauthorized: false,
port: 443,
});
const tokensData = await axios.post<TLoginApi, AxiosResponse<TLoginApi, any>, TLoginDTO>(
`${process.env.AUTH_URL}/login`,
credentials,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
// or this but failed anyway httpsAgent: new https.Agent({
rejectUnauthorized: false,
port: 443,
}),
}
);
answering my own question.
To avoid using NODE_TLS_REJECT_UNAUTHORIZED=0, you need to create your self sign certificate.
The main issues I was facing was related to LOCALHOST and GOOGLE CHROME (at least release 108) , because my test backend is in same dev machine.
I came up with a solution to generate self signed certificate that is OK for Google Chrome with domain like 'localhost'.
When generating the server certificate, you need to add an extension file that is adding some DNS and the IP address (IP4 & IP6) of 'localhost'.
Also important to import your root CA in Chrome to avoid Reject unauthorized...
steps to create CA and certificates
1- generate your root CA. It has to be imported in Google Chrome
openssl req -x509 -newkey rsa:4096 -days 999 -keyout ca-key.pem -out ca-cert.pem -subj "/C=US/ST=Oregon/L=City/O=whatevev/OU=whatevev/CN=your name if you want/emailAddress=test#test.com"
2- generate the server private key and CSR
openssl req -newkey rsa:4096 -keyout server-key.pem -out server-req.pem -subj "/C=US/ST=Oregon/L=City/O=whatevev/OU=whatevev/CN=your name if you want/emailAddress=test#test.com"
3- finaly generate the server key, with some additional conf (see below)
openssl x509 -req -days 999 -in server-req.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extfile server-ext.conf
example of server-ext.conf file that prevent chrome from complaining about wrong DNS or anything else
can fine more information about this extension file HERE
subjectAltName=DNS:test.home,DNS:localhost.home,DNS:localhost,IP:0.0.0.0,IP:127.0.0.1,IP:::1
Finally, on your BACKEND, you can configure your nodejs express server using your root CA and the certificate/key :
const httpsOptions: https.ServerOptions = {
key: fs.readFileSync(
path.join(__dirname, "auth", "certificats", "server-key.pem")
),
cert: fs.readFileSync(
path.join(__dirname, "auth", "certificats", "server-cert.pem")
),
ca: fs.readFileSync(
path.join(__dirname, "auth", "certificats", "ca-cert.pem")
),
passphrase: "passpahrase of root CA,
};

ITfoxtec SAML 2.0 Azure Ad Certificate Format Issue .Cer to .PFX

I'm trying to implement SSO SAML authentication in .Net Core 3.1 with Azure AD
Following this Guid Here
My questions are:
Can I remove the code that refers to SigningCertificatePassword (.pfx file) and add reference to my .cer file because Azure Ad only Give .cer/.pem files and while ITfoxtec SAML 2.0 only support .PFX file so How can I convert those files?
A PFX is a complete bundle (Keystore) consisting of a certificate and its private key. So if you have got both then you can add those entities to the Keystore.
openssl pkcs12 -inkey private_key.pem -in certificate.cert -export -out keystore.pfx
A PXT certificate contain both the privat and public key. a DER certificate only contain the public key.
You need to create you own PXT certificate for your application or possible use the same certificated used for TLS/SSL.
.NET sample code which show how to create a certificate in .NET:
https://github.com/ITfoxtec/FoxIDs.Samples/blob/b6dd1f8211015a5b366ce2b062dde481e38848fc/src/FoxIDs.SampleHelperLibrary/TestCertificate.cs
using (var rsa = RSA.Create(2048))
{
var certRequest = new CertificateRequest(
$"CN={cn}, O=FoxIDs",
rsa,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
certRequest.CertificateExtensions.Add(
new X509BasicConstraintsExtension(false, false, 0, false));
certRequest.CertificateExtensions.Add(
new X509SubjectKeyIdentifierExtension(certRequest.PublicKey, false));
certRequest.CertificateExtensions.Add(
new X509KeyUsageExtension(
X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyAgreement,
false));
var now = DateTimeOffset.UtcNow;
var cert = certRequest.CreateSelfSigned(now.AddDays(-1), now.AddYears(100));
File.WriteAllBytes(PfxFile(path, cn), cert.Export(X509ContentType.Pfx));
File.WriteAllBytes(CrtFile(path, cn), cert.Export(X509ContentType.Cert));
}

Starting a react app in HTTPS instead of HTTP

I want to know how to start a react app which was made using the create-react-app command in https instead of HTTP?
Use something like Root SSL certificate
Generate a key
openssl genrsa -des3 -out rootCA.key 2048
With they key you can generate a certificate which is good for 1,024 days
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
Open keychain access on your Mac and go to the certificates category and emport that rootCA.pem generated from the last step. Double click and under "When using this certiciate" select 'Always Trust'
Create an OpenSSL configuration file
server.csr.cnf
[req]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn
[dn]
C=US
ST=RandomState
L=RandomCity
O=RandomOrganization
OU=RandomOrganizationUnit
emailAddress=hello#example.com
CN = localhost
Create a v3.ext file to create a X509 v3 certificate.
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = #alt_names
[alt_names]
DNS.1 = localhost
Create a certificate key for localhost using the configuration settings stored in server.csr.cnf. This key is stored in server.key.
openssl req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config <( cat server.csr.cnf )
A certificate signing request is issued via the root SSL certificate we created earlier to create a domain certificate for localhost. The output is a certificate file called server.crt.
openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 500 -sha256 -extfile v3.ext
You’re now ready to secure your localhost with HTTPS. Move the server.key and server.crt files to an accessible location on your server and include them when starting your server.
In an Express app written in Node.js, here’s how you would do it. Make sure you do this only for your local environment. Do not use this in production.
var path = require('path')
var fs = require('fs')
var express = require('express')
var https = require('https')
var certOptions = {
key: fs.readFileSync(path.resolve('build/cert/server.key')),
cert: fs.readFileSync(path.resolve('build/cert/server.crt'))
}
var app = express()
var server = https.createServer(certOptions, app).listen(443)
Check https://github.com/dakshshah96/local-cert-generator/ for more detailed instructions
Adding on to the solution provided by Mark, to import the certificate you must click File > Import Items. Then, search for the certificate on your hard drive. After doing so you can proceed with the remaining steps.

IdentityServer4 AddSignerCredentials RSA example

Getting ready to move our IdentityServer4 setup from dev to test and I need to get the AddSignerCredentials() piece migrated from AddDeveloperCredentials(). I can generate a private and public RSASecurityKey but I'm unclear as to what RsaSecurityKey to pass to AddSignerCredentials(). The discovery endpoint somehow knows about the public key, but we'd want to sign tokens with the private key. Neither seems to work
Is there an example of how to use this somewhere in the documentation that I missed?
Use openSSL to create the certificate using the following demo command in your command prompt:
->OpenSSL req -x509 -newkey rsa:4096 -sha256 -nodes -keyout
IdentityServer4.key -out IdentityServer4.crt -subj
"/CN=IdentityServer4.com" -days 3650
->OpenSSL pkcs12 -export -out IdentityServer4.pfx -inkey
IdentityServer4.key -in IdentityServer4.crt -certfile IdentityServer4.crt
Install that certificate to your current user profile.
Replace
AddDeveloperSigningCredential()
with
AddSigningCredential("ThumbprintOfCertificate", StoreLocation.CurrentUser,NameType.Thumbprint)
That's it.

Check if connection exists to a flat database in Matlab

I have used Postgres and love its way to handle the database connection.
I have to use now Matlab and Physionet's flat database system to retrieve data.
However, I do not understand the logic in some cases, like in ptbdb.
How can you check if a connection exists to a database in Matlab?
How can you monitor what the system is doing when connecting to the database?
It would be very nice to be able to ping the system or something like that to know what is the problem. I get no information now what is the problem.
My connection was disconnected continuously because it was not secure.
The topic is about secure connection between Matlab and PostgreSQL, which is undocumented widely, for instance, discussed here about Secure SSL connection between Matlab and PostgreSQL.
Summary of the blog post
Make appropriate changes in
Generate certificate for the server; diseserver.csr, root.crt; postgreSQL directry (diseserver.key, diseserver.crt, and root.crt); please see more precisely here
postgresql.conf
pg_hba.conf
generate client certificates
convert key to pkcs8 format
check correct version of JDBC driver
check client certificate
dbtest.m
Certificate for the server
$openssl req -out diseserver.csr -new -newkey rsa:2048 -nodes -keyout diseserver.key
postgresql.conf
ssl = on
ssl_cert_file = 'diseserver.crt' # (change requires restart)
ssl_key_file = 'diseserver.key' # (change requires restart)
ssl_ca_file = 'root.crt' # (change requires restart)
pg_hba.conf
hostnossl all all 0.0.0.0/0 reject
hostssl mytable all 0.0.0.0/0 cert map=ssl clientcert=1
Generate client certificates
$mkdir ~/.postgresql
$cd ~/.postgresql
$openssl req -out postgresql.csr -new -newkey rsa:2048 -nodes -keyout postgresql.key
Convert key to pkcs8 format
$openssl pkcs8 -topk8 -inform PEM -outform DER -in postgresql.key -out postgresql.pk8 -nocrypt
Check client certificate
jdbc:postgresql://diseserver.mydomain.org/mytable?ssl=true&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory&sslmode=verify-full&
dbtest.m matlab function
function dbtest
driver = 'org.postgresql.Driver';
[~,username] = system('whoami');
url = 'jdbc:postgresql://diseserver.mydomain.org/mytable?ssl=true&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory&sslmode=verify-full&';
myconn = database('mytable', username, '', driver, url);
if ~isempty(myconn.Message)
fprintf(2,'%s\n', myconn.Message);
else
fprintf(1, 'Connected!\n');
end
end

Resources