ASOS - Token validation is not working when having separate authorization server and the resource server - asp.net-core

I'm trying to impement the OpenID Connect server (resource owner password credentials grant) with ASOS by this post.
Everything works fine when I have both Authorization server and resource server in one app. But when I split them on two apps (but on one machine) resource server fails to validate token and returns The access token is not valid.
I downloaded the source code of AspNet.Security.OAuth.Validation to investigate the issue and it returns null here
Here are some logs from Authorization Server:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 POST http://localhost:5000/connect/token application/x-www-form-urlencoded; charset=UTF-8 77
info: AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware[0]
The token request was successfully extracted from the HTTP request: {
"grant_type": "password",
"username": "UserLogin",
"password": "[removed for security reasons]",
"scope": "offline_access"
}.
info: AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware[0]
The token request was successfully validated.
trce: AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware[0]
A sign-in operation was triggered: sub: 123, username: UserLogin ; [.scopes, ["email","profile","offline_access"]], [.resources, ["resource_server"]].
dbug: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[37]
Reading data from file 'C:\Users\User1\AppData\Local\ASP.NET\DataProtection-Keys\key-********-****-****-****-64bb57db1c3b.xml'.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[18]
Found key {********-****-****-****-64bb57db1c3b}.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver[13]
Considering key {********-****-****-****-64bb57db1c3b} with expiration date 2017-09-27 16:44:49Z as default key.
dbug: Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor[51]
Decrypting secret element using Windows DPAPI.
dbug: Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorDescriptor[4]
Opening CNG algorithm 'AES' from provider '(null)' with chaining mode CBC.
dbug: Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorDescriptor[3]
Opening CNG algorithm 'SHA256' from provider '(null)' with HMAC.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider[2]
Using key {********-****-****-****-64bb57db1c3b} as the default key.
trce: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector[31]
Performing protect operation to key {********-****-****-****-64bb57db1c3b} with purposes ('C:\Users\User1\documents\visual studio 2017\Projects\OpenIdDictSample\Aka.OpenIdConnectServer', 'OpenIdConnectServerHandler', 'AccessTokenFormat', 'ASOS').
trce: AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware[0]
A new access token was successfully generated using the specified data format: CfDJ8NSKICBGwihOm75ku1fbHDtG4usEbfF-mLGaJcGGFEPQJLb36rfHqCTJ3Clu_SCBRHlaZ_B7s3pxNfUqS9fPfjtjjEH1KKmkiV6gvakRYf0Iof32BVddUUPgd7sEDrB0fET91pIDJT9WwsPx653viw5tFyvrztsSD5CYAOQZjm1werRcVPuvwRhXUQb_9Vbba52tqj8y7WbOjk78Hl17knbwSz4C70vwlRU5pL_Bp41R4vEEKwtm_VMQ_u1kSBKM5KjOh6OKdbDJ9jOhyh4RpNbvGN25ZskzByi8ndKRW3dmajWYyf-0cj6-4MEE5Hocd47te8C-haYIxEUb7tcQ-JTItknIiE1sk6W7zHlhLg3nprE2Ct4mvKi11G7Kvd1W4u-UmEvL1NesjVFNKpNJVdEaK2I8mcNzJLU69ZnM4poRrLqEqD__cHa8nCFgPtE9L0Jyo6IyFwc7NZ2sXz7y7lPfJ9Q3Pu1W_t0lOGBte5uKHfJZpiOYaqKrAwdJSpULLK52iKoCNhRYxOSdq__DNJs ; sub: 123, username: UserLogin ; [.scopes, ["email","profile","offline_access"]], [.resources, ["resource_server"]], [.issued, Fri, 30 Jun 2017 09:13:29 GMT], [.expires, Fri, 30 Jun 2017 10:13:29 GMT], [.token_id, e27cbb46-d1ea-4576-8803-dddc001b3fc8], [.audiences, ["resource_server"]].
trce: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector[31]
Performing protect operation to key {********-****-****-****-64bb57db1c3b} with purposes ('C:\Users\User1\documents\visual studio 2017\Projects\OpenIdDictSample\Aka.OpenIdConnectServer', 'OpenIdConnectServerHandler', 'RefreshTokenFormat', 'ASOS').
trce: AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware[0]
A new refresh token was successfully generated using the specified data format: CfDJ8NSKICBGwihOm75ku1fbHDtcKlYz_IbJiNmiW_tfu19E7p5BIO9xE0b2qu8mYWw-zD7wCWB1F5Fx548L4FARrsJwlJls1AkK2GrqXjV0krH6me_btsSAxM9trrFCUL2ZrXkm2sStZ6DUcbf_cSNFh-YxXft-gbLGV11THAINTb8K9-v_fkeXq7aN8Qgu7zJfhON1ehflLwZ-DXZwW_S9assqx8f7oe-n5gTzOO6PjEyO5g0YMJ1SY7X-sMO1MKjn03vZxPB0ecT0l8NXB89vGhW7kZnoEaL1NwmSTiEOYMatwrkURPBgb2YLnpiu7sYAD04HxsicoLaQTDbc8ZJyWUJ7guLl6Mp2HLhZG_wLQM9REC_QeZX8eDn8aqSOiGKZeLF4G7A5y369VIZ0RPASdTpEsAHSE8ws0RB18jap-75bM_aAi3w3-PlfnY7ySnDYm3xkF1ImyBcph2XF6R8-imdAXhQG-tTAYd2FKw4msaWCPcnX5CxYlo-alVYpd878haDvo43fCvbd2_Dc2O1wI98 ; sub: 123, username: UserLogin ; [.scopes, ["email","profile","offline_access"]], [.resources, ["resource_server"]], [.issued, Fri, 30 Jun 2017 09:13:29 GMT], [.expires, Fri, 14 Jul 2017 09:13:29 GMT], [.token_id, c0cf40ad-cd47-4c82-9e37-6943cda95ffc].
info: AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware[0]
The token response was successfully returned: {
"resource": "resource_server",
"scope": "email profile offline_access",
"token_type": "Bearer",
"access_token": "[removed for security reasons]",
"expires_in": 3600,
"refresh_token": "[removed for security reasons]"
}.
Here are some logs from Resource Server:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5001/api/values
trce: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector[5]
Performing unprotect operation to key {********-****-****-****-64bb57db1c3b} with purposes ('C:\Users\User1\documents\visual studio 2017\Projects\OpenIdDictSample\Aka.WebApi', 'OpenIdConnectServerHandler', 'AccessTokenFormat', 'ASOS').
dbug: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[37]
Reading data from file 'C:\Users\User1\AppData\Local\ASP.NET\DataProtection-Keys\key-********-****-****-****-64bb57db1c3b.xml'.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[18]
Found key {********-****-****-****-64bb57db1c3b}.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver[13]
Considering key {********-****-****-****-64bb57db1c3b} with expiration date 2017-09-27 16:44:49Z as default key.
dbug: Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor[51]
Decrypting secret element using Windows DPAPI.
dbug: Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorDescriptor[4]
Opening CNG algorithm 'AES' from provider '(null)' with chaining mode CBC.
dbug: Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorDescriptor[3]
Opening CNG algorithm 'SHA256' from provider '(null)' with HMAC.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider[2]
Using key {********-****-****-****-64bb57db1c3b} as the default key.
info: AspNet.Security.OAuth.Validation.OAuthValidationMiddleware[7]
Bearer was not authenticated. Failure message: Authentication failed because the access token was invalid.
1) What is wrong with my resource server?
2) How to configure the resource server on different machine (especially token signing/checking and encryption/decryption)?

How to configure the resource server on different machine (especially token signing/checking and encryption/decryption)?
You need to make sure the key ring (containing the master keys that are derived by ASP.NET Core Data Protection to create encryption and validation keys) is correctly synchronized and shared by both your authorization server and your resource server(s). The procedure is described here: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview.
Here's an example of how it could be done using a shared folder:
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(#"\\server\share\directory\"))
}
You'll also need to configure the two applications to use the same "application discriminator":
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(#"\\server\share\directory\"))
.SetApplicationName("Your application name");
}

Related

Asp Net Core 3 Sample with 503 Service Unavailable

When creating a new ASP.NET Core Web Application using react and .Net Core 3.0 or 3.1 in visual studio and run the application the page shows:
503 Service Unavailable
Failed to connect to server localhost
I am using windows 10 professional and visual studio 2019.
The error happens running in IISExpress and kestrel.
On a different machine this works fine.
Creating a template using "Web Application (Model-View-Controller)" works.
The api call works (https://localhost:5001/WeatherForecast).
I'm troubleshooting a migration in a project from AspNet Core 2.2 to 3.0 with the same error, I checked to see if the template project would work and found out that the error was not specific to the migration. Figuring out why the template is not working will probably solve the error with the migration.
Edit:
Disabling firewall did not solve issue.
Here is the debug log for trying to open the page:
dbug: Microsoft.AspNetCore.Server.Kestrel[39]
Connection id "0HLTKHV201G3Q" accepted.
dbug: Microsoft.AspNetCore.Server.Kestrel[1]
Connection id "0HLTKHV201G3Q" started.
dbug: Microsoft.AspNetCore.Server.Kestrel[39]
Connection id "0HLTKHV201G3R" accepted.
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/
dbug: Microsoft.AspNetCore.Server.Kestrel[1]
Connection id "0HLTKHV201G3R" started.
trce: Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware[2]
All hosts are allowed.
dbug: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[4]
The request path / does not match a supported file type
dbug: Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1000]
No candidates found for the request path '/'
dbug: Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware[2]
Request did not match any endpoints
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 27.156ms 503 text/html; charset=UTF-8
dbug: Microsoft.AspNetCore.Server.Kestrel[10]
Connection id "0HLTKHV201G3Q" disconnecting.
dbug: Microsoft.AspNetCore.Server.Kestrel[2]
Connection id "0HLTKHV201G3Q" stopped.
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[6]
Connection id "0HLTKHV201G3Q" received FIN.
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[7]
Connection id "0HLTKHV201G3Q" sending FIN because: "The Socket transport's send loop completed gracefully."
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/favicon.ico
trce: Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware[2]
All hosts are allowed.
dbug: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[5]
The request path /favicon.ico does not match an existing file
dbug: Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1000]
No candidates found for the request path '/favicon.ico'
dbug: Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware[2]
Request did not match any endpoints
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 19.8075ms 503 text/html; charset=UTF-8
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[6]
Connection id "0HLTKHV201G3R" received FIN.
dbug: Microsoft.AspNetCore.Server.Kestrel[10]
Connection id "0HLTKHV201G3R" disconnecting.
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets[7]
Connection id "0HLTKHV201G3R" sending FIN because: "The client closed the connection."
dbug: Microsoft.AspNetCore.Server.Kestrel[2]
Connection id "0HLTKHV201G3R" stopped.
This was happening because proxy was blocking requests from .Net Host to react and angular.
In AspNetCore 3.0 HttpClient now has a default proxy created from system variables HTTPS_PROXY, HTTP_PROXY and NO_PROXY.
Adding NO_PROXY=localhost to system variables solved my problem.

Kong Api Gateway - HMAC Signature does not Match

I am trying to implement HMAC Authentication with Kong,
I am getting error “HMAC Signature does not match” .
I am making HTTP request using Postman Rest Client.
Can some one verify my request parameter below.
Credential of Consumer:
Username: "test"
Secret: "test123#"
Http Request Detail:
Date:Thu, 05 Sep 2019 09:56:28 GMT
host:172.17.0.3
Authorization: hmac username="test",algorithm="hmac-sha1",headers="date",signature="YTg5NmQwMjhmMzVmYWNhZmQyZTQwNmY5ZTVkMmUzNDM4NDAxNmY3MA=="
Http Response:
Http Code:401
Response Body:
{
message:"HMAC Signature does not match"
}
I did generation for signing string "Date: Thu, 05 Sep 2019 09:56:28 GMT". Yes you need space after date.
The signature should be MduuZsP0dKRPKGoMSTft/fT+Qmc= for hmac-sha1 secret is "test123#"
I made this document for anyone who might need it (relating to kong hmac).

Could not create SSL/TLS secure channel - Connecting Microsoft Flows with HTTP request

I am a new user for Microsoft Flows.
I have a requirement for Connecting the Microsoft Flow with HTTP Request.
When connecting the HTTP Request, I am using the Client Certificate with the .pfx certificate file.
I am using the below format :
{
"type": "ClientCertificate",
"pfx": "aGVsbG8g...d29ybGQ=",
"password": "myPassword"
}
I am adding the pfx file in Base64 Encoding Format and Password in Plain Text format.
While running the Flow, I get the below error :
BadRequest. Http request failed with status code 'SecureChannelFailure'
and status message: 'The request was aborted: Could not create SSL/TLS secure
channel.'.
Please help me to resolve this issue and correct the SSL/TLS Secure Channel Error.
Thanks,
:)

FIWARE CEP (Proton) REST ouput authentication error

I'm training to send an output event from FIWARE CEP (Proton), using the REST consumer, to an ActiveMQ queue. The credential for access the ActiveMQ queue are included in the URL, as http://user:passwrd#X.X.X.X:xxxx/api/message/myqueue, but I have the following error:
com.ibm.hrl.proton.webapp.resources.EventResource submitNewEvent
INFO: events sent to proton runtime...
org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: basic authentication scheme selected
org.apache.commons.httpclient.HttpMethodDirector processWWWAuthChallenge
INFO: No credentials available for BASIC 'ActiveMQRealm'#X.X.X.X
com.ibm.hrl.proton.server.executorServices.SimpleThreadFactory$ProtonExceptionHandler uncaughtException
SEVERE: Uncaught exception in thread: Thread[4,5,main],exception: com.ibm.hrl.proton.adapters.rest.client.RESTException: com.ibm.hrl.proton.adapters.rest.client.RESTException: Could not perform POST of event instance: ...
with request headers:
Content-Type: text/plain
User-Agent: Jakarta Commons-HttpClient/3.0
Host: X.X.X.X:xxxx
Content-Length: 389
to consumer http://user:passwrd#X.X.X.X:xxx/api/message/myqueue, responce result: 401
Seems like that Proton doesn't extract the credential from the URL.
Anyone else had the same problem?
You can add to the CEP REST consumer definition an AuthToken parameter.
From the CEP user guide (can be found here):
AuthToken – an optional parameter. When set, it is added as an X-Auth-Token
HTTP header of the request.

gss_acquire_cred returning Key table entry not found error

I have been trying to follow the guidelines in this Microsoft article to authenticate
against Apache with Kerberos and AD. I have successfully tested the communication between the apache server and the AD server with kinit. However when I attempt to access a restricted page on the server with IE I get an Internal server error and the following appears in the apache error log.
[Wed Sep 24 14:18:15 2008] [debug] src/mod_auth_kerb.c(1483): [client 172.31.37.38] kerb_authenticate_user entered with user (NULL) and auth_type Kerberos
[Wed Sep 24 14:18:15 2008] [debug] src/mod_auth_kerb.c(1174): [client 172.31.37.38] Acquiring creds for HTTP/srvnfssol1.dev.local#DEV.LOCAL
[Wed Sep 24 14:18:15 2008] [error] [client 172.31.37.38] gss_acquire_cred() failed: Miscellaneous failure (see text) (Key table entry not found)
I have run a truss on the apache process and confirmed that it is in fact loading up the keytab file ok. I am wondering if there is something wrong with the format of the keytab file...
HTTP/srvnfssol1.dev.local#DEV.LOCAL
I am not sure what I am missing though. Or what other things to check.
Any suggestions?
Thanks
Peter
Ok. Keytabs are supposed to contain the Service principal name, in this case "HTTP/srvnfssol1.dev.local#DEV.LOCAL" and the encryption key. I see where the MS docs say just to echo that to a file, but I don't think that's right.
You'll need to use the ktpass utility to create the keytab. The MS docs are here.
In particular, you'll need to specify KRB5_NT_SRV_HST, and most of the rest of the options can be default.
Sample of it on my machine:
C:\>ktpass /out test.keytab /princ HTTP/srvnfssol1.dev.local#DEV.LOCAL
/ptype KRB5_NT_SRV_HST /pass *
Type the password for HTTP/srvnfssol1.dev.local:
Key created.
Output keytab to test.keytab:
Keytab version: 0x502
keysize 62 HTTP/srvnfssol1.dev.local#DEV.LOCAL
ptype 3 (KRB5_NT_SRV_HST) vno 1 etype 0x1 (DES-CBC-CRC)
keylength 8 (0xa7f1fb38041c199e)
If the active directory server is the KDC, you'll need to use the /map <name> argument, where <name> is the computer account in active directory representing the server.
Some details on how all this works. When you browse to the website it should respond with a WWW-Authenticate: Negotiate header, and your browser will send a request to the KDC (active directory server) to get a kerberos ticket for the service. The AD server will look up the encryption key for the ticket using the service principal name, and send an encrypted service ticket back to the browser. Once the browser has the service ticket, it'll reissue the HTTP request with an authenticate header containing the ticket. The apache server will look up its key in the keytab, decrypt the ticket, and grant access.
The "key table entry not found" error happens because apache isn't finding itself in the keytab. Can also happen if the name resolution/realms aren't set up right.
You should be able to see all the kerberos requests AP-REQ/AP-REP/TGS-REQ/TGS-REP using wireshark on the client, tcp or udp port 88.