How to specify more than one IssuerSigningKey in UseJwtBearerAuthentication? - oauth

I have a REST api using OAuth bearer token authentication. Token is signed by an asymmetric key and REST api validates the token using public key. I got the code work like below. However, there is a case I need to handle when key needs to update. I am thinking to have a secondary public key passed in and let the framework validate token first using primary key and then secondary key. In this way, when I need to update key, I can easily add secondary key, swap and retire. The issue is looking at code below it only takes one signing key. Is there a way to specify multiple?
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// codes to get signningKey ignored here
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKey = new RsaSecurityKey(signingKey)
},
});
}
Thanks,

Ok, I think I figured it out. There are two ways. One simply straight forward way is to use IssuerSigningKeys property (how could I not discovery it at first place). The code looks like this:
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKeys = new List<RsaSecurityKey>
{
Utils.GetSigningKey(isPrimary: true),
Utils.GetSigningKey(isPrimary: false)
},
},
});
The second approach is to customized IOAuthBearerAuthenticationProvider. The code looks like this: First,
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AllowedAudiences = new string[] { "*" },
IssuerSecurityTokenProviders = new List<IIssuerSecurityTokenProvider>()
{
// Dummy object which won't be used anywhere. It is used to work around parameter validation error about no token provider specified.
new SymmetricKeyIssuerSecurityTokenProvider("dummy", "dummy")
},
// This is where validation work happens.
Provider = new BearerAuthenticationProvider(app)
});
Then, the BearerAuthenticationProvider class:
/// <summary>
/// Bearer authentication provider.
/// </summary>
public class BearerAuthenticationProvider : IOAuthBearerAuthenticationProvider
{
/// <summary>
/// App config.
/// </summary>
private readonly IAppBuilder appConfig;
/// <summary>
/// Handles applying the authentication challenge to the response message.
/// </summary>
public Func<OAuthChallengeContext, Task> OnApplyChallenge { get; set; }
/// <summary>
/// Handles processing OAuth bearer token.
/// </summary>
public Func<OAuthRequestTokenContext, Task> OnRequestToken { get; set; }
/// <summary>
/// Handles validating the identity produced from an OAuth bearer token.
/// </summary>
public Func<OAuthValidateIdentityContext, Task> OnValidateIdentity { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="T:Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationProvider" /> class
/// </summary>
public BearerAuthenticationProvider(IAppBuilder appConfig)
{
this.appConfig = appConfig;
this.OnRequestToken = (OAuthRequestTokenContext context) =>
{
var idContext = new OAuthValidateIdentityContext(context.OwinContext, null, null);
this.ValidateIdentity(idContext);
return Task.FromResult<int>(0);
};
this.OnValidateIdentity = (OAuthValidateIdentityContext context) => Task.FromResult<object>(null);
this.OnApplyChallenge = (OAuthChallengeContext context) => Task.FromResult<object>(null);
}
/// <summary>
/// Handles applying the authentication challenge to the response message.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Task ApplyChallenge(OAuthChallengeContext context)
{
return this.OnApplyChallenge(context);
}
/// <summary>
/// Handles processing OAuth bearer token.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public virtual Task RequestToken(OAuthRequestTokenContext context)
{
return this.OnRequestToken(context);
}
/// <summary>
/// Handles validating the identity produced from an OAuth bearer token.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public virtual Task ValidateIdentity(OAuthValidateIdentityContext context)
{
const string AuthHeaderName = "Authorization";
if (context.Request.Headers.ContainsKey(AuthHeaderName))
{
var jwt = context.Request.Headers[AuthHeaderName].Replace("Bearer ", string.Empty);
var token = new JwtSecurityToken(jwt);
var claimIdentity = new ClaimsIdentity(token.Claims, "ExternalBearer");
var param = new TokenValidationParameters()
{
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKeys = new List<RsaSecurityKey>
{
Utils.GetSigningKey(isPrimary: true),
Utils.GetSigningKey(isPrimary: false)
},
};
SecurityToken securityToken = null;
var handler = new JwtSecurityTokenHandler();
var identity = handler.ValidateToken(token.RawData, param, out securityToken);
var claimPrincipal = new ClaimsPrincipal(claimIdentity);
context.Response.Context.Authentication.User = claimPrincipal;
context.Validated(claimIdentity);
}
else
{
throw new Exception("Invalid authorization header.");
}
return this.OnValidateIdentity(context);
}
}
First approach initializes two signing keys at app startup and only way to make change is when process restarts. the second approach retrieves keys at run time so key rollover doesn't require a service restart.

If you would like to have multiple security keys, you can use the benefit of IssuerSigningKeys property, where you can add all the keys you would like to use for authentication.

Related

Firebase Delete User who signed it with apple correclty

I have implemented the Sign-In-With-Apple with Firebase. And I also have the functionality to delete a user. This is what I do:
static Future<bool> deleteUser(BuildContext context) async {
try {
await BackendService().deleteUser(
context,
);
await currentUser!.delete(); // <-- this actually deleting the user from Auth
Provider.of<DataProvider>(context, listen: false).reset();
return true;
} on FirebaseException catch (error) {
print(error.message);
AlertService.showSnackBar(
title: 'Fehler',
description: error.message ?? 'Unbekannter Fehler',
isSuccess: false,
);
return false;
}
}
As you can see I delete all the users data and finally the user himself from auth.
But Apple still thinks I am using the App. I can see it inside my Settings:
Also when trying to sign in again with apple, it acts like I already have an account. But I just deleted it and there is nothing inside Firebase that says that I still have that account?
How can I completely delete an Apple user from Firebase? What am I missing here?
Apple and some other 3rd party identity provider do not provide APIs to do so commonly.
Access to those data may lead to privacy issue, for e.g., a malicious app can remove the authorization information after access to user profile.
But if you want to do a "graceful" logout, you can ask your users to logout from iOS Settings, and listen to the server-to-server notification for revoking.
Although users account has been deleted on firebase it has not been removed from Apple's system. At the time of writing firebase SDK for Apple is still working on this feature git hub issue (Planned for Q4 2022 or Q1 2023), as flutter and react native are probably dependant on base SDK a custom implementation is needed until this is available.
According to Apple, to completely remove users Apple account you should obtain Apple's refresh token using generate_tokens API and then revoke it using revoke_tokens API.
High level description:
Client side (app): Obtain Apple authorization code.
Send authorization code to your server.
Server side: Use Apples p8 secret key to create jwt token. Jwt token will be used for authenticating requests towards Apple's API
Server side: Trade authorization code for refresh_token (see first link above)
Server side: Revoke refresh_token (see second link above)
Detailed description:
https://stackoverflow.com/a/72656672/6357154
.NET implantation of the server side process.
Assumptions:
_client is a HttpClient registered in DI contrainer with base url from Apple docs posted above
AppleClientOptions contains the same values used for Apple setup on firebase.
/// <summary>
/// Gets apple refresh token
/// SEE MORE: https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens
/// </summary>
/// <param name="jwtToken"></param>
/// <param name="authorizationCode"></param>
/// <returns></returns>
public async Task<string> GetTokenFromApple(string jwtToken, string authorizationCode)
{
IEnumerable<KeyValuePair<string, string>> content = new[]
{
new KeyValuePair<string, string>("client_id", _appleClientOptions.ClientId),
new KeyValuePair<string, string>("client_secret", jwtToken),
new KeyValuePair<string, string>("code", authorizationCode),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
};
var encodedContent = new FormUrlEncodedContent(content);
var response = await _client.PostAsync("auth/token", encodedContent);
var responseAsString = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var appleTokenResponse = JsonConvert.DeserializeObject<AppleTokenResponse>(responseAsString);
return appleTokenResponse.refresh_token;
}
_logger.LogError($"GetTokenFromApple failed: {responseAsString}");
return null;
}
/// <summary>
/// Revokes apple refresh token
/// SEE MORE: https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens
/// </summary>
/// <param name="jwtToken"></param>
/// <param name="refreshToken"></param>
/// <returns></returns>
public async Task<bool> RevokeToken(string jwtToken, string refreshToken)
{
IEnumerable<KeyValuePair<string, string>> content = new[]
{
new KeyValuePair<string, string>("client_id", _appleClientOptions.ClientId),
new KeyValuePair<string, string>("client_secret", jwtToken),
new KeyValuePair<string, string>("token", refreshToken),
new KeyValuePair<string, string>("token_type_hint", "refresh_token"),
};
var response = await _client.PostAsync("auth/revoke", new FormUrlEncodedContent(content));
return response.IsSuccessStatusCode;
}
private string GenerateAppleJwtTokenLinux()
{
var epochNow = (int) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
var (payload, extraHeaders) = CreateJwtPayload(
epochNow,
_appleClientOptions.TeamId,
_appleClientOptions.ClientId,
_appleClientOptions.KeyId);
var privateKeyCleaned = Base64Decode(_appleClientOptions.PrivateKey)
.Replace("-----BEGIN PRIVATE KEY-----", string.Empty)
.Replace("-----END PRIVATE KEY-----", string.Empty)
.Replace("\r\n", string.Empty)
.Replace("\r\n", string.Empty);
var bytes = Convert.FromBase64String(privateKeyCleaned);
using var ecDsaKey = ECDsa.Create();
ecDsaKey!.ImportPkcs8PrivateKey(bytes, out _);
return Jose.JWT.Encode(payload, ecDsaKey, JwsAlgorithm.ES256, extraHeaders);
}
private static (Dictionary<string, object> payload, Dictionary<string, object> extraHeaders) CreateJwtPayload(
int epochNow,
string teamId,
string clientId,
string keyId)
{
var payload = new Dictionary<string, object>
{
{"iss", teamId},
{"iat", epochNow},
{"exp", epochNow + 12000},
{"aud", "https://appleid.apple.com"},
{"sub", clientId}
};
var extraHeaders = new Dictionary<string, object>
{
{"kid", keyId},
{"alg", "ES256"}
};
return (payload, extraHeaders);
}
/// <summary>
/// https://developer.apple.com/documentation/sign_in_with_apple/tokenresponse
/// </summary>
public class AppleTokenResponse
{
public string access_token { get; set; }
public string expires_in { get; set; }
public string id_token { get; set; }
public string refresh_token { get; set; }
public string token_type { get; set; }
}
public class AppleClientOptions
{
public string TeamId { get; set; }
public string ClientId { get; set; }
public string KeyId { get; set; }
public string PrivateKey { get; set; }
}
public async Task<bool> DeleteUsersAccountAsync(string appleAuthorizationCode)
{
// Get jwt token:
var jwtToken = _appleClient.GenerateAppleJwtTokenLinux(); // Apple client is code form above, registered in DI.
// Get refresh token from authorization code:
var refreshToken = await _appleClient.GetTokenFromApple(jwtToken, appleAuthorizationCode);
if (string.IsNullOrEmpty(refreshToken)) return false;
// Delete token:
var isRevoked = await _appleClient.RevokeToken(jwtToken, refreshToken);
_logger.LogInformation("Deleted apple tokens for {UserId}", userId);
if (!isRevoked) return false;
return true;
}
Other implementation examples:
https://github.com/jooyoungho/apple-token-revoke-in-firebase
https://github.com/invertase/react-native-apple-authentication/issues/282
You did actually delete the user from Firebase but Apple doesn't know about that. You should delete that information also from Apple. Open the Settings app on your iPhone, then tap on your name at the top. Then press "Password & Security", then "Apple ID logins". All Apple ID logins should be listed there and can be deleted.
so... Apple does not provide this service. But I found a workaround.
My sign in process:
1. Check if user signed in before
// Create an `OAuthCredential` from the credential returned by Apple.
final oauthCredential = OAuthProvider("apple.com").credential(
idToken: appleCredential.identityToken,
rawNonce: rawNonce,
);
// If you can not access the email property in credential,
// means that user already signed in with his appleId in the application once before
bool isAlreadyRegistered = appleCredential.email == null;
Now to the crucial part:
2. sign in user and check if that uid already exists in Firebase
final UserCredential result =
await FirebaseAuth.instance.signInWithCredential(
oauthCredential,
);
isAlreadyRegistered = await BackendService.checkIfUserIdExists(
result.user?.uid ?? '',
);
checkIfUserIdExists is quite simple as well:
static Future<bool> checkIfUserIdExists(String userId) async {
try {
var collectionRef = FirebaseFirestore.instance.collection(
BackendKeys.users,
);
var doc = await collectionRef.doc(userId).get();
return doc.exists;
} on FirebaseException catch (e) {
return false;
}
}

ConfigurationManager RefreshInterval vs AutomaticRefreshInterval

Can someone explain to me the difference between AutomaticRefreshInterval and RefreshInterval, i'm using ConfigurationManager in my OpenIdConnectCachingSecurityTokenProvider implementing IIssuerSecurityTokenProvider, by default AutomaticRefreshInterval is set to 5 days and RefreshInterval to 30 seconds, i can't find a clear explaination between those two values, the goal is to prevent resquesting metadata frequently and request them only after 1 hours for example, is the default configuration is ok or i have to change the RefreshInterval
My OpenIdConnectCachingSecuritytokenProvider class
public class OpenIdConnectCachingSecurityTokenProvider : IIssuerSecurityTokenProvider
{
public ConfigurationManager<OpenIdConnectConfiguration> _configManager;
private string _issuer;
private IEnumerable<SecurityToken> _tokens;
private readonly string _metadataEndpoint;
private readonly ReaderWriterLockSlim _synclock = new ReaderWriterLockSlim();
public OpenIdConnectCachingSecurityTokenProvider(string metadataEndpoint)
{
_metadataEndpoint = metadataEndpoint;
_configManager = new ConfigurationManager<OpenIdConnectConfiguration>(metadataEndpoint);
//_configManager.RefreshInterval = new TimeSpan(0,1,0);
//_configManager.AutomaticRefreshInterval
RetrieveMetadata();
}
/// <summary>
/// Gets the issuer the credentials are for.
/// </summary>
/// <value>
/// The issuer the credentials are for.
/// </value>
public string Issuer
{
get
{
RetrieveMetadata();
_synclock.EnterReadLock();
try
{
return _issuer;
}
finally
{
_synclock.ExitReadLock();
}
}
}
/// <summary>
/// Gets all known security tokens.
/// </summary>
/// <value>
/// All known security tokens.
/// </value>
public IEnumerable<SecurityToken> SecurityTokens
{
get
{
RetrieveMetadata();
_synclock.EnterReadLock();
try
{
return _tokens;
}
finally
{
_synclock.ExitReadLock();
}
}
}
private void RetrieveMetadata()
{
_synclock.EnterWriteLock();
try
{
OpenIdConnectConfiguration config = Task.Run(_configManager.GetConfigurationAsync).Result;
_issuer = config.Issuer;
_tokens = config.SigningTokens;
}
finally
{
_synclock.ExitWriteLock();
}
}
}

ASP.NET Identity, persistent cookie - is something like this build in?

We are using CookieAuthenticationProvider and would like to implement the 'Remember me' functionality in our application that would work like this:
No matter if the 'Remember me' checkbox is checked or not, the token expiration time should always be set to 30 minutes (with SlidingExpiration turned on)
If user doesn't check 'Remember me' all we do is check if token expired - if it did, then user is redirected to login screen (this is build in into OWIN and works fine)
However if user checks 'Remember me' his credentials should be saved in the additional cookie (with default lifetime of 30 days). If his token expires (the timeout should still be set to 30 minutes), OWIN should use that additional cookie to renew the token automatically in the background. So in other words - if user check 'Remember me' he should be logged in for 30 days or until he logs out.
Question is - how can something like this be done with OWIN? As far as I can see, the default implementation still uses ExpireTimeSpan parameter - the only difference is, that the cookie is marked as persistent, so if user restarts browser he is logged in - but token expiration is still limited by ExpireTimeSpan.
I guess I have to somehow manually save user credentials during the SignIn and override the OnApplyRedirect event (that seems to be the only event fired if an unauthorized user tries to access a view that requires authorization), and instead of redirecting, somehow regenerate user's token... but does anybody know how exactly to do that?
Finally, I ended up writing custom middleware and plugging it in:
RememberMeTokenMiddleware.cs:
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using WebApplicationtoRemove.Owin.HelperClasses;
using Microsoft.AspNet.Identity.Owin;
namespace WebApplicationtoRemove.Owin.Middleware
{
public class RememberMeTokenMiddleware : OwinMiddleware
{
#region Private Members
private static double RememberMeTokenPeriodOfvalidityInMinutes = 43200;
private IOwinContext Context { get; set; }
#endregion
#region Public Static Members
#endregion
#region Constructor
public RememberMeTokenMiddleware(OwinMiddleware next)
: base(next)
{
}
public RememberMeTokenMiddleware(OwinMiddleware next, double RememberMeTokenPeriodOfvalidityInMinutes)
: base(next)
{
RememberMeTokenMiddleware.RememberMeTokenPeriodOfvalidityInMinutes = RememberMeTokenPeriodOfvalidityInMinutes;
}
#endregion
#region Public Methods
public override async Task Invoke(IOwinContext context)
{
try
{
Context = context;
bool shouldDeleteRememberMeToken = CheckIfRememberMeTokenShouldBeDeleted(context);
if (shouldDeleteRememberMeToken)
{
context.Response.Cookies.Delete("RemoveRememberMeToken");
context.Response.Cookies.Delete("RememberMeToken");
}
else
{
if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated)
{
//User is either not set or is not authenticated - try to log him in, using the RememberMeCookie
Login(context);
}
}
}
catch (Exception ex)
{
//Something went wrong - we assume that cookie and/or token was damaged and should be deleted
context.Response.Cookies.Delete("RememberMeToken");
}
await this.Next.Invoke(context);
}
#endregion
#region Static Methods
/// <summary>
/// Check conditions and creates RememberMeToken cookie if necessary. This should be called inside SidnedIn event of CookieProvider
/// </summary>
public static void CheckAndCreateRememberMeToken(CookieResponseSignedInContext ctx)
{
try
{
bool signedInFromRememberMeToken = CheckIfUserWasSignedInFromRememberMeToken(ctx.OwinContext);
if (!signedInFromRememberMeToken && ctx.Properties.IsPersistent)
{
//Login occured using 'normal' path and IsPersistant was set - generate RememberMeToken cookie
var claimsToAdd = GenerateSerializableClaimListFromIdentity(ctx.Identity);
SerializableClaim cookieExpirationDate = GenerateRememberMeTokenExpirationDateClaim();
claimsToAdd.Add(cookieExpirationDate);
var allClaimsInFinalCompressedAndProtectedBase64Token = GenerateProtectedAndBase64EncodedClaimsToken(claimsToAdd);
ctx.Response.Cookies.Append("RememberMeToken", allClaimsInFinalCompressedAndProtectedBase64Token, new CookieOptions()
{
Expires = DateTime.Now.AddMinutes(RememberMeTokenPeriodOfvalidityInMinutes)
});
//Remove the SignedInFromRememberMeToken cookie, to let the middleware know, that user was signed in using normal path
ctx.OwinContext.Set("SignedInFromRememberMeToken", false);
}
}
catch (Exception ex)
{
//Log errors using your favorite logger here
}
}
/// <summary>
/// User logged out - sets information (using cookie) for RememberMeTokenMiddleware that RememberMeToken should be removed
/// </summary>
public static void Logout(IOwinContext ctx)
{
ctx.Response.Cookies.Append("RemoveRememberMeToken", "");
}
#endregion
#region Private Methods
/// <summary>
/// Returns information if user was signed in from RememberMeToken cookie - this information should be used to determine if RememberMeToken lifetime should be regenerated or not (it should be, if user signed in using normal path)
/// </summary>
private static bool CheckIfUserWasSignedInFromRememberMeToken(IOwinContext ctx)
{
bool signedInFromRememberMeToken = ctx.Get<bool>("SignedInFromRememberMeToken");
return signedInFromRememberMeToken;
}
/// <summary>
/// Generates serializable collection of user claims, that will be saved inside the cookie token. Custom class is used because Claim class causes 'Circular Reference Exception.'
/// </summary>
private static List<SerializableClaim> GenerateSerializableClaimListFromIdentity(ClaimsIdentity identity)
{
var dataToReturn = identity.Claims.Select(x =>
new SerializableClaim()
{
Type = x.Type,
ValueType = x.ValueType,
Value = x.Value
}).ToList();
return dataToReturn;
}
/// <summary>
/// Generates a special claim containing an expiration date of RememberMeToken cookie. This is necessary because we CANNOT rely on browsers here - since each one threat cookies differently
/// </summary>
private static SerializableClaim GenerateRememberMeTokenExpirationDateClaim()
{
SerializableClaim cookieExpirationDate = new SerializableClaim()
{
Type = "RememberMeTokenExpirationDate",
Value = DateTime.Now.AddMinutes(RememberMeTokenPeriodOfvalidityInMinutes).ToBinary().ToString()
};
return cookieExpirationDate;
}
/// <summary>
/// Generates token containing user claims. The token is compressed, encrypted using machine key and returned as base64 string - this string will be saved inside RememberMeToken cookie
/// </summary>
private static string GenerateProtectedAndBase64EncodedClaimsToken(List<SerializableClaim> claimsToAdd)
{
var allClaimsAsString = JsonConvert.SerializeObject(claimsToAdd);
var allClaimsAsBytes = Encoding.UTF8.GetBytes(allClaimsAsString);
var allClaimsAsCompressedBytes = CompressionHelper.CompressDeflate(allClaimsAsBytes);
var allClaimsAsCompressedBytesProtected = MachineKey.Protect(allClaimsAsCompressedBytes, "RememberMeToken");
var allClaimsInFinalCompressedAndProtectedBase64Token = Convert.ToBase64String(allClaimsAsCompressedBytesProtected);
return allClaimsInFinalCompressedAndProtectedBase64Token;
}
/// <summary>
/// Primary login method
/// </summary>
private void Login(IOwinContext context)
{
var base64ProtectedCompressedRememberMeTokenBytes = context.Request.Cookies["RememberMeToken"];
if (!string.IsNullOrEmpty(base64ProtectedCompressedRememberMeTokenBytes))
{
var RememberMeToken = GetRememberMeTokenFromData(base64ProtectedCompressedRememberMeTokenBytes);
var claims = JsonConvert.DeserializeObject<IEnumerable<SerializableClaim>>(RememberMeToken);
bool isRememberMeTokenStillValid = IsRememberMeTokenStillValid(claims);
if (isRememberMeTokenStillValid)
{
//Token is still valid - sign in
SignInUser(context, claims);
//We set information that user was signed in using the RememberMeToken cookie
context.Set("SignedInFromRememberMeToken", true);
}
else
{
//Token is invalid or expired - we remove unnecessary cookie
context.Response.Cookies.Delete("RememberMeToken");
}
}
}
/// <summary>
/// We log user, using passed claims
/// </summary>
private void SignInUser(IOwinContext context, IEnumerable<SerializableClaim> claims)
{
List<Claim> claimList = new List<Claim>();
foreach (var item in claims)
{
string type = item.Type;
string value = item.Value;
claimList.Add(new Claim(type, value));
}
ClaimsIdentity ci = new ClaimsIdentity(claimList, DefaultAuthenticationTypes.ApplicationCookie);
context.Authentication.SignIn(ci);
context.Authentication.User = context.Authentication.AuthenticationResponseGrant.Principal;
}
/// <summary>
/// Get information if RememberMeToken cookie is still valid (checks not only the date, but also some additional information)
/// </summary>
private bool IsRememberMeTokenStillValid(IEnumerable<SerializableClaim> claims)
{
var userIdClaim = claims.Where(x => x.Type == ClaimTypes.NameIdentifier).SingleOrDefault();
if (userIdClaim == null)
{
throw new Exception("RememberMeTokenAuthMiddleware. Claim of type NameIdentifier was not found.");
}
var userSecurityStampClaim = claims.Where(x => x.Type == "AspNet.Identity.SecurityStamp").SingleOrDefault();
if (userSecurityStampClaim == null)
{
throw new Exception("RememberMeTokenAuthMiddleware. Claim of type SecurityStamp was not found.");
}
string userId = userIdClaim.Value;
var userManager = Context.GetUserManager<ApplicationUserManager>();
if (userManager == null)
{
throw new Exception("RememberMeTokenAuthMiddleware. Unable to get UserManager");
}
var currentUserData = userManager.FindById(userId);
if (currentUserData == null)
{
return false;
}
if (currentUserData.LockoutEndDateUtc >= DateTime.Now)
{
return false;
}
if (currentUserData.SecurityStamp != userSecurityStampClaim.Value)
{
//User Securitystamp was changed
return false;
}
return GetRememberMeTokenExpirationMinutesLeft(claims) > 0;
}
/// <summary>
/// Returns how many minutes the RememberMeToken will be valid - if it expired, returns zero or negative value
/// </summary>
private double GetRememberMeTokenExpirationMinutesLeft(IEnumerable<SerializableClaim> claims)
{
double dataToReturn = -1;
var RememberMeTokenExpirationDate = GetRememberMeTokenExpirationDate(claims);
dataToReturn = (RememberMeTokenExpirationDate - DateTime.Now).TotalMinutes;
return dataToReturn;
}
/// <summary>
/// Returns a DateTime object containing the expiration date of the RememberMeToken
/// </summary>
private DateTime GetRememberMeTokenExpirationDate(IEnumerable<SerializableClaim> claims)
{
DateTime RememberMeTokenExpirationDate = DateTime.Now.AddDays(-1);
var RememberMeTokenExpirationClaim = GetRememberMeTokenExpirationDateClaim(claims);
if (RememberMeTokenExpirationClaim == null)
{
throw new Exception("RememberMeTokenAuthMiddleware. RememberMeTokenExpirationClaim was not found.");
}
long binaryTime = Convert.ToInt64(RememberMeTokenExpirationClaim.Value);
RememberMeTokenExpirationDate = DateTime.FromBinary(binaryTime);
return RememberMeTokenExpirationDate;
}
/// <summary>
/// Returns the claim determining the expiration date of the token
/// </summary>
private SerializableClaim GetRememberMeTokenExpirationDateClaim(IEnumerable<SerializableClaim> claims)
{
var RememberMeTokenExpirationClaim = claims.Where(x => x.Type == "RememberMeTokenExpirationDate").SingleOrDefault();
return RememberMeTokenExpirationClaim;
}
/// <summary>
/// Attempts to decipher the RememberMeToken to the JSON format containing claims
/// </summary>
private string GetRememberMeTokenFromData(string base64ProtectedCompressedRememberMeTokenBytes)
{
var protectedCompressedRememberMeTokenBytes = Convert.FromBase64String(base64ProtectedCompressedRememberMeTokenBytes);
var compressedRememberMeTokenBytes = MachineKey.Unprotect(protectedCompressedRememberMeTokenBytes, "RememberMeToken");
var RememberMeTokenBytes = CompressionHelper.DecompressDeflate(compressedRememberMeTokenBytes);
var RememberMeToken = Encoding.UTF8.GetString(RememberMeTokenBytes);
return RememberMeToken;
}
/// <summary>
/// Returns information if token cookie should be delated (for example, when user click 'Logout')
/// </summary>
private bool CheckIfRememberMeTokenShouldBeDeleted(IOwinContext context)
{
bool shouldDeleteRememberMeToken = (context.Request.Cookies.Where(x => x.Key == "RemoveRememberMeToken").Count() > 0);
return shouldDeleteRememberMeToken;
}
#endregion
}
}
And some helper classes:
CompressionHelper.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Web;
namespace WebApplicationtoRemove.Owin.HelperClasses
{
/// <summary>
/// Data compression helper
/// </summary>
public static class CompressionHelper
{
public static byte[] CompressDeflate(byte[] data)
{
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(output, CompressionLevel.Optimal))
{
dstream.Write(data, 0, data.Length);
}
return output.ToArray();
}
public static byte[] DecompressDeflate(byte[] data)
{
MemoryStream input = new MemoryStream(data);
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
return output.ToArray();
}
}
}
SerializableClaim.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplicationtoRemove.Owin.HelperClasses
{
public class SerializableClaim
{
public string Type { get; set; }
public string ValueType { get; set; }
public string Value { get; set; }
}
}
To test the above - create new MVC 4.6.x project (authentication mode: Individual User Accounts), add the above classes to it and then modify the Startup.Auth.cs:
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using WebApplicationtoRemove.Models;
using WebApplicationtoRemove.Owin.Middleware;
namespace WebApplicationtoRemove
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
OnResponseSignedIn = ctx =>
{
RememberMeTokenMiddleware.CheckAndCreateRememberMeToken(ctx);
},
OnResponseSignOut = ctx =>
{
RememberMeTokenMiddleware.Logout(ctx.OwinContext);
}
}
});
app.Use<RememberMeTokenMiddleware>();
}
}
}
What interests you there are these:
OnResponseSignedIn = ctx =>
{
RememberMeTokenMiddleware.CheckAndCreateRememberMeToken(ctx);
},
OnResponseSignOut = ctx =>
{
RememberMeTokenMiddleware.Logout(ctx.OwinContext);
}
and this line:
app.Use<RememberMeTokenMiddleware>();
This should enable the middleware. How this works: if the user checks 'Remember me' checkbox, a RememberMeToken cookie will be created (containing all the claims user had during login) alongside the 'AspNet.ApplicationCookie'.
When the session times out, the middleware will check if the RememberMeToken exists, and is still valid - if so: it will log in the user seamlessly in background.
Hope this helps anyone.

WCF services, loading data from database

I have some problem with WCF services in asp.net mvc application.
Help me please!
When I run my project some data for some entities are loading from database, but some data are not loading(Internal server error).
Code and description of exceptions:
EntityTypeController:
public HttpResponseMessage GetAll()
{
//for debug
var t = EntityTypeService.GetAll();
//some exception here!
/*
The request channel timed out while waiting for a reply after 00:00:59.9979999.
Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding.
The time allotted to this operation may have been a portion of a longer timeout.
*/
//SendTimeout is 00:30:00 for all services.
or
/*The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.*/
or
/*An error occurred while receiving the HTTP response to http://localhost:18822/Services/Department.svc.
This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an
HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.*/
return CreateResponse<IEnumerable<EntityType>>(EntityTypeService.GetAll);
}
EntityTypeService:
public class EntityTypeService : BaseService<Base.Entities.EntityType>, IEntityTypeService
{
public IQueryable<Base.Entities.EntityType> GetAll()
{
var t = Repository.Get();
return t;
}
}
Repository:
public class Repository<TEntity>: IRepository<TEntity> where TEntity: BaseEntity
{
[Inject]
public IDataContext Context { get; set; }
[Inject]
public IDatabase DataSource { get; set; }
/// <summary>
/// Get entities from repository
/// </summary>
/// <param name="filter">Filter</param>
/// <param name="orderBy">Order by property</param>
/// <param name="includeProperties"></param>
/// <returns></returns>
public virtual IQueryable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
var query = Context.Set<TEntity>().AsQueryable();
// Apply filter
filter.Do((s) => {
query = query.Where(filter);
});
// Apply includes
foreach (var includeProperty in includeProperties.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
// Apply order by if need
var result = orderBy
.With(x => x(query))
.Return(x => x, query);
return result;
}
/// <summary>
/// Find entity by key
/// </summary>
/// <param name="id">Identificator</param>
/// <returns>Entity</returns>
public virtual TEntity GetById(object id)
{
//throw new NotImplementedException();
return Context.Set<TEntity>().Find(id);
}
/// <summary>
/// Add new entity to repository
/// </summary>
/// <param name="entity">New entity</param>
public virtual void Insert(TEntity entity)
{
AttachIsNotAttached(entity);
Context.Set<TEntity>().Add(entity);
Context.SaveChanges();
}
/// <summary>
/// Updated entity in repositoy
/// </summary>
/// <param name="entity">Entity</param>
public virtual void Update(TEntity entity)
{
AttachIsNotAttached(entity);
Context.Entry(entity).State = EntityState.Modified;
Context.SaveChanges();
}
/// <summary>
/// Remove entity from rpository
/// </summary>
/// <param name="entity">Entity</param>
public virtual void Delete(TEntity entity)
{
AttachIsNotAttached(entity);
Context.Set<TEntity>().Remove(entity);
Context.Entry(entity).State = EntityState.Deleted;
Context.SaveChanges();
}
/// <summary>
/// Return models error
/// </summary>
/// <returns></returns>
public IEnumerable<object> GetValidationModelErrors()
{
return Context.GetValidationErrors();
}
/// <summary>
/// Attach entity
/// </summary>
/// <param name="entity"></param>
protected void AttachIsNotAttached(TEntity entity)
{
if (Context.Entry(entity).State == EntityState.Detached)
{
var attached = Context.Set<TEntity>().Local.Where(x => x.Id == entity.Id).FirstOrDefault();
attached.Do((s) => {
Context.Entry(s).State = EntityState.Detached;
});
Context.Set<TEntity>().Attach(entity);
}
}
}
By default the wcf config has many limitations like the max size of array, and the exception doesnt exactly what happens,maybe in your case it's due to the default wcf config, I advice you to use svcTraceViewer, it will help you a lot to understand what happen exactly with an explicit messages.

How can I get ExtraData from OAuthWebSecurity?

(MVC 4)
AuthConfig.cs in definition;
OAuthWebSecurity.RegisterFacebookClient(
appId: "21703538509...",
appSecret: "28cbbc965e8ff6c9dc57cac9e323..."
);
ExternalLoginCallback function in, OAuthWebSecurity.VerifyAuthentication returned results are (name,link,gender). However, I need the email address. How can I get the email address from Facebook?
To get email access you need to write a custom facebook provider.
Downloaded DotNetOpenAuth.AspNet.Clients.FacebookClient and added { "scope", "email, read_stream" },
public sealed class CustomFacebookClient : OAuth2Client
{
#region Constants and Fields
/// <summary>
/// The authorization endpoint.
/// </summary>
private const string AuthorizationEndpoint = "https://www.facebook.com/dialog/oauth";
/// <summary>
/// The token endpoint.
/// </summary>
private const string TokenEndpoint = "https://graph.facebook.com/oauth/access_token";
/// <summary>
/// The _app id.
/// </summary>
private readonly string appId;
/// <summary>
/// The _app secret.
/// </summary>
private readonly string appSecret;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="FacebookClient"/> class.
/// </summary>
/// <param name="appId">
/// The app id.
/// </param>
/// <param name="appSecret">
/// The app secret.
/// </param>
public CustomFacebookClient(string appId, string appSecret)
: base("facebook")
{
Requires.NotNullOrEmpty(appId, "appId");
Requires.NotNullOrEmpty(appSecret, "appSecret");
this.appId = appId;
this.appSecret = appSecret;
}
#endregion
#region Methods
/// <summary>
/// The get service login url.
/// </summary>
/// <param name="returnUrl">
/// The return url.
/// </param>
/// <returns>An absolute URI.</returns>
protected override Uri GetServiceLoginUrl(Uri returnUrl)
{
// Note: Facebook doesn't like us to url-encode the redirect_uri value
var builder = new UriBuilder(AuthorizationEndpoint);
builder.AppendQueryArgs(
new Dictionary<string, string> {
{ "client_id", this.appId },
{ "scope", "email, read_stream" },
{ "redirect_uri", returnUrl.AbsoluteUri }
});
return builder.Uri;
}
/// <summary>
/// The get user data.
/// </summary>
/// <param name="accessToken">
/// The access token.
/// </param>
/// <returns>A dictionary of profile data.</returns>
protected override IDictionary<string, string> GetUserData(string accessToken)
{
FacebookGraphData graphData;
var request =
WebRequest.Create(
"https://graph.facebook.com/me?access_token=" + FacebookClientHelper.EscapeUriDataStringRfc3986(accessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
graphData = FacebookClientHelper.Deserialize<FacebookGraphData>(responseStream);
}
}
// this dictionary must contains
var userData = new Dictionary<string, string>();
userData.AddItemIfNotEmpty("id", graphData.Id);
userData.AddItemIfNotEmpty("username", graphData.Email);
userData.AddItemIfNotEmpty("name", graphData.Name);
userData.AddItemIfNotEmpty("link", graphData.Link == null ? null : graphData.Link.AbsoluteUri);
userData.AddItemIfNotEmpty("gender", graphData.Gender);
userData.AddItemIfNotEmpty("birthday", graphData.Birthday);
userData.AddItemIfNotEmpty("email", graphData.Email);
return userData;
}
/// <summary>
/// Obtains an access token given an authorization code and callback URL.
/// </summary>
/// <param name="returnUrl">
/// The return url.
/// </param>
/// <param name="authorizationCode">
/// The authorization code.
/// </param>
/// <returns>
/// The access token.
/// </returns>
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
{
// Note: Facebook doesn't like us to url-encode the redirect_uri value
var builder = new UriBuilder(TokenEndpoint);
builder.AppendQueryArgs(
new Dictionary<string, string> {
{ "client_id", this.appId },
{ "redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri) },
{ "client_secret", this.appSecret },
{ "code", authorizationCode },
});
using (WebClient client = new WebClient())
{
string data = client.DownloadString(builder.Uri);
if (string.IsNullOrEmpty(data))
{
return null;
}
var parsedQueryString = HttpUtility.ParseQueryString(data);
return parsedQueryString["access_token"];
}
}
/// <summary>
/// Converts any % encoded values in the URL to uppercase.
/// </summary>
/// <param name="url">The URL string to normalize</param>
/// <returns>The normalized url</returns>
/// <example>NormalizeHexEncoding("Login.aspx?ReturnUrl=%2fAccount%2fManage.aspx") returns "Login.aspx?ReturnUrl=%2FAccount%2FManage.aspx"</example>
/// <remarks>
/// There is an issue in Facebook whereby it will rejects the redirect_uri value if
/// the url contains lowercase % encoded values.
/// </remarks>
private static string NormalizeHexEncoding(string url)
{
var chars = url.ToCharArray();
for (int i = 0; i < chars.Length - 2; i++)
{
if (chars[i] == '%')
{
chars[i + 1] = char.ToUpperInvariant(chars[i + 1]);
chars[i + 2] = char.ToUpperInvariant(chars[i + 2]);
i += 2;
}
}
return new string(chars);
}
#endregion
}
Also, one could think this could work:
var parameters = new Dictionary<string, object>();
parameters["scope"] = "email";
OAuthWebSecurity.RegisterFacebookClient(appId: "appId", appSecret: "appSecret",
"facebook, parameters);
This doesn't work. It gives extra data for your providers, which you can use when you present your providers in views.
<img src="#provder.ExtraData["icon"]"/>

Resources