How to decrypt JWE token in IdentityServer4? Implementing JWE in Identity Server4? - oauth-2.0

I am trying to implement JWE in IdentityServer4. But getting exception
SecurityTokenKeyWrapException: IDX10659: UnwrapKey failed, exception from cryptographic operation: '[PII of type 'Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException' is hidden.
Basically I am following https://www.scottbrady91.com/identity-server/encrypting-identity-tokens-in-identityserver4 for the encryption and decryption.
Encrypting "id_token" by overriding CreateTokenAsync method of DefaultTokenCreationService
public class JweTokenCreationService : DefaultTokenCreationService
{
public JweTokenCreationService(ISystemClock clock, IKeyMaterialService keys,
IdentityServerOptions options, ILogger<DefaultTokenCreationService> logger) :
base(clock, keys, options, logger)
{
}
public override async Task<string> CreateTokenAsync(Token token)
{
var filePath = Path.Combine(Environment.CurrentDirectory, "server.crt");
var certificate = new X509Certificate2(filePath); // certificate for encryption
if (token.Type == IdentityServerConstants.TokenTypes.IdentityToken)
{
var payload = await base.CreatePayloadAsync(token);
var handler = new JsonWebTokenHandler();
var jwe = handler.CreateToken(
payload.SerializeToJson(),
await Keys.GetSigningCredentialsAsync(),
new X509EncryptingCredentials(new X509Certificate2(certificate))
);
return jwe; // encrypted token
}
return await base.CreateTokenAsync(token);
}
}
The "id_token" gets encrypted sucessfully.
Decrypting "id_token" in MVC client.
In the Startup.cs class of MVC client I have added the code.
var filePath = Path.Combine(Environment.CurrentDirectory, "server.pfx");
var certificate = new X509Certificate2(filePath, "123456", X509KeyStorageFlags.Exportable);
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://localhost:5001";
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.Scope.Add("api1");
options.SaveTokens = true;
options.TokenValidationParameters = new TokenValidationParameters
{
TokenDecryptionKey = new X509SecurityKey(certificate) // set the TokenDecryptionKey on OpenIdConnectsOptions’s TokenValidationParameters to the appropriate private key
};
});
Result:
While running the application the "id_token" gets encrypted successfully (Checked with debugger). But in client app its throwing exception SecurityTokenKeyWrapException: IDX10659: UnwrapKey failed, exception from cryptographic operation.
Tried Workarounds:
a. Tried using RSA key instead of X5t as mentioned here IDX10659 error when using X509Certficate to decrypt JWT token
options.TokenValidationParameters = new TokenValidationParameters
{
TokenDecryptionKey = new
RsaSecurityKey(certificate.GetRSAPrivateKey().ExportParameters(true))
};
Still getting same exception.
b. Tried Using a Custom Crypto Provider like https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/615
Created a Custom CryptoProviderFactory
public class UnwrappingCryptoProviderFactory : CryptoProviderFactory
{
public UnwrappingCryptoProviderFactory()
{
System.Console.WriteLine("UnwrappingCryptoProviderFactory invoked");
}
public override KeyWrapProvider CreateKeyWrapProvider(SecurityKey key, string algorithm)
{
switch (key)
{
case X509SecurityKey x509Key:
return new RsaKeyWrapProvider(x509Key, algorithm, true);
default:
return base.CreateKeyWrapProvider(key, algorithm);
}
}
}
In MVC client used this custom CryptoProviderFactory
var filePath = Path.Combine(Environment.CurrentDirectory, "server.pfx");
var certificate = new X509Certificate2(filePath, "123456", X509KeyStorageFlags.Exportable);
var key = new X509SecurityKey(certificate);
{
// Custom provider to ensure we can unwrap the key properly when decrypting the token
CryptoProviderFactory = new UnwrappingCryptoProviderFactory()
};
Here is the TokenValidationParameters
options.TokenValidationParameters = new TokenValidationParameters
{
TokenDecryptionKey = key
};
Still getting same exception.
Any help/suggestion would be really helpful. Thanks!

Related

How do I connect to Oracle Netsuite using OAuth 2.0 Client Credentials Flow and JWT certificate with .net core

I am trying to use the Netsuite Rest api. Below are the steps I took.
https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_162730264820.html
Created a Integration Record in Netsuite
Create a self signed cert:
openssl req -x509 -newkey rsa:4096 -sha256 -keyout auth-key.pem -out auth-cert.pem -nodes -days 730
Added the auth-cert.pem to the integration in Netsuite
Tried calling the TokenUrl endpoint to get access token
I keep getting Bad Request (Status code 400) when I call GetNetsuiteJwtAccessToken(string signedJWTAssertion) to get access token from TokenUrl.
static void Main(string[] args)
//static string Scope = "rest_webservices";
//static string Aud = "https://<Tenant>-sb1.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token";
//static string TokenUrl = "https://<Tenant>-sb1.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token";
//static string TenantName = "<Tenant>";
//static string ClientId = "<ClientId>";
//static string Issuer = ClientId;
//static string ClientSecret = "<Client Secret>";
//static string AppId = "<AppId>";
//static string Kid = "<Key from the Netsuite for the uploaded Cert">;
{
var jwt= GenerateNetsuiteJWTFromPEMFile("auth-key.pem");
var accessToken = GetNetsuiteJwtAccessToken(signedJWTAssertion: jwt);
}
public static string GenerateNetsuiteJWTFromPEMFile(string PEMFile)
{
var tokenHandler = new JwtSecurityTokenHandler();
var rsaPem = File.ReadAllText(PEMFile);
var privatekey = RSA.Create();
privatekey.ImportFromPem(rsaPem);
var key = new RsaSecurityKey(privatekey);
//key.KeyId = Kid;
var signingCredentials = new SigningCredentials(
key: key,
algorithm: SecurityAlgorithms.RsaSha256
);
//signingCredentials.Key.KeyId = Kid;
var Now = DateTimeOffset.UtcNow;
var Exp = Now.AddMinutes(30).ToUnixTimeSeconds();
var Iat = Now.ToUnixTimeSeconds();
var jwt = new SecurityTokenDescriptor
{
Issuer = Issuer,
Claims = new Dictionary<string, object>()
{
["iss"] = Issuer,
["scope"] = Scope,
["aud"] = Aud,
["exp"] = Exp,
["iat"] = Iat
},
SigningCredentials = signingCredentials
};
var jws = tokenHandler.CreateToken(jwt);
var encoded = new JwtSecurityTokenHandler().WriteToken(jws);
return encoded;
}
public static string GetNetsuiteJwtAccessToken(string signedJWTAssertion)
{
string accessToken;
HttpClient _httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Clear();
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
new KeyValuePair<string, string>("assertion", signedJWTAssertion)
};
using (var content = new FormUrlEncodedContent(requestParams))
{
var response = _httpClient.PostAsync(TokenUrl, content).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
accessToken = responseContent;
}
return accessToken;
}
I ran into the exact same issue and here's how I resolved it.
The function below actual sends the request:
public async Task GetAccessToken()
{
string tokenBaseUrl = <token endpoint URL>;
string consumerKey = <consumer key/client ID from NetSuite>;
// Don't worry about _configurationService below
string assertion = new JwtToken(_configurationService).GetJwtToken(consumerKey);
var parameters = new Dictionary<string, string>
{
{"grant_type", "client_credentials" },
{"client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" },
{"client_assertion", assertion } // use client_assertion, not assertion, the example provided in the docs uses the former
};
var content = new FormUrlEncodedContent(parameters);
var response = await _httpClient.PostAsync(tokenBaseUrl, content);
}
You can extract the access token from response at the end. I just haven't gotten to that.
Now the magic happens in the function below, which creates the JWT token:
public string GetJwtToken()
{
try
{
// Read the content of a private key PEM file, PKCS8 encoded.
string privateKeyPem = File.ReadAllText(<file path to private key>);
// keep only the payload of the key.
privateKeyPem = privateKeyPem.Replace("-----BEGIN PRIVATE KEY-----", "");
privateKeyPem = privateKeyPem.Replace("-----END PRIVATE KEY-----", "");
// Create the RSA key.
byte[] privateKeyRaw = Convert.FromBase64String(privateKeyPem);
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.ImportPkcs8PrivateKey(new ReadOnlySpan<byte>(privateKeyRaw), out _);
RsaSecurityKey rsaSecurityKey = new RsaSecurityKey(provider);
// Create signature and add to it the certificate ID provided by NetSuite.
var signingCreds = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256);
signingCreds.Key.KeyId = <certificate ID provided when auth cert uploaded to NetSuite>;
// Get issuing timestamp.
var now = DateTime.UtcNow;
// Create token.
var handler = new JsonWebTokenHandler();
string token = handler.CreateToken(new SecurityTokenDescriptor
{
Issuer = <consumer key/client ID>,
Audience = <token endpoint URL>,
Expires = now.AddMinutes(5),
IssuedAt = now,
Claims = new Dictionary<string, object> { { "scope", new[] { "rest_webservices" } } },
SigningCredentials = signingCreds
});
return token;
}
catch (Exception e)
{
throw new <custom exception>("Creating JWT bearer token failed.", e);
}
This returns a status 200, so if it still doesn't work for you, I would double check if you set up all the NetSuite 0Auth 2.0 settings correctly.

JWT Token authentication - Doing it right way

Overview of my project structure:
I have 2 Projects.
Asp.net core Web Api
Asp.net core Web MVC
In Web Api Project
I am NOT using Asp.net core Identity for login, instead, I am using my own login mechanism.
LoginAction method will authenticate user in database and generate JWT Token.
I was able to generate JWT Token and Life is smooth till this point.
Generate Token
[AllowAnonymous]
[Route("requesttoken")]
[HttpPost]
public async Task<IActionResult> RequestToken([FromBody] TokenRequest request)
{
var result = await IsValidUser(request);
if(result)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, request.Email)
};
var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_myAppSettings.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _myAppSettings.WebsiteName.ToLower(),
audience: _myAppSettings.WebsiteName.ToLower(),
claims: claims,
notBefore: Utilities.GetEST_DateTimeNow(),
expires: Utilities.GetEST_DateTimeNow().AddMinutes(5),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
else
{
return Unauthorized();
}
}
Inside Startup class
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyAppSettings>(Configuration.GetSection("MyAppSettings"));
#region Validate JWT Token
ConfigureJwtAuthService(services, Configuration);
#endregion
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
JWT Validation part (As partial startup class)
public void ConfigureJwtAuthService(IServiceCollection services, IConfiguration configuration)
{
var symmetricKeyAsBase64 = configuration["MyAppSettings:SecurityKey"];
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray);
var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = Configuration["MyAppSettings:WebsiteName"].ToLower(),
// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = Configuration["MyAppSettings:WebsiteName"].ToLower(),
// Validate the token expiry
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
services.AddAuthentication(
options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o => o.TokenValidationParameters = tokenValidationParameters);
}
Sample response of LoginAction Method.
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkrDtGhuIETDs8OoIiwiYWRtaW4iOnRydWV9.469tBeJmYLERjlKi9u6gylb-2NsjHLC_6kZNdtoOGsA"
}
In Web MVC Project
I am consuming above Web Api and passing login parameters and was able to get JWT Token response.
I am storing JWT Token response in cookie [Manually - _httpContextAccessor.HttpContext.Response.Cookies.Append(key, jwtTokenValue, option);]
Based on JWT Token response receive, I am trying to extract claims from that JWT Token, so that I can able to create valid identity of user and login user on the web.
I am trying to achieve something like below:
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.Email)
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToLocal(returnUrl);
}
Questions
Am I doing right by storing JWT Token in cookie. Is my manual approach of storing cookie is correct or is there any better way?
How can I get claims from JWT in Web Project, so that I can able to singin user using cookie?
Want to do it right way, any help would be much appreciated.
Following seems to helped me: http://blogs.quovantis.com/json-web-token-jwt-with-web-api/ not sure whether that is right way of doing or not.
/// Using the same key used for signing token, user payload is generated back
public JwtSecurityToken GenerateUserClaimFromJWT(string authToken)
{
var tokenValidationParameters = new TokenValidationParameters()
{
ValidAudiences = new string[]
{
"http://www.example.com",
},
ValidIssuers = new string[]
{
"self",
},
IssuerSigningKey = signingKey
};
var tokenHandler = new JwtSecurityTokenHandler();
SecurityToken validatedToken;
try {
tokenHandler.ValidateToken(authToken,tokenValidationParameters, out validatedToken);
}
catch (Exception)
{
return null;
}
return validatedToken as JwtSecurityToken;
}

MSIS9649: Received invalid OAuth request. The 'assertion' parameter value is not a valid access token

I am trying to implement ADFS4 - OAuth (OpenID connect) for authentication and webapp to webapi communication.
I have configured ADFS application group accordingly and use OpenIdconnectauth pipeline in webapp for authentication. In order to call webapi, if I request accesstoken using just client credential grant, it works fine as I receive the valid access token and able to get to the api. However, the access token does not have any user details in it which I need it from the webapi end.
So, then I tried by creating UserAssertion object from bootstrapcontext.token. But this time, when ever I request access token, I receive this error as mentioned in the title.
Here is the code snippet:
AuthenticationContext authContext = null;
AuthenticationResult result = null;
authContext = new AuthenticationContext(Startup.authority, false);
ClientCredential credential = new ClientCredential(Startup.clientId, Startup.appKey);
string usercheck = User.Identity.Name; //For checking, returns username
var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
string username = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userAccessToken = bootstrapContext.Token;
UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", username);
string accessToken = null;
HttpClient httpClient = new HttpClient();
try {
//result = authContext.AcquireTokenAsync(Startup.apiResourceId, credential).Result; // This works fine but no user details in the token
result = authContext.AcquireTokenAsync(Startup.apiResourceId, credential, userAssertion).Result;
}
Here is how the Startup.ConfigureAuth(IAppBuilder app) looks like in both webapp and webapi:
In webapp:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,
MetadataAddress = metadataAddress,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = postLogoutRedirectUri,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
{
SaveSigninToken = true
},
ResponseType = "code id_token",
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
And in webapi:
public void ConfigureAuth(IAppBuilder app)
{
JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
app.UseActiveDirectoryFederationServicesBearerAuthentication(
new ActiveDirectoryFederationServicesBearerAuthenticationOptions
{
MetadataEndpoint = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"],
TokenValidationParameters = new TokenValidationParameters() {
SaveSigninToken = true,
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
}
});
}
I reckon that the token that I am passing in to the userassertion is incorrect. But how can I fix this? Is there any other way which I can get the user details in to the access token. I really appreciate if anyone can help us to solve this issue?
Thanks.
You have to use authorization code flow to get the MVC app to talk to the API. Vittorio has a nice post on it here, although it talks about azure.
In order to do that you need to handle the AuthorizationCodeReceived Event via Notifications on the OpenIdConnectAuthenticationOptions from Startup.ConfigureAuth(IAppBuilder app)
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions {
...
Notifications = new OpenIdConnectAuthenticationNotifications {
AuthorizationCodeReceived = async code => {
ClientCredential credential = new ClientCredential(Startup.clientId, Startup.appKey);
AuthenticationContext authContext = new AuthenticationContext(Startup.authority, false);
AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
code.Code,
new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
credential,
Startup.apiResourceId);
}
}
When you are ready to make the call you acquire your token silently.
var authContext = new AuthenticationContext(Startup.authority, false);
var credential = new ClientCredential(Startup.clientId, Startup.appKey);
var claim = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userId = new UserIdentifier(claim, UserIdentifierType.UniqueId);
result = await authContext.AcquireTokenSilentAsync(
Startup.apiResourceId,
credential,
userId);
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
result.AccessToken);

IdentityServer3: OWIN Katana middleware is throwing "invalid_client" error as it cannot get a token

We are using IdentityServer3 as the identity provider and OWIN Katana middleware to do the handshake based on OpenId Connect. The authentication works fine as we were redirected to identity server and back to the originating website. But the issue of invalid_client appears when I try to retrieve the tokens and get claims in the "OpenIdConnectAuthenticationNotifications".
Please check the code (startup class) below and the attached screenshot.
public sealed class Startup
{
public void Configuration(IAppBuilder app)
{
string ClientUri = #"https://client.local";
string IdServBaseUri = #"https://idm.website.com/core";l
string TokenEndpoint = #"https://idm.website.com/core/connect/token";
string UserInfoEndpoint = #"https://idm.website.com/core/connect/userinfo";
string ClientId = #"WebPortalDemo";
string ClientSecret = #"aG90apW2+DbX1wVnwwLD+eu17g3vPRIg7p1OnzT14TE=";
//AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = ClientId,
Authority = IdServBaseUri,
RedirectUri = ClientUri,
PostLogoutRedirectUri = ClientUri,
ResponseType = "code id_token token",
Scope = "openid profile roles",
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
},
SignInAsAuthenticationType = "Cookies",
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
// use the code to get the access and refresh token
var tokenClient = new TokenClient(
TokenEndpoint,
ClientId,
ClientSecret);
var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);
if (tokenResponse.IsError)
{
throw new Exception(tokenResponse.Error);
}
// use the access token to retrieve claims from userinfo
var userInfoClient = new UserInfoClient(UserInfoEndpoint);
var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);
// create new identity
var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
//id.AddClaims(userInfoResponse.GetClaimsIdentity().Claims);
id.AddClaims(userInfoResponse.Claims);
id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));
n.AuthenticationTicket = new AuthenticationTicket(
new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
n.AuthenticationTicket.Properties);
},
RedirectToIdentityProvider = n =>
{
// if signing out, add the id_token_hint
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");
if (idTokenHint != null)
{
n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
}
}
return Task.FromResult(0);
}
}
});
}
}
The client configuration at the IdSvr3 has been specified to use Hybrid Flow and I have checked that the client Id and client secret many times to verify that they are correct.
Here is the client configuration at the server side:
I was able to resolve the issue by looking at the logs generated by identity server. The logs said the client secret is incorrect, when I have checked several times that the secret was exact to what was showing on the identity server. But then I realised that the secret should be the actual text and NOT the hashed one. The modified code that worked is below:
string ClientId = #"WebPortalDemo";
//string ClientSecret = #"aG90apW2+DbX1wVnwwLD+eu17g3vPRIg7p1OnzT14TE="; // Incorrect secret, didn't work
string ClientSecret = #"love"; // Actual text entered as secret, worked
Credit: #rawel

Troubles authenticating native client to Azure AD securised MVC web app

I created both a MVC 5 web app hosted on Azure and a WPF client. My short term purpose (as if I can achieve that I'll be able to implement all my uses case) is the following:
Enforce Azure Ad authentification on the WPF client
Have the MVC web app to check through Azure Graph API the AD group membership of the user authentified in the client
Send back Graph API object to the client (IUser, Group...)
Use group membership to define Authorization on controllers
My actual issue is the following:
The user launch the app, and is prompted for authentication. I guess it work as I can display the user's mail and I have an access token.
The user tries to access a web api controller and it works fine
The user tries to access another web api controller decorated with [Authorize] and i get in return some HTML page stating this : "We can't sign you in.Your browser is currently set to block JavaScript. You need to allow JavaScript to use this service."
From what I've found searching on the web it seems that it could be related to my web app that is not configured properly (I already tried to add my webapp url in trusted sites and I'm sure that my controller URL is Ok). i cannot find much doc on native client + AAD + MVC so I don't really know how to correct it.
Here's my startup.auth.cs from the webapp :
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
private static string certName = ConfigurationManager.AppSettings["ida:CertName"];
public static readonly string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
string graphResourceId = ConfigurationManager.AppSettings["ida:GraphUrl"];
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
//
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
//
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
#region Certs (not used)
if (certName.Length != 0)
{
// Create a Client Credential Using a Certificate
//
// Initialize the Certificate Credential to be used by ADAL.
// First find the matching certificate in the cert store.
//
X509Certificate2 cert = null;
X509Store store = new X509Store(StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
// Place all certificates in an X509Certificate2Collection object.
X509Certificate2Collection certCollection = store.Certificates;
// Find unexpired certificates.
X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
// From the collection of unexpired certificates, find the ones with the correct name.
X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certName, false);
if (signingCert.Count == 0)
{
// No matching certificate found.
return Task.FromResult(0);
}
// Return the first certificate in the collection, has the right name and is current.
cert = signingCert[0];
}
finally
{
store.Close();
}
// Then create the certificate credential.
ClientAssertionCertificate credential = new ClientAssertionCertificate(clientId, cert);
string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
"http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
AuthenticationHelper.token = result.AccessToken;
}
#endregion
else
{
// Create a Client Credential Using an Application Key
ClientCredential credential = new ClientCredential(clientId, appKey);
string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
AuthenticationHelper.token = result.AccessToken;
}
return Task.FromResult(0);
}
}
});
}
}
Here's the controller which can be acceded when not decorated with [Authorize] but in that case the action throw a null exception (but if I can't get it fixed i'll post another question):
[System.Web.Http.Authorize]
public class UserADGraphController : ApiController
{
[ResponseType(typeof(IUser))]
[System.Web.Http.Route("api/UserADGraphController/GetMyInformations")]
public IHttpActionResult GetMyInformations()
{
try
{
string uID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
if (uID == null)
return Ok("UId null");
ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
if (client == null)
return Ok("Client null");
IUser adUser = client.Users.Where(u => u.ObjectId == uID).ExecuteAsync().Result.CurrentPage.SingleOrDefault();
if (adUser == null)
{
return NotFound();
}
return Ok(adUser);
}
catch (Exception e)
{
return Ok(e.Message + " " + e.StackTrace);
}
and finally here are relevant parts of the client:
In the mainviewmodel class:
#region Azure AD auth properties
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
Uri redirectUri = new Uri(ConfigurationManager.AppSettings["ida:RedirectUri"]);
private static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
private static string AppServiceResourceId = ConfigurationManager.AppSettings["todo:AppServiceResourceId"];
private static string AppServiceBaseAddress = ConfigurationManager.AppSettings["todo:AppServiceBaseAddress"];
private HttpClient httpClient;
private AuthenticationContext authContext = null;
#endregion
In the mainviewmodel constructor:
authContext = new AuthenticationContext(authority);
httpClient = new HttpClient();
My sign in method:
{
AuthenticationResult result = null;
try
{
result = authContext.AcquireToken(AppServiceResourceId, clientId, redirectUri, PromptBehavior.Auto);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
SignInLabelContent = "Connected to azure AD as " + result.UserInfo.DisplayableId;
}
catch (AdalException ex)
{
if (ex.ErrorCode == "user_interaction_required")
{
}
else
{
// An unexpected error occurred.
string message = ex.Message;
if (ex.InnerException != null)
{
message += "Inner Exception : " + ex.InnerException.Message;
}
Messenger.Default.Send<NotificationMessage>(new NotificationMessage(message));
//MessageBox.Show(message);
}
return;
}
}
The method that access the protected controller:
IUser me = null;
AuthenticationResult result = null;
result = authContext.AcquireToken(AppServiceResourceId, clientId, redirectUri, PromptBehavior.Auto);
string authHeader = result.CreateAuthorizationHeader();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
//HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, AppServiceBaseAddress + "/api/UserADGraphController/GetMyInformations");
//request.Headers.TryAddWithoutValidation("Authorization", authHeader);
//HttpResponseMessage response = await client.SendAsync(request);
//string responseString = await response.Content.ReadAsStringAsync();
//LogManager.log(responseString);
//Messenger.Default.Send<NotificationMessage>(new NotificationMessage(responseString));
HttpResponseMessage response = await httpClient.GetAsync(AppServiceBaseAddress + "/api/UserADGraphController/GetMyInformations");
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
LogManager.log(jsonString);
me = JsonConvert.DeserializeObject<IUser>(jsonString);
//Messenger.Default.Send<NotificationMessage>(new NotificationMessage(jsonString));
}
In my case response has status code 200 but the jsonString contains the web page telling me about javascript disabled.
If someone has an idea it would be great !
Thanks !
If someone gets into this issue, I managed to solve it by changing my configureAuth method this way :
var azureADBearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = tenant
};
azureADBearerAuthOptions.TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = audience
};
app.UseWindowsAzureActiveDirectoryBearerAuthentication(azureADBearerAuthOptions);
This error message is very misleading. I was getting the same problem, and found that my issue was actually mismatched Client Secret/AppURI settings.
From the error message, I assumed it was something I was doing in the ConfigureAuth method. Turns out I was mixing up dev and test settings.
Maybe this will help others who end up on this confusing error message.

Resources