|
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; |
|
} |
|
} |
|
} |