Skip to content

Instantly share code, notes, and snippets.

@woloski
Created May 29, 2013 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woloski/5670691 to your computer and use it in GitHub Desktop.
Save woloski/5670691 to your computer and use it in GitHub Desktop.
ServiceStack WIF cookie auth provider
using System.Linq;
using System.Threading;
using Microsoft.IdentityModel.Claims;
using ServiceStack.Common.Web;
using ServiceStack.Configuration;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.Auth;
namespace YourApp
{
public class WifCookieAuthProvider : AuthProvider
{
public static string Name = "wifcookie";
public static string Realm = "/auth/wifcookie";
public WifCookieAuthProvider(IResourceManager appSettings)
: base(appSettings, Realm, Name) { }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
{
var identity = Thread.CurrentPrincipal.Identity as IClaimsIdentity;
if (identity != null && identity.IsAuthenticated)
{
session.Email = GetClaim(identity, ClaimTypes.Email);
session.FirstName = GetClaim(identity, ClaimTypes.GivenName);
session.LastName = GetClaim(identity, ClaimTypes.Surname);
session.UserName = GetClaim(identity, ClaimTypes.Name, ClaimTypes.NameIdentifier);
session.UserAuthId = GetClaim(identity, ClaimTypes.NameIdentifier, ClaimTypes.Name);
session.UserAuthName = GetClaim(identity, ClaimTypes.Name, ClaimTypes.NameIdentifier);
session.IsAuthenticated = true;
authService.SaveSession(session);
return new AuthResponse
{
UserName = session.UserName,
SessionId = session.Id
};
}
throw HttpError.Unauthorized("User is not authenticated");
}
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null)
{
bool authorized = !string.IsNullOrEmpty(session.UserAuthName);
return authorized;
}
public static string GetClaim(IClaimsIdentity identity, params string[] claimTypes)
{
foreach (var claimType in claimTypes)
{
var claim = identity.Claims.SingleOrDefault(c => c.ClaimType == claimType);
if (claim != null)
return claim.Value;
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment