Owin UseOAuthBearerAuthentication Not getting groups claims - single-sign-on

I am not getting any group claims back from Okta when authenticating using the id_token. I am getting the name, email, address, and username, but no groups.
Not sure what else I would need to do to get this onto the principle
var clientID = WebConfigurationManager.AppSettings["okta:ClientId"];
var oidcIssuer = WebConfigurationManager.AppSettings["okta:OIDC_Issuer"];
TokenValidationParameters tvps = new TokenValidationParameters
{
ValidateAudience = true,
ValidAudience = clientID,
ValidateIssuer = true,
ValidIssuer = oidcIssuer,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5),
};
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenFormat = new JwtFormat(tvps,
new OpenIdConnectCachingSecurityTokenProvider(oidcIssuer + "/.well-known/openid-configuration")),
});

Related

JwtBearer middleware with ES256 always 401 Bearer error="invalid_token", error_description="The signature key was not found"

token is created using
public class AppTokenHandler : TokenValidator, IAppTokenHandler
{
private readonly JwtSecurityTokenHandler _handler = new JwtSecurityTokenHandler();
private readonly AppTokenConfiguration _appTokenConfiguration;
private readonly RsaSecurityKey _publicKey;
private readonly ECDsa _key;
public AppTokenHandler(IOptions<AppTokenConfiguration> appTokenConfiguration, RsaSecurityKey publicKey, ECDsa key)
{
_appTokenConfiguration = appTokenConfiguration.Value;
_publicKey = publicKey;
_key = key;
}
public string Create(Dictionary<string, object> claims)
{
var name = claims["name"].ToString();
////create token security key used to sign token from app's rsa private key
//using var rsa = RSA.Create();
//var rsaKey = _appTokenConfiguration.RsaKey;
//rsa.ImportRSAPrivateKey(Convert.FromBase64String(rsaKey), out _);
//RsaSecurityKey rsaSecurityKey = new(rsa);
////create signing credentials, specifying not to cache signature provider
//SigningCredentials signingCredentials = new(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
//{
// CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
//};
SigningCredentials signingCredentials = new(new ECDsaSecurityKey(_key), SecurityAlgorithms.EcdsaSha256);
// create token
var tokenDescriptor = new SecurityTokenDescriptor
{
Audience = _appTokenConfiguration.Audience,
Claims = claims,
Expires = DateTime.UtcNow.AddDays(2),
IssuedAt = DateTime.UtcNow,
Issuer = _appTokenConfiguration.Issuer,
SigningCredentials = signingCredentials,
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, name),
})
};
var encodedJwt = _handler.CreateEncodedJwt(tokenDescriptor);
return encodedJwt;
}
public override bool Validate(string tokenString, out JwtSecurityToken token, out SecurityTokenValidationException validationException)
{
validationException = null;
token = null;
var publicKey = ECDsa.Create(_key.ExportParameters(false));
var validationParameters = new TokenValidationParameters
{
// validate lifetime
RequireExpirationTime = true,
ValidateLifetime = true,
// validate audience
RequireAudience = true,
ValidateAudience = true,
ValidAudience = _appTokenConfiguration.Audience,
// validate issuer
ValidateIssuer = true,
ValidIssuer = _appTokenConfiguration.Issuer,
// set source of name
NameClaimType = "name",
// validate signing key
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
//IssuerSigningKey = _publicKey
IssuerSigningKey = new ECDsaSecurityKey(publicKey)
};
try
{
var validate = _handler.ValidateToken(tokenString, validationParameters, out var validatedSecurityToken);
token = _handler.ReadJwtToken(tokenString);
}
catch (SecurityTokenValidationException ex)
{
validationException = ex;
return false;
}
catch
{
throw;
}
return true;
}
public Dictionary<string, object> MapClaims(JwtSecurityToken accessToken, JwtSecurityToken idToken)
{
List<string> claimKeys = new()
{
"name",
"preferred_username",
"oid",
"tid",
"azp",
"family_name",
"given_name",
"email"
};
var claims = accessToken?
.Claims
.Where(x=>claimKeys.Contains(x.Type))
.ToDictionary(x => x.Type, x => x.Value as object)
??
new Dictionary<string, object>();
var idTokenClaims = idToken
.Claims
.Where(x => claimKeys.Contains(x.Type))
.ToDictionary(x => x.Type, x => x.Value as object);
foreach (var claim in idTokenClaims.Where(x => !claims.ContainsKey(x.Key)))
claims.Add(claim.Key, claim.Value);
claims.Add("scp", "app_authorized_user");
return claims;
}
}
token is configured using
public class AppTokenOptions
{
public static Action<JwtBearerOptions> ConfigureToken(IServiceCollection services)
{
return options =>
{
var serviceProvider = services.BuildServiceProvider();
var authConfig = serviceProvider.GetRequiredService<IOptions<AppTokenConfiguration>>();
var publicKey = serviceProvider.GetRequiredService<RsaSecurityKey>();
var privkey = serviceProvider.GetRequiredService<ECDsa>();
//var key = ECDsa.Create(privkey.ExportParameters(false));
options.IncludeErrorDetails = true;
options.TokenValidationParameters = new TokenValidationParameters
{
// validate lifetime
RequireExpirationTime = true,
ValidateLifetime = true,
// validate audience
RequireAudience = true,
ValidateAudience = true,
ValidAudience = authConfig.Value.Audience,
// validate issuer
ValidateIssuer = true,
ValidIssuer = authConfig.Value.Issuer,
// set source of name
NameClaimType = "name",
// validate signing key
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
//IssuerSigningKey = publicKey
IssuerSigningKey = new ECDsaSecurityKey(ECDsa.Create(privkey.ExportParameters(false)))
};
options.Events = new JwtBearerEvents();
options.Events.OnTokenValidated = async context =>
{
(context.Principal?.Identity as ClaimsIdentity)?.AddClaim(new Claim("cpcb", "test"));
};
};
}
}
auth is added immediately in ConfigureServices of Startup.cs using
public static class AuthServicesRegistration
{
public static IServiceCollection ConfigureApplicationAuthServices(this IServiceCollection services, IConfiguration Configuration)
{
// get relevant config sections
IConfiguration appAuth= Configuration.GetSection("Auth:app");
IConfiguration aadIdTokenAuth = Configuration.GetSection("Auth:AADIdToken");
// create keys for app token
using (RSA rsa = RSA.Create(3072))
{
string rsaKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey());
string rsaPublicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey());
appAuth["RsaKey"] = rsaKey;
appAuth["RsaPublicKey"] = rsaPublicKey;
}
// bind auth configs
services.Configure<AppTokenConfiguration>(appAuth);
services.Configure<AzureAdIdTokenConfiguration>(aadIdTokenAuth);
// add public key instance as singleton
// so it can be used in .net's token validation middleware
// otherwise if just declared when defined token validation parameters
// the RSA instance will be prematurely disposed and you will get misleading 401s
services.AddSingleton(provider => {
RSA rsa = RSA.Create();
rsa.ImportRSAPublicKey(Convert.FromBase64String(appAuth["RsaPublicKey"]), out _);
return new RsaSecurityKey(rsa);
});
services.AddSingleton(provider =>
{
return ECDsa.Create(ECCurve.NamedCurves.nistP256);
});
// add provider for microsoft openidconnect config
services.AddSingleton<IOpenIdConnectConfigurationProvider>(provider =>
{
var stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
var configProvider = new OpenIdConnectConfigurationProvider(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
configProvider.AutomaticRefreshInterval = TimeSpan.FromHours(1);
return configProvider;
});
// add authentication schemes
// default is app token
services.AddAuthentication("app")
.AddJwtBearer("app", AppTokenOptions.ConfigureToken(services))
.AddMicrosoftIdentityWebApi(Configuration, "Auth:AzureAd", "aad");
// configure aad token options
services.Configure("aad", AzureAdTokenOptions.ConfigureAadToken());
// add authorization
services.AddAuthorization();
// add auth related services
services.AddScoped<IAppTokenHandler, AppTokenHandler>();
services.AddScoped<ITokenValidator, MicrosoftIdTokenValidator>();
return services;
}
}
token generation endpoint and test endpoint to validate token
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private readonly IAppTokenHandler _appTokenHandler;
private readonly ITokenValidator _idTokenValidator;
public AuthController(IAppTokenHandler tokenHandler, ITokenValidator idTokenValidator) : base()
{
_appTokenHandler = tokenHandler;
_idTokenValidator = idTokenValidator;
}
/// <summary>
/// Returns token for requested resource verifying using msal accesstoken
/// </summary>
/// <returns></returns>
[Authorize(AuthenticationSchemes = "aad")]
[RequiredScope(AcceptedScope = new[] { "app_login" })]
[Route("token")]
[HttpGet]
public async Task<IActionResult> token()
{
if (!Request.Headers.TryGetValue("identity", out var idTokenString)) return Unauthorized("No identity present to verify");
var aadToken = await HttpContext.GetTokenAsync("aad", "access_token");
JwtSecurityToken accessToken = null;
if (aadToken != null)
{
accessToken = new JwtSecurityToken(aadToken);
}
// verify idToken
if (!_idTokenValidator.Validate(idTokenString, out var idToken, out var validationException))
{
return Unauthorized($"invalid id token: {validationException.Message}");
}
// get / verify user
// get claims from tokens
var claims = _appTokenHandler.MapClaims(accessToken, idToken);
// generate token
var encodedJwt = _appTokenHandler.Create(claims);
return Ok(encodedJwt);
}
/// <summary>
/// Test authorize endpoint
/// </summary>
/// <returns></returns>
[Authorize]
[RequiredScope(AcceptedScope = new[] { "app_authorized_user" })]
[Route("validate/{token}")]
[HttpGet]
public async Task<IActionResult> validate(string token)
{
var authorization = Request.Headers.Authorization.ToString().Substring("Bearer ".Length).Trim();
try
{ // both validate calls are successful when authorize attribute is commented out
if (_appTokenHandler.Validate(token, out _, out var ex))
{
Debug.WriteLine("valid token");
}
else
{
Debug.WriteLine("invalid token", ex.Message);
}
if (_appTokenHandler.Validate(authorization, out _, out var ex2))
{
Debug.WriteLine("valid auth header");
}
else
{
Debug.WriteLine("invalid auth header", ex2.Message);
}
}
catch (Exception exc)
{
Debug.WriteLine(exc.Message);
}
return Ok(token);
}
}
if i swap out ES256 for RSA I had previously wired up, no issues. However, when I tried swapping out RSA for ES256, I got the error "The signature key was not found". If I remove the authorize attribute on the validate endpoint, get a token from the token endpoint and then verify the token using the app token handler, it's valid. There seems to be an issue with the jwt bearer middleware?? I have tried using the full ECDsa instead of just the public key, a singleton of an ECDsaSecurityKey with a key id and without a key id, a singleton of a jsonwebkey, and now a singleton of just the ecdsa. All same result. app token handler instance validates it with same token validation parameters, but jwt bearer middleware fails authorization. And again, if I swap out the signing credentials to use the RSA credentials, everything works just fine.
Am I creating the signing keys incorrectly?
Am I providing the public / private keys incorrectly to jwt bearer middleware?
Am I missing something in token creation?
How do I hook into jwt bearer middleware to get a better idea of what is going on? I see there is the ontokenvalidated event but that is not being hit obviously, is there an event I can hook into that might provide more info into what is going wrong?
Thanks!
I think the ecdsa instance used to create private key was getting displosed too early (?)
Ended up creating the ecdsa and saving the ecparams to config (similar as with rsa keys), created singleton of ecdsasecuritykey with just q and curve (so just public key), used serviceprovider to get ecdsasecuritykey to set as issuersigningkey for token validation in configure jwtbeareroptions, then used all ecparams from config (bound in apptokenconfiguration class) to create private key ecdsasecuritykey when creating the token
in configureapplicationauthservices
// create keys for app tokens
using (RSA rsa = RSA.Create(3072))
using (ECDsa ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256))
{
// rsa
string rsaKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey());
string rsaPublicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey());
appAuth["RsaKey"] = rsaKey;
appAuth["RsaPublicKey"] = rsaPublicKey;
appAuth["RsaKid"] = Guid.NewGuid().ToString();
// ecdsa
ECParameters ecParams = ecdsa.ExportParameters(true);
appAuth["D"] = Convert.ToBase64String(ecParams.D);
appAuth["QX"] = Convert.ToBase64String(ecParams.Q.X);
appAuth["QY"] = Convert.ToBase64String(ecParams.Q.Y);
appAuth["EcKid"] = Guid.NewGuid().ToString();
}
// bind auth configs
services.Configure<AppTokenConfiguration>(appAuth);
services.Configure<AzureAdIdTokenConfiguration>(aadIdTokenAuth);
// add rsa public key instance as singleton
// so it can be used in .net's token validation middleware
// otherwise if just declared when defined token validation parameters
// the RSA instance will be prematurely disposed and you will get misleading 401s
services.AddSingleton(provider => {
RSA rsa = RSA.Create();
rsa.ImportRSAPublicKey(Convert.FromBase64String(appAuth["RsaPublicKey"]), out _);
return new RsaSecurityKey(rsa);
});
// add ecdsa public key same way as rsa
services.AddSingleton(provider =>
{
ECParameters ecParams = new ECParameters();
ecParams.Curve = ECCurve.NamedCurves.nistP256;
ecParams.Q = new ECPoint()
{
X = Convert.FromBase64String(appAuth["QX"]),
Y = Convert.FromBase64String(appAuth["QY"])
};
ECDsa ecdsa = ECDsa.Create(ecParams);
return new ECDsaSecurityKey(ecdsa);
});
token configuration for middleware
public static Action<JwtBearerOptions> ConfigureToken(IServiceCollection services)
{
return options =>
{
var serviceProvider = services.BuildServiceProvider();
var authConfig = serviceProvider.GetRequiredService<IOptions<AppTokenConfiguration>>();
var publicKey = serviceProvider.GetRequiredService<RsaSecurityKey>();
var ecpublicKey = serviceProvider.GetRequiredService<ECDsaSecurityKey>();
options.IncludeErrorDetails = true;
options.TokenValidationParameters = new TokenValidationParameters
{
// validate lifetime
RequireExpirationTime = true,
ValidateLifetime = true,
// validate audience
RequireAudience = true,
ValidateAudience = true,
ValidAudience = authConfig.Value.Audience,
// validate issuer
ValidateIssuer = true,
ValidIssuer = authConfig.Value.Issuer,
// set source of name
NameClaimType = "name",
// validate signing key
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = ecpublicKey
//IssuerSigningKey = publicKey
};
options.Events = new JwtBearerEvents();
options.Events.OnTokenValidated = async context =>
{
(context.Principal?.Identity as ClaimsIdentity)?.AddClaim(new Claim("cpcb", "test"));
};
options.Validate();
};
}
token creation (and validation for manual testing)
public class AppTokenHandler : TokenValidator, IAppTokenHandler
{
//private readonly JsonWebTokenHandler _handler = new();
private readonly JwtSecurityTokenHandler _handler = new();
private readonly AppTokenConfiguration _appTokenConfiguration;
private readonly RsaSecurityKey _publicKey;
private readonly ECDsaSecurityKey _ecdsaPublicKey;
public AppTokenHandler(IOptions<AppTokenConfiguration> appTokenConfiguration, RsaSecurityKey publicKey, ECDsaSecurityKey ecdsaPublicKey)
{
_appTokenConfiguration = appTokenConfiguration.Value;
_publicKey = publicKey;
_ecdsaPublicKey = ecdsaPublicKey;
}
public string Create(Dictionary<string, object> claims)
{
var name = claims["name"].ToString();
//create token security key used to sign token from app's rsa private key
//using var rsa = RSA.Create();
//var rsaKey = _appTokenConfiguration.RsaKey;
//rsa.ImportRSAPrivateKey(Convert.FromBase64String(rsaKey), out _);
//RsaSecurityKey rsaSecurityKey = new(rsa);
////create signing credentials, specifying not to cache signature provider
//SigningCredentials signingCredentials = new(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
//{
// CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
//};
ECParameters ecParams = new ECParameters();
ecParams.Curve = ECCurve.NamedCurves.nistP256;
ecParams.D = Convert.FromBase64String(_appTokenConfiguration.D);
ecParams.Q = new ECPoint()
{
X = Convert.FromBase64String(_appTokenConfiguration.QX),
Y = Convert.FromBase64String(_appTokenConfiguration.QY)
};
using ECDsa ecdsa = ECDsa.Create(ecParams);
ECDsaSecurityKey ecdsaSecurityKey = new(ecdsa);
SigningCredentials signingCredentials = new(ecdsaSecurityKey, SecurityAlgorithms.EcdsaSha256)
{
CryptoProviderFactory = new CryptoProviderFactory { CacheSignatureProviders = false }
};
// create token
var tokenDescriptor = new SecurityTokenDescriptor
{
Audience = _appTokenConfiguration.Audience,
Claims = claims,
Expires = DateTime.UtcNow.AddDays(2),
IssuedAt = DateTime.UtcNow,
Issuer = _appTokenConfiguration.Issuer,
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, name),
}),
SigningCredentials = signingCredentials
};
var encodedJwt = _handler.CreateEncodedJwt(tokenDescriptor);
return encodedJwt;
}
public override bool Validate(string tokenString, out JwtSecurityToken token, out SecurityTokenValidationException validationException)
{
validationException = null;
token = null;
var validationParameters = new TokenValidationParameters
{
// validate lifetime
RequireExpirationTime = true,
ValidateLifetime = true,
// validate audience
RequireAudience = true,
ValidateAudience = true,
ValidAudience = _appTokenConfiguration.Audience,
// validate issuer
ValidateIssuer = true,
ValidIssuer = _appTokenConfiguration.Issuer,
// set source of name
NameClaimType = "name",
// validate signing key
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = _ecdsaPublicKey
//IssuerSigningKey = _publicKey
};
try
{
var validate = _handler.ValidateToken(tokenString, validationParameters, out var validatedSecurityToken);
token = _handler.ReadJwtToken(tokenString);
}
catch (SecurityTokenValidationException ex)
{
validationException = ex;
return false;
}
catch
{
throw;
}
return true;
}
}
gonna clean this up a bit, but at least it is working correctly now :)

How to set JwtBearerOptions dynamically?

I'm developing a multi-tenant application with asp.net core 3.1 as the backend. I used JWT to authenticate users. I'm passing the tenantId along with the http request and I would like to validate JWT against tenantIds. To do this, I must pass the tenantIds to JwtBearerOptions.ValidAudience at each client request.
I set options at startup as follows...
public void ConfigureServices(IServiceCollection services){
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(configureOptions =>
{
configureOptions.ClaimsIssuer = jwtOptions["Issuer"];
configureOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = jwtOptions["Issuer"],
ValidAudience = tenantId,
ValidateIssuerSigningKey = true,
IssuerSigningKey = accessKey,
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
}
Please note that I don't want to pass all tenantIds to ValidateAudiences because each tenant should receive an unique token. e.g. I don't want tenant X's token works for tenant Y.
How do I achieve this?
Thanks in advance!
I'm not sure why you want to set tenant id as Audience , but you can use custom audience validator to implement the logic in TokenValidationParameters :
AudienceValidator = (audiences, securityToken, validationParameters) =>
{
//return true/false based on your requirement
return true;
},
I ended up using below for validating tenderid and I'm quite happy with the outcome. please let me know if there are drawbacks to approch below, thanks!
ValidAudiences = tenants.Value.Select(x=>x.TenantId).ToList(),
IssuerSigningKeyResolver = (string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters) =>
{
var tenant = tenants.Value.Where(t => t.TenantId == kid).FirstOrDefault();
List<SecurityKey> keys = new List<SecurityKey>();
if (tenant != null && kid == tenantsResolver.GetCurrentTenantId())
{
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tenant.SecretKey));
keys.Add(signingKey);
}
return keys;
}

asp.net core 2.0 GitHub has with GetExternalLoginInfoAsync

I config service for GitHub
services.AddOAuth("GitHub", "Github", o =>
{
o.ClientId = Configuration["Authentication:GitHub:ClientId"];
o.ClientSecret = Configuration["Authentication:GitHub:ClientSecret"];
o.CallbackPath = new PathString("/signin-github");
o.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
o.TokenEndpoint = "https://github.com/login/oauth/access_token";
o.UserInformationEndpoint = "https://api.github.com/user";
o.ClaimsIssuer = "OAuth2-Github";
o.SaveTokens = true;
// Retrieving user information is unique to each provider.
o.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
o.ClaimActions.MapJsonKey(ClaimTypes.Name, "login");
o.ClaimActions.MapJsonKey("urn:github:name", "name");
o.ClaimActions.MapJsonKey(ClaimTypes.Email, "email", ClaimValueTypes.Email);
o.ClaimActions.MapJsonKey("urn:github:url", "url");
o.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
// Get the GitHub user
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var user = JObject.Parse(await response.Content.ReadAsStringAsync());
context.RunClaimActions(user);
}
};
});
When I login on GitHub I redirect to action and in action has line ...
var info = await _signInManager.GetExternalLoginInfoAsync();//return null
That line always return null.
Can you help me?

How to decode SessionSecurityToken

Is it possible to decode a SessionSecurityToken?
I've set up a site to work with ThinkTecture IdentityServer using MachineKeySessionSecurityTokenHandler, and everything works as expected.
But now I need to pass the token to another service, but in an Authorization HTTP header instead of a cookie.
I've tried the following:
var cookie = HttpContext.Current.Request.Cookies[FederatedAuthentication.FederationConfiguration.CookieHandler.Name];
if (cookie != null)
{
var t = MachineKey.Unprotect(Convert.FromBase64String(cookie.Value), "System.IdentityModel.Services.MachineKeyTransform");
}
but this throws a System.Security.Cryptography.CryptographicException
Found the solution.
The only (easy) way of sending the data across the wire is to convert the SessionSecurityToken to a JwtSecurityToken and use the RawData property.
Sample implementation (dependent on ThinkTecture.IdentityModel):
public JwtSecurityToken ConvertSessionToJsonWebSecurityToken(SessionSecurityToken sessionToken)
{
var h = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[typeof(JwtSecurityToken)] as JwtSecurityTokenHandler;
if (h != null)
{
var issuer = ((ValidatingIssuerNameRegistry)h.Configuration.IssuerNameRegistry).IssuingAuthorities.First().Name;
var audience = h.Configuration.AudienceRestriction.AllowedAudienceUris.First().AbsoluteUri;
var signingKey = ((ValidatingIssuerNameRegistry)h.Configuration.IssuerNameRegistry).IssuingAuthorities.First().SymmetricKeys.First();
var securityKey = ((NamedKeyIssuerTokenResolver)h.Configuration.IssuerTokenResolver).SecurityKeys.First().Value.First();
// Create token
var t = h.CreateToken(
null,
null,
(ClaimsIdentity)sessionToken.ClaimsPrincipal.Identity,
new Lifetime(sessionToken.ValidFrom, sessionToken.ValidTo),
new SigningCredentials(
securityKey,
Algorithms.HmacSha256Signature,
Algorithms.Sha256Digest));
// Serialize token for validaiton
var s = h.WriteToken(t);
// Validate token
var validationParameters = new TokenValidationParameters()
{
AllowedAudience = audience,
ValidIssuer = issuer,
SigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(signingKey))
};
h.ValidateToken(s, validationParameters);
// Return token with correct type
return h.ReadToken(s) as JwtSecurityToken;
}
return null;
}
[Test]
public void GetToken_WhenValidSessionTokenExist_ShouldReturnValidJwtToken()
{
JwtSecurityToken c;
FederatedAuthentication.SessionAuthenticationModule.TryReadJwtTokenFromCookie(container.GetInstance<ISecurityTokenOperations>(), out c)
Assert.That(!string.IsNullOrEmpty(c.RawData));
}

Getting user access_token from Facebook

I'm building an application that allows users to post message to their facebook from the application. To problem I'm having that I don't know how to get the user access_token for the publish_stream permission.
This is what I've got so far:
var fb = new FacebookClient();
dynamic result = fb.GetLoginUrl(new
{
client_id = AppID,
client_secret = AppSecret,
grant_type = "client_credentials",
scope = "publish_stream",
state = "http://localhost:17578/Facebook.aspx",
redirect_uri = "http://localhost:17578/Facebook.aspx"
});
That works fine and it returns a 'code' in the querystring. However, I'm not sure what to do with that code.
The 'old' Facebook C# sdk contained the FacebookOAuthClient class which had the ExchangeCodeForAccessToken() method, but I don't know what the replacement of this static method is in the new SDK.
So the question really is: How to exchange the code that is returned for an access_token?
After you get the code query string parameter you must make a call to the Facebook Graph API to get the access token.
https://developers.facebook.com/docs/howtos/login/server-side-login/
FacebookClient client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new { client_id = Settings.Social_Facebook_App_Id, client_secret = Settings.Social_Facebook_Secret_Key, code = Request.QueryString["code"], redirect_uri = Settings.Social_Facebook_Login_Redirect_URI });
if (result.error == null)
{
Session["AccessToken"] = client.AccessToken = result.access_token;
dynamic user = client.Get("me", new { fields = "name,username,email" });
string userName = user.username;
mu = Membership.GetUser(userName);
if (mu == null) // Register
{
RegisterModel rm = new RegisterModel();
rm.Email = user.email;
rm.UserName = userName;
return View("Register", rm);
}
else
{
FormsAuthentication.SetAuthCookie(userName, true);
return RedirectToAction(MVC.Home.Index());
}
}