How to use ClientRegistration in Oauth2.0 without client secret? - spring-boot

I have make authorization link using Spring Boot OAuth2.0 but I don't have client secret instead I have to use certificate. Any idea how to solve this?

You can use client assertion instead of a client secret. The client uses a certificate to prove the token request came from the client. You can use a self-signed certificate to create the client assertion
Please check this official document and upload a certificate as below
If the script for the document didn't work, please use the script below to create a self-assigned certificate.
$certroopath = "C:\Users\Administrator\Desktop"
$certname = "mycert1"
$certpassword = "P#ssw0rd1234"
$cert = New-SelfSignedCertificate -DnsName "$certname" -CertStoreLocation cert:\CurrentUser\My
$pwd = ConvertTo-SecureString -String $certpassword -Force -AsPlainText
$certwithThumb = "cert:\CurrentUser\my\"+$cert.Thumbprint
$filepath = "$certroopath\$certname.pfx"
Export-PfxCertificate -cert $certwithThumb -FilePath $filepath -Password $pwd
Utilize the ClientID and TenantID that are used while the Powershell script is running. The output from the PowerShell script should be used for the client assertion parameter.
https://login.microsoftonline.com/{TenantID}/oauth2/v2.0/token
For more information in detail, please refer below links:
Using client assertion to get access tokens from Azure AD
https://blogs.aaddevsup.xyz/2020/10/how-to-use-postman-to-perform-a-client-credentials-grant-flow-with-a-certificate/

Related

A accessToken is not valid for connecting to Azure DevOps deployment group from Windows server

In Azure Devops Server, I have created a group in Deployment Groups. A registration script was created for run in the target server. This is the generated script.
$ErrorActionPreference="Stop";If(-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() ).IsInRole( [Security.Principal.WindowsBuiltInRole] “Administrator”)){ throw "Run command in an administrator PowerShell prompt"};If($PSVersionTable.PSVersion -lt (New-Object System.Version("3.0"))){ throw "The minimum version of Windows PowerShell that is required by the script (3.0) does not match the currently running version of Windows PowerShell." };If(-NOT (Test-Path $env:SystemDrive'azagent')){mkdir $env:SystemDrive'azagent'}; cd $env:SystemDrive'azagent'; for($i=1; $i -lt 100; $i++){$destFolder="A"+$i.ToString();if(-NOT (Test-Path ($destFolder))){mkdir $destFolder;cd $destFolder;break;}}; $agentZip="$PWD\agent.zip";$DefaultProxy=[System.Net.WebRequest]::DefaultWebProxy;$securityProtocol=#();$securityProtocol+=[Net.ServicePointManager]::SecurityProtocol;$securityProtocol+=[Net.SecurityProtocolType]::Tls12;[Net.ServicePointManager]::SecurityProtocol=$securityProtocol;$WebClient=New-Object Net.WebClient; $Uri='https://go.microsoft.com/fwlink/?linkid=2066756';if($DefaultProxy -and (-not $DefaultProxy.IsBypassed($Uri))){$WebClient.Proxy= New-Object Net.WebProxy($DefaultProxy.GetProxy($Uri).OriginalString, $True);}; $WebClient.DownloadFile($Uri, $agentZip);Add-Type -AssemblyName System.IO.Compression.FileSystem;[System.IO.Compression.ZipFile]::ExtractToDirectory( $agentZip, "$PWD");.\config.cmd --deploymentgroup --deploymentgroupname "DG-Test" --agent $env:COMPUTERNAME --runasservice --work '_work' --url 'https://devops.MyCompany.com/tfs/' --collectionname 'Col-FRN-Main' --projectname 'T-MyCompany'; Remove-Item $agentZip;
I run the script then PowerShell asks me to Enter authentication type (press enter for PAT), so I enter an accessToken that is generated in Personal Access Token but PowerShell returns Enter authentication type (press enter for PAT).
I could use the accessToken for connecting Team explorer in Visual studio to my DevOps server and connecting agent pool to my DevOps server, but I have trouble connecting deployment agnet.
What's wrong?
When PowerShell asks you to Enter authentication type (press enter for PAT), you are supposed to press enter on your keyboard. Then it will prompt you to enter your Personal Access Token. Follow the prompts and you should be able to connect successfully.

How to install root certificate in aspnet:3.0 base image for windows container

I am hosting two windows containers from a Windows 2019 servers and both are running in https. When my Web URL container tried to make a call to the API container. It didn't work and when I got inside the Web container and run the curl command to my API web site and I received the following error.
(77) schannel: next InitializeSecurityContext failed: SEC_E_UNTRUSTED_ROOT (0x80090325) - The certificate chain was issued by an authority that is not trusted.
I am trying to find out how to import the root certificate to my aspnet:3.0 base image.
This is what I did to get certificates working in my docker container. I import the root certificate as well as the certificate for the application, so take the parts you need.
On your host put the certificates (pfx) into a directory and mount it within the container. I will assume you have mounted them on 'C:\certificates' in the container.
I pass the certificates as environmental variables so the script can pick them up.
Add this script to run when the container starts up:
Import-Module WebAdministration
$webCertificatePath = $ENV:WEB_CERTIFICATE_PATH
$webCertificatePassword = $ENV:WEB_CERTIFICATE_PASSWORD
$rootCertificatePaths = $ENV:ROOT_CERTIFICATE_PATHS
# I don't do anything with this... yet
$intermediateCertificatePaths = $ENV:INTERMEDIATE_CERTIFICATE_PATHS
# Import Root Certificate
# You can stop here if you only want the Root Certificate installed.
Import-Certificate -FilePath $rootCertificatePaths -CertStoreLocation 'Cert:\\LocalMachine\Root'
# Import website certificate
$mypwd = ConvertTo-SecureString -String $webCertificatePassword -Force -AsPlainText
$cert = Import-PfxCertificate -FilePath "$webCertificatePath" -Password $mypwd -CertStoreLocation 'Cert:\LocalMachine\My'
if (-not (Test-Path 'IIS:\SSLBindings\0.0.0.0!443')) {
$cert | New-Item 'IIS:\SSLBindings\0.0.0.0!443'
}
There are many ways to do this, but you get the idea.

Set-AuthenticodeSignature won't perform SHA256 Timestamp?

Signing Windows binaries on Server Core Windows Server 2019 Datacenter Edition with Visual Studio 2019 Community.
signtool.exe was not behaving correctly (issues opening PFX file), and so we were advised to switch to PowerShell + Set-AuthenticodeSignature.
Using the following commands:
$securepassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$pfx = Get-PfxData -FilePath $certificate -Password $securepassword
$cert = $pfx.EndEntityCertificates[0]
Set-AuthenticodeSignature -FilePath $target -Certificate $cert -HashAlgorithm "SHA256" -TimestampServer http://timestamp.digicert.com
results in a binary with the expected SHA256 signature, however, the Timestamp Signature is SHA1. Have also tried using http://timestamp.digicert.com?alg=sha256 as the server, however Set-AuthenticodeSignature does not add the timestamp signature at all.
Since this command doesn't allow you to specify the hash of the Timestamp algorithm, how can we achieve this?
Use another RFC3161 timestamp server. For example:
-TimestampServer "http://timestamp.comodoca.com/rfc3161"
I also see this issue in Windows 10 Enterprise when trying to use -TimestampServer "http://timestamp.digicert.com?alg=sha256" in PowerShell, despite this timestamp server working fine with signtool in the same environment.
If one flushes the local DNS cache and then observes the network interface with Wireshark, both signtool and Set-AuthenticodeSignature normally trigger a DNS lookup for the timestamp server during the signing process. This does not occur when using the DigiCert URL with Set-AuthenticodeSignature. The cmdlet seems like it may be having an issue with the ?alg=sha256 parameter and then skips the timestamp step completely.

Extend certificate expired date for windows app

How to extend the expiry date of windows app certificate? We're side loading the app/ The main obstacle is the certificate expires every year which is a bothersome to renew it through GP cause we already have issues in our environment. We would like to extend it for at least 5 years.
I have managed to find technet articles on how to create a code signing certificate but it didnt work. Visual studio doesnt accept the certificate and gives an error message that it is corrupted or invalid.
https://learn.microsoft.com/en-us/windows/uwp/packaging/create-certificate-package-signing#create-a-self-signed-certificate
https://technet.microsoft.com/itpro/powershell/windows/pki/new-selfsignedcertificate
Is there any way to do it easily?
You could do something like this, the subject must be same as UWP app's Publisher (package.appxmanifest):
New-SelfSignedCertificate -Type Custom -Subject "CN=Something" -TextExtension #("2.5.29.37={critical}{text}1.3.6.1.5.5.7.3.3", "2.5.29.19={text}") -KeyUsage DigitalSignature -FriendlyName "Friendly Name" -CertStoreLocation "Cert:\LocalMachine\My" -NotBefore (Get-Date) -NotAfter (Get-Date).AddYears(5)
Now export to .pfx and add the thumbprint to the PackageCertificateThumbprint
The process is described in Microsoft documentation, but it is convoluted. There is no "visual" part as "Visual Studio" would suggest.
To sideload an application, it is sufficient to create a self-signed certificate, which means that you trust yourself. There is no trust from a CA (certification authority) involved.
These steps worked for me. The whole process being in PowerShell run as administrator.
Create the certificate
New-SelfSignedCertificate -Type Custom -Subject "CN=Company Name, O=Company Name Inc., C=CA" -KeyUsage DigitalSignature -FriendlyName "Programming certificate, 50 years" -CertStoreLocation "Cert:\CurrentUser\My" -TextExtension #("2.5.29.37={text}1.3.6.1.5.5.7.3.3", "2.5.29.19={text}") -NotBefore (Get-Date) -NotAfter (Get-Date).AddYears(50)
The -Subject item may contain only the CN= part, I believe the other bits are optional. O= seems to refer to the organization and C= the country code.
The -CertStoreLocation and -TextExtension are correct as written (see the documentation). I am not too familiar with what -CertStoreLocation really means, as I was not able to find it later, but that is what Microsoft suggests and remains irrelevant to the process.
The (Get-Date) bits get the current date, and .AddYears(50) would be modified to how many years the certificate should last.
The output will display the thumbprint; copy it.
Export the certificate
Set a password variable (confusingly, the password here is written without quotes).
$password = ConvertTo-SecureString -String CustomPasswordYouWouldChoose -Force -AsPlainText
Export the certificate; paste the thumbprint in the "Cert:\CurrentUser\My..." string and choose a file path (in my case, using the C:\ drive worked fine).
Export-PfxCertificate -cert "Cert:\CurrentUser\My\YOURTHUMBPRINTHERE" -FilePath C:\ProgrammingCertificate.pfx -Password $password
Add the certificate in Visual Studio
Go to Package.appxmanifest > Packaging > Choose Certificate... > Select from file... > then select your exported certificate.
Install the certificate on sideload deployment
Double-click the certificate file > Install Certificate... > Local Machine > Place all certificates in the following store > Browse > Trusted People > accept all and the import should be successful. Congratulations, the application is now certified by yourself.

Does anybody know how the powershell certificate provider paths map to certmgr.msc folders?

When using powershell to investigate the Certificate Provider i noticed that all the paths seem similar but not the same as the folder structure within certmgr. It seems pretty clear that:
Certs:\LocalMachine ~= Certificates (Local Computer)
Certs:\CurrentUser ~= Certificates - Current User
I'm also guessing that:
Root ~= Trusted Root Certification Authority
My ~= Personal
WebHosting ~= WebHosting
...
But i have been unable to find any sort of official reference (or even sensible explanation) to give me the warm fuzzy I'm looking for...
My intent is to test an https WCF service locally (both server and client side). I can easily generate the self signed certificate needed by the server using New-SelfSignedCertificate. However, if I try to point my client (also .NET) at the service it fails to connect given that the service serves up a non-trusted certificate.
I have found various out-dated references (like this one), showing how I could use a combination of makecert (now deprecated), and certmgr to generate a certificate authority, then use it to sign the cert for my https service, then install the certificate authority cert into Trusted Root Certification Authority container to get everything working. While this approach would likely work, it is certainly not developer/automation friendly.
That said, I was able to use powershell to do this:
$my_cert_store_location = "Cert:\LocalMachine\My"
$root_cert_store_location = "Cert:\LocalMachine\Root"
$root_friendly_name = "Test Root Authority"
$root_cert_subject = "CN=$($root_friendly_name)"
# The ip and port you want to reserve for your app
$ipport = "127.0.0.11:8734"
# Your app guid (found in ApplicationInfo.cs)
$appid = "{f77c65bd-d592-4a7b-ae32-cab24130fdf6}"
# Your dns name
$dns_name = "my-machine-local"
$rebuild_root_cert = $false
$root_cert = Get-ChildItem $my_cert_store_location |
Where-Object {$_.SubjectName.Name.Equals($root_cert_subject)}
if ($root_cert -and $rebuild_root_cert)
{
Get-ChildItem $root_cert_store_location |
Where-Object {$_.SubjectName.Name.Equals($root_cert_subject)} |
Remove-Item
Remove-Item $root_cert
$root_cert = $false
}
if (-not $root_cert)
{
$root_cert = New-SelfSignedCertificate `
-Type Custom `
-FriendlyName $root_friendly_name `
-HashAlgorithm sha384 `
-KeyAlgorithm RSA `
-KeyLength 4096 `
-Subject $root_cert_subject `
-KeyUsage DigitalSignature, CertSign `
-NotAfter (Get-Date).AddYears(20) `
-CertStoreLocation $my_cert_store_location
Write-Output "Created root cert: $($root_cert.Thumbprint)"
$exported_cert = New-TemporaryFile
Export-Certificate -Cert $root_cert -FilePath $exported_cert.FullName
$imported_root_cert = Import-Certificate -FilePath $exported_cert.FullName `
-CertStoreLocation $root_cert_store_location
Write-Output "Imported root cert to: $($root_cert_store_location)\$($imported_root_cert.Thumbprint)"
}
Write-Output "Root cert is: $($root_cert.Thumbprint)"
$test_signed_cert_subject = "CN=$($dns_name)"
$test_signed_cert = Get-ChildItem $my_cert_store_location |
Where-Object {$_.SubjectName.Name.Equals($test_signed_cert_subject)}
if (-not $test_signed_cert)
{
$test_signed_cert = New-SelfSignedCertificate `
-Type Custom `
-Subject $test_signed_cert_subject `
-FriendlyName $dns_name `
-Signer $root_cert `
-CertStoreLocation $my_cert_store_location
Write-Output "Created signed cert: $($test_signed_cert.Thumbprint)"
}
Write-Output "Signed cert is: $($test_signed_cert.Thumbprint)"
if ($test_signed_cert)
{
netsh http delete sslcert `
ipport="$($ipport)"
netsh http add sslcert `
ipport="$($ipport)" `
appid="$($appid)" `
certstorename="My" `
certhash="$($test_signed_cert.Thumbprint)"
Write-Output "Assigned signed cert to: $($ipport)"
}
But the question still stands... Is there any information about how the certificate provider paths map to certmgr folders?
Here is the mapping between containers (in parentheses) and their description:
Personal (My) — This container is used to store certificates with private keys. When a certificate private key is used, the application looks to this container to find the appropriate certificate and associated private key.
Trusted Root Certification Authorities (ROOT) — This container contains trusted, self-signed certificates without private keys. Each certificate chain must chain up to a certificate presented in self-signed form. This self-signed certificate is the ‘root certificate’ or ‘trusted anchor.’ However, not all root certificates can be considered as trusted. You should carefully choose which new certificates you will consider as trusted.
Enterprise Trust (trust) — This container is used to store Certificate Trust Lists (CTL). For example, the Key Management Server adds its certificate to this container.
Intermediate Certification Authorities (CA) — This container keeps many different types of CA certificates. These certificates are usually used by the certificate chaining engine to build certificate chains.
Trusted Publishers (TrustedPublisher) — This container keeps explicitly trusted signing certificates. While the digital signature certificate chains up to the trusted root certification authority, many applications (such Microsoft Office and Windows PowerShell) are required to store a particular signing certificate in this container in order to trust signatures from that particular signer. This means that a digital signature-aware application can trust one signing certificate but not trust another signing certificate even if both certificates are issued by the same certification authority.
Untrusted Certificates (Disallowed) — This container keeps explicitly untrusted certificates. If you decide to not trust either a particular certificate or all certificates issued by a particular certification authority, just add these certificates to this container. By default, this container already contains two certificates. It is strongly recommended to NOT REMOVE them from the container. For additional info read the following article: http://support.microsoft.com/kb/293817.
Third-Party Root Certification Authorities (AuthRoot) — This certificate container is similar to the Trusted Root Certification Authorities. It keeps the certificates from the Microsoft Root Certificate Program. For more information about the Microsoft Root Certificate program, read the following article: http://support.microsoft.com/kb/931125.
Trusted People (TrustedPeople) — This container keeps certificates issued to people or end entities that are explicitly trusted. Most often, these are self-signed certificates or certificates explicitly trusted in an application such as Microsoft Outlook. To share an EFS–encrypted file with other parties, you must have their certificate in this store.
Certificate Enrollment Requests (REQUEST) — This container stores certificate enrollment requests until these requests are submitted to the certification authority. When a certification authority issues a certificate in response to a request, you need to install the certificate to this container using a special utility, such CertReq.exe. After that, the certificate enrollment request is transferred to the Personal (My) container as a certificate.
Smart Card Trusted Roots (SmartCardRoot) — This container is used to store trusted smart card certificates.
Other People (AddressBook) — This container maintains certificates that have been added to an Outlook contact.
Active Directory User Object (UserdDS) — This container is used to store certificates associated with a user object and published in Active Directory. The content of this container is equal to the certificates that are shown in the advanced view of the Active Directory Users and Computers console when the properties of a user object are viewed.

Resources