I am currently using windows azure active directory as a single sign-on in my MVC.NET application and that portion works great. I can authenticate against WAAD and get my ClaimsPrinicipal loaded without any problems.
The next step was to transform the claims retrieved from WAAD by adding new claims from a different data source. To this extent I created a class inheriting the ClaimsAuthenticationManager (below). The claims get added to the Principal and get persisted to the session cookie in the CreateSession method.
My problem right now is that ClaimsPrincipal.Current does not carry any of the additional claims that I've added. When I set a breakpoint in the SessionAuthenticationModule_SessionSecurityTokenReceived event, I can see that there's a discrepancy between the ClaimsPrincipal.Current
ClaimsPrincipal.Current.FindAll(ClaimTypes.Email)
Count = 0
and e.SessionToken.ClaimsPrincipal.
e.SessionToken.ClaimsPrincipal.FindAll(ClaimTypes.Email)
Count = 1
[0]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress: me#mydomain.com}
What am I missing here? In all the samples that dealt with transforming claims that I could find there's no mention of manually reloading the ClaimsPrinicipal from the cookie. Would the session security token event be the right place to reload the ClaimsPrincipal or am I breaking the security model?
Thanks.
public class MyAuthenticationManager : ClaimsAuthenticationManager
{
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (!incomingPrincipal.Identity.IsAuthenticated)
{
return base.Authenticate(resourceName, incomingPrincipal);
}
var transformedPrincipal = this.CreateUserPrincipal(incomingPrincipal.Identity.Name);
this.CreateSession(transformedPrincipal);
return transformedPrincipal;
}
private ClaimsPrincipal CreateUserPrincipal(String userName)
{
List<Claim> claims = new List<Claim>();
var user = SecurityController.GetUserIdentity(userName);
claims.Add(new Claim(ClaimTypes.Name, userName));
claims.Add(new Claim(ClaimTypes.Email, user.Email));
claims.Add(new Claim(ClaimTypes.GivenName, user.FirstName));
claims.Add(new Claim(ClaimTypes.Surname, user.LastName));
return new ClaimsPrincipal(new ClaimsIdentity(claims, "MyCustom"));
}
private void CreateSession(ClaimsPrincipal transformedPrincipal)
{
var sessionSecurityToken = new SessionSecurityToken(transformedPrincipal, TimeSpan.FromHours(8));
if (FederatedAuthentication.SessionAuthenticationModule != null &&
FederatedAuthentication.SessionAuthenticationModule.ContainsSessionTokenCookie(HttpContext.Current.Request.Cookies))
{
return;
}
FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionSecurityToken);
//Added line below as per suggestion in one of the posts
//Doesn't seem to have any effect
Thread.CurrentPrincipal = transformedPrincipal;
FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenReceived += SessionAuthenticationModule_SessionSecurityTokenReceived;
}
void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("SessionAuthenticationModule_SessionSecurityTokenReceived");
}
Looks like I had to access the claims through ClaimsIdentity instead of ClaimsPrincipal. Now I can successfully access the claims from any view or controller in my application.
((ClaimsIdentity)Thread.CurrentPrincipal.Identity).FindAll(ClaimTypes.Email)
Count = 1
[0]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress: me#mydomain.com}
Final codebase in AuthenticationManager looks like this (note that there is no explicit assignment operation to the ClaimsPrincipal on the current thread).
public class MyAuthenticationManager : ClaimsAuthenticationManager
{
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (!incomingPrincipal.Identity.IsAuthenticated)
{
return base.Authenticate(resourceName, incomingPrincipal);
}
var transformedPrincipal = this.CreateUserPrincipal(incomingPrincipal.Identity.Name);
this.CreateSession(transformedPrincipal);
return transformedPrincipal;
}
private ClaimsPrincipal CreateUserPrincipal(String userName)
{
List<Claim> claims = new List<Claim>();
var user = SecurityController.GetUserIdentity(userName);
claims.Add(new Claim(ClaimTypes.Name, userName));
claims.Add(new Claim("UserId", user.Id.ToString()));
claims.Add(new Claim(ClaimTypes.Email, user.Email));
claims.Add(new Claim(ClaimTypes.GivenName, user.FirstName));
claims.Add(new Claim(ClaimTypes.Surname, user.LastName));
//claims.Add(new Claim(ClaimTypes.NameIdentifier, userName));
if (user.Account != null)
{
claims.Add(new Claim("AccountId", user.Account.Id.ToString()));
claims.Add(new Claim("AccountName", user.Account.Name.ToString()));
}
if (user.Owner != null)
{
claims.Add(new Claim("OwnerId", user.Owner.Id.ToString()));
claims.Add(new Claim("OwnerName", user.Owner.Name.ToString()));
}
return new ClaimsPrincipal(new ClaimsIdentity(claims, "MyCustom"));
}
private void CreateSession(ClaimsPrincipal transformedPrincipal)
{
if (FederatedAuthentication.SessionAuthenticationModule != null &&
FederatedAuthentication.SessionAuthenticationModule.ContainsSessionTokenCookie(HttpContext.Current.Request.Cookies))
{
return;
}
var sessionSecurityToken = new SessionSecurityToken(transformedPrincipal, TimeSpan.FromHours(8));
FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionSecurityToken);
}
}
I don't see you adding your ClaimsPrincipal (after the transformation) back to Thread.CurrentPrincipal. Please try
private void CreateSession(ClaimsPrincipal transformedPrincipal)
{
var sessionSecurityToken = new SessionSecurityToken(transformedPrincipal, TimeSpan.FromHours(8));
if (FederatedAuthentication.SessionAuthenticationModule != null &&
FederatedAuthentication.SessionAuthenticationModule.ContainsSessionTokenCookie(HttpContext.Current.Request.Cookies))
{
return;
}
FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionSecurityToken);
//Following is the missing line of code.
Thread.CurrentPrincipal = transformedPrincipal;
}
Related
After debugging through the code block, the user pass the user not null test but at Context.Validate() it returns invalid grant
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userStore = new UserStore<IdentityUser>(new ApplicationDbContext());
var manager = new UserManager<IdentityUser>(userStore);
var user = await manager.FindAsync(context.UserName, context.Password);
if(user !=null)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("Username", user.UserName));
identity.AddClaim(new Claim("Email", user.Email));
identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
context.Validated();
}
else
{
return;
}
}
You should pass the identity inside Validated() method. It is also a good idea to set context error if the user is not validated.
So it should look like below:
if(user !=null)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("Username", user.UserName));
identity.AddClaim(new Claim("Email", user.Email));
identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
I want to sign my users in using their email address from Facebook. I have configured my Facebook authentication:
var facebookAuthenticationOptions = new FacebookAuthenticationOptions
{
AppId = facebookId,
AppSecret = facebookSecret,
Provider = new FacebookProvider()
};
app.UseFacebookAuthentication(facebookAuthenticationOptions);
I have overridden the Facebook provider to also return the email address:
public class FacebookProvider : FacebookAuthenticationProvider
{
public override Task Authenticated(FacebookAuthenticatedContext context)
{
var accessTokenClaim = new Claim("ExternalAccessToken", context.AccessToken, "urn:facebook:access_token");
context.Identity.AddClaim(accessTokenClaim);
var extraClaims = GetAdditionalFacebookClaims(accessTokenClaim);
context.Identity.AddClaim(new Claim(ClaimTypes.Email, extraClaims.First(k => k.Key == "email").Value.ToString()));
context.Identity.AddClaim(new Claim("Provider", context.Identity.AuthenticationType));
context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Identity.FindFirstValue(ClaimTypes.Name)));
var userDetail = context.User;
var link = userDetail.Value<string>("link") ?? string.Empty;
context.Identity.AddClaim(new Claim("link", link));
context.Identity.AddClaim(new Claim("FacebookId", userDetail.Value<string>("id")));
return Task.FromResult(0);
}
private static JsonObject GetAdditionalFacebookClaims(Claim accessToken)
{
var fb = new FacebookClient(accessToken.Value);
return fb.Get("me", new { fields = new[] { "email" } }) as JsonObject;
}
Everything works fine in MVC - in the LoginOwinCallback function, I am able to retrieve the user's email address as returned from Facebook. I am trying to achieve the same thing in WebApi using token authentication instead of external cookies. However, although I can see my provider adding the email claim to the response, when I call the AuthenticateAsync method in the following routine, the Email claim is not included.
private async Task<ExternalLoginInfo> GetExternalLoginInfoAsync()
{
var result = await Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ExternalBearer);
if (result == null || result.Identity == null) return null;
var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
if (idClaim != null)
{
return new ExternalLoginInfo()
{
DefaultUserName = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", ""),
ExternalIdentity = result.Identity,
Login = new UserLoginInfo(idClaim.Issuer, idClaim.Value)
};
}
return null;
}
Any ideas what I am doing wrong?
For anyone else facing the same problem, the Email claim is available - just a bit hidden.
Firstly, to correctly retrieve the user's email address from Facebook, the authentication set-up in the ConfigureAuth method of Startup.Auth.cs should be:
app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
AppId = facebookId,
AppSecret = facebookSecret,
Scope= {"email"},
UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=email"
});
In the LoginOwinCallback method of the MVC AccountController class, the email address is found in the Email property of the ExternalLoginInfo object returned by var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();.
To retrieve the email address in the WebAPI AccountController class, you will need to cast the User.Identity object to the ClaimsIdentity type.
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
if (error != null)
{
return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
}
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
// get all of the claims
var claimsIdentity = User.Identity as ClaimsIdentity; // this cast exposes all of the claims returned by Facebook
// get the external login details
var externalLogin = ExternalLoginData.FromIdentity(claimsIdentity);
if (externalLogin == null)
{
return InternalServerError();
}
if (externalLogin.LoginProvider != provider)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
return new ChallengeResult(provider, this);
}
var user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
externalLogin.ProviderKey));
var hasRegistered = user != null;
if (hasRegistered)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
var cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);
var properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
AuthenticationManager.SignIn(properties, oAuthIdentity, cookieIdentity);
}
else
{
var claims = claimsIdentity?.Claims ?? externalLogin.GetClaims();
var identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
AuthenticationManager.SignIn(identity);
}
return Ok();
}
This means you can then use the FindFirst method on the Identity to find the email claim returned by Facebook.
I am developing an intranet Web App using windows auth. I am using Claims Transformation using custom ClaimsAuthenticationManager.
public class ClaimsTransformer : ClaimsAuthenticationManager
{
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (!incomingPrincipal.Identity.IsAuthenticated)
{
return base.Authenticate(resourceName, incomingPrincipal);
}
var newPrinciPal = CreateApplicationPrincipal(incomingPrincipal.Identity.Name);
EstablishSession(newPrinciPal);
return newPrinciPal;
}
private void EstablishSession(ClaimsPrincipal newPrinciPal)
{
var sessionToken = new SessionSecurityToken(newPrinciPal, TimeSpan.FromHours(8))
{
IsPersistent = false,
IsReferenceMode = true
};
FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken);
}
private ClaimsPrincipal CreateApplicationPrincipal(string userName)
{
new SecurityManager().LoginUser(userName);
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, userName));
RPSUser originalIdentity = Thread.CurrentPrincipal.Identity as RPSUser;
if (originalIdentity != null)
{
RPSUserInformation userDetails = originalIdentity.UserDetails;
int splitIndex = userDetails.FullName.IndexOf(' ');
claims.Add(new Claim(ClaimTypes.GivenName, userDetails.FullName.Substring(0, splitIndex)));
claims.Add(new Claim(ClaimTypes.Surname, userDetails.FullName.Substring(splitIndex + 1)));
claims.Add(new Claim(ClaimTypes.Email, userDetails.Email));
claims.Add(new Claim(ClaimTypes.WindowsAccountName, userDetails.LanId));
}
RPSUser transformedIdentity = new RPSUser(new ClaimsIdentity(claims, "Custom"));
transformedIdentity.UserDetails = originalIdentity.UserDetails;
return new RPSPrincipal(transformedIdentity, null);
}
}
In Global.ascx I have this code
protected void Application_PostAuthenticateRequest()
{
try
{
var newPrincipal = FederatedAuthentication.FederationConfiguration
.IdentityConfiguration
.ClaimsAuthenticationManager.Authenticate(string.Empty, ClaimsPrincipal.Current);
SecurityManager.SetIdentityToThread(newPrincipal as RPSPrincipal);
}
catch
{
}
}
Also I am able to retrieve/deserialize the Cookie from this piece of code in Global.asax
void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
var extendSession = true;
if (Request.UrlReferrer.AbsolutePath.Equals("/"))
{
var principal = e.SessionToken.ClaimsPrincipal as RPSPrincipal;
SecurityManager.SetIdentityToThread(principal);
if (extendSession)
{
e.SessionToken = new SessionSecurityToken(
e.SessionToken.ClaimsPrincipal,
TimeSpan.FromHours(8))
{
IsPersistent = false,
IsReferenceMode = true
};
e.ReissueCookie = extendSession;
}
}
}
But the problem is even though I am able to deserialize the cookie to the custom Principal (RPSPrincipal) in this event and able to set it to thread, subsequently in the Application_PostAuthenticateRequest (for the same request) we are losing the Custom Principal. We are just getting ClaimsPrincipal there.
What am I doing wrong here? How could I ensure that windows authentication does not overwrite principal when there is a custom principal is already set and IsAuthenticated property of Identity is already set to true?
Or is there anyway to access the sessionSecurityToken at Application_PostAuthenticateRequest event?
I am kind of successful by doing this in the Startup.Auth.cs file
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.Properties["Microsoft.Owin.Security.Constants.DefaultSignInAsAuthenticationType"] = "ExternalCookie";
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri
});
The challenge I have is, when a user is signed out,and tries to hit a non-login page like say http://mywebsite/users/management rather than http://mywebsite/account/login the application redirects to the Azure AD sign-in page automatically, which is not right. Because there could be users who do not have account on Azure AD at all. Even if we give a proper userid and password in the AD sign in page and click sign-in, it keeps redirecting between different urls within http://login.windows.net and never goes to our website at all.
Here is the logout code -
AuthenticationManager.SignOut(new string[] { DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ApplicationCookie, OpenIdConnectAuthenticationDefaults.AuthenticationType });
return RedirectToAction("Login", "Account");
I am not sure what I'm doing wrong here.
Edit 1
My ExternalLoginCallback method
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Sid, "Office365"));
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindByEmailAsync(loginInfo.ExternalIdentity.Name);
if (user != null && user.IsActive == true && user.EmailConfirmed == true)
{
var result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
if (result.Succeeded)
{
if (claims != null)
{
var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
userIdentity.AddClaims(claims);
}
}
await SignInAsync(user, isPersistent: true);
Session[AppConstants.General.UserID] = user.Id;
string fullName = string.Format("{0} {1}",user.FirstName,user.LastName);
Session[AppConstants.General.UserFullName] = fullName;
return RedirectToLocal(returnUrl);
}
else
{
// If the user does not have an account, tell that to the user.
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
Try this
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ClientId,
Authority = Authority,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
RedirectToIdentityProvider = (context) =>
{
if (context.Request.Path.Value == "/Account/ExternalLogin" || (context.Request.Path.Value == "/Account/LogOff" && context.Request.User.Identity.IsExternalUser()))
{
// This ensures that the address used for sign in and sign out is picked up dynamically from the request
// this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
// Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
}
else
{
//This is to avoid being redirected to the microsoft login page when deep linking and not logged in
context.State = Microsoft.Owin.Security.Notifications.NotificationResultState.Skipped;
context.HandleResponse();
}
return Task.FromResult(0);
},
}
});
EDIT:
Forgot this extension method
public static class IdentityExtensions
{
public static bool IsExternalUser(this IIdentity identity)
{
ClaimsIdentity ci = identity as ClaimsIdentity;
if (ci != null && ci.IsAuthenticated == true)
{
var value = ci.FindFirstValue(ClaimTypes.Sid);
if (value != null && value == "Office365")
{
return true;
}
}
return false;
}
}
EDIT 2:
You have to have some custom logic in the ExternalLoginCallback (AccountController) e.g. add the Sid claim. In this case there is also logic to check if the user allows external login.
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl, string urlHash)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Sid, "Office365"));
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindAsync(loginInfo.Login);
if (user == null)
{
user = await UserManager.FindByNameAsync(loginInfo.DefaultUserName);
if (user != null)
{
if(user.AllowExternalLogin == false)
{
ModelState.AddModelError("", String.Format("User {0} not allowed to authenticate with Office 365.", loginInfo.DefaultUserName));
return View("Login");
}
var result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
if (result.Succeeded)
{
if (claims != null)
{
var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
userIdentity.AddClaims(claims);
}
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", String.Format("User {0} not found.", loginInfo.DefaultUserName));
return View("Login");
}
}
else
{
if (user.AllowExternalLogin == false)
{
ModelState.AddModelError("", String.Format("User {0} not allowed to authenticate with Office 365.", loginInfo.DefaultUserName));
return View("Login");
}
if (claims != null)
{
var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
userIdentity.AddClaims(claims);
}
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
I have created my own web api OAuth authentication server with my customized Microsoft.Owin implementation:
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/Auth/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
app.UseOAuthBearerTokens(OAuthOptions);
Now I want to use that OAuth authentication in an external mvc application but I've been really confused.
In fact my main concern is authorizing controllers and actions based on my existing OAuth server.
After 2 days research finally I implemented that based on a custom OAuthBearerAuthenticationProvider which is worked based on a cookie created during sign in process. The functionality works correctly But I think (actually I know) something is wrong.
this is my Custom OAuthBearerAuthenticationProvider :
public class ApplicationOAuthBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var tokenCookie = context.OwinContext.Request.Cookies["BearerToken"];
if (!string.IsNullOrEmpty(tokenCookie))
{
context.Token = tokenCookie;
}
return Task.FromResult<object>(null);
}
}
and this is my MVC auth startup configure method:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Auth/SignIn")
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
Provider = new ApplicationOAuthBearerAuthenticationProvider(),
});
}
If someone has related experience please advise me.
UPDATE: I think finally I found a solution.
In my solution during sign in process I create a ticket and protect that inside OAuthBearerOptions which is defined inside Startup.Auth class.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SignIn(LoginPageModel pageModel, string returnUrl)
{
if (!ModelState.IsValid)
{
return RedirectToAction("SignIn", new { returnUrl = returnUrl });
}
try
{
var result = await AuthService.Instance.AuthenticateAsync(pageModel.LoginModel);
CreateIdentity(result);
return RedirectToLocal(returnUrl);
}
catch (Exception ex)
{
return RedirectToAction("SignIn", new { returnUrl = returnUrl });
}
}
private void CreateIdentity(TokenResponseModel result)
{
IDictionary< String, String> data = new Dictionary< String, String>
{
{ "userName", result.Username }
};
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, result.Username));
claims.Add(new Claim(ClaimTypes.Email, result.Username));
if (!String.IsNullOrEmpty(result.ExternalIdentity))
{
claims.Add(new Claim(CustomClaimTypes.ExternalIdentity, result.ExternalIdentity));
}
if (result.Roles != null && result.Roles.Length != 0)
{
foreach (var role in result.Roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
}
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationProperties properties = new AuthenticationProperties(data);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
AuthenticationManager.SignIn(cookiesIdentity);
}
And the Auth Configure is changed to this:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Auth/SignIn"),
});
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}