public AuthenticationController( OwinEnvironmentService owin, IViewService viewService, IUserService userService, IdentityServerOptions idSvrOptions, IClientStore clientStore, IEventService eventService, ILocalizationService localizationService, SessionCookie sessionCookie, MessageCookie <SignInMessage> signInMessageCookie, MessageCookie <SignOutMessage> signOutMessageCookie, LastUserNameCookie lastUsernameCookie, AntiForgeryToken antiForgeryToken) { this.context = new OwinContext(owin.Environment); this.viewService = viewService; this.userService = userService; this.options = idSvrOptions; this.clientStore = clientStore; this.eventService = eventService; this.localizationService = localizationService; this.sessionCookie = sessionCookie; this.signInMessageCookie = signInMessageCookie; this.signOutMessageCookie = signOutMessageCookie; this.lastUserNameCookie = lastUsernameCookie; this.antiForgeryToken = antiForgeryToken; }
protected string WriteMessageToCookie <T>(T msg) where T : Message { var cookieStates = client.DefaultRequestHeaders.GetCookies().SelectMany(c => c.Cookies); var requestCookies = cookieStates.Select(c => c.ToString()).ToArray(); var request_headers = new Dictionary <string, string[]> { { "Cookie", requestCookies } }; var response_headers = new Dictionary <string, string[]>(); var env = new Dictionary <string, object>() { { "owin.RequestScheme", "https" }, { "owin.RequestHeaders", request_headers }, { "owin.ResponseHeaders", response_headers }, { Constants.OwinEnvironment.IdentityServerBasePath, "/" }, }; var ctx = new OwinContext(env); var signInCookie = new MessageCookie <T>(ctx, options); var id = signInCookie.Write(msg); client.SetCookies(response_headers["Set-Cookie"]); return(id); }
/// <summary> /// Creates the sign out request. /// </summary> /// <param name="env">The env.</param> /// <param name="message">The message.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">message</exception> public static string CreateSignOutRequest(this IDictionary <string, object> env, SignOutMessage message) { if (message == null) { throw new ArgumentNullException("message"); } // if there's no return url, then use current request's URL if (message.ReturnUrl.IsMissing()) { var ctx = new OwinContext(env); message.ReturnUrl = ctx.Request.Uri.AbsoluteUri; } if (message.ReturnUrl.StartsWith("~/")) { message.ReturnUrl = message.ReturnUrl.Substring(1); } if (message.ReturnUrl.StartsWith("/")) { message.ReturnUrl = env.GetIdentityServerBaseUrl().RemoveTrailingSlash() + message.ReturnUrl; } var options = env.ResolveDependency <IdentityServerOptions>(); var cookie = new MessageCookie <SignOutMessage>(env, options); var id = cookie.Write(message); var url = env.GetIdentityServerBaseUrl() + Constants.RoutePaths.Logout; var uri = new Uri(url.AddQueryString("id=" + id)); return(uri.AbsoluteUri); }
public static string WriteMessageToCookie <T>(this IdentityServerHost host, T msg) where T : Message { var request_headers = new Dictionary <string, string[]>(); var response_headers = new Dictionary <string, string[]>(); var env = new Dictionary <string, object>() { { "owin.RequestScheme", "https" }, { "owin.RequestHeaders", request_headers }, { "owin.ResponseHeaders", response_headers }, { Constants.OwinEnvironment.IdentityServerBasePath, "/" }, }; var ctx = new OwinContext(env); var signInCookie = new MessageCookie <T>(ctx, host.Options); var id = signInCookie.Write(msg); CookieHeaderValue cookie; if (!CookieHeaderValue.TryParse(response_headers["Set-Cookie"].First(), out cookie)) { throw new InvalidOperationException("MessageCookie failed to issue cookie"); } host.Client.AddCookies(cookie.Cookies); return(id); }
public AuthenticationController( OwinEnvironmentService owin, IViewService viewService, IUserService userService, IdentityServerOptions idSvrOptions, IClientStore clientStore, IEventService eventService, ILocalizationService localizationService, SessionCookie sessionCookie, MessageCookie<SignInMessage> signInMessageCookie, MessageCookie<SignOutMessage> signOutMessageCookie, LastUserNameCookie lastUsernameCookie, AntiForgeryToken antiForgeryToken) { this.context = new OwinContext(owin.Environment); this.viewService = viewService; this.userService = userService; this.options = idSvrOptions; this.clientStore = clientStore; this.eventService = eventService; this.localizationService = localizationService; this.sessionCookie = sessionCookie; this.signInMessageCookie = signInMessageCookie; this.signOutMessageCookie = signOutMessageCookie; this.lastUsernameCookie = lastUsernameCookie; this.antiForgeryToken = antiForgeryToken; }
private SignOutMessage GetSignOutMessage(string id) { if (!String.IsNullOrWhiteSpace(id)) { var cookie = new MessageCookie <SignOutMessage>(Request.GetOwinContext(), this._options); return(cookie.Read(id)); } return(null); }
public async Task <IHttpActionResult> LoginExternalCallback() { Logger.Info("Callback invoked from external identity provider "); var signInId = await GetSignInIdFromExternalProvider(); if (signInId.IsMissing()) { Logger.Error("No signin id passed"); return(RenderErrorPage()); } var cookie = new MessageCookie <SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signInId); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return(RenderErrorPage()); } var user = await GetIdentityFromExternalProvider(); if (user == null) { Logger.Error("no identity from external identity provider"); return(await RenderLoginPage(signInMessage, signInId, Messages.NoMatchingExternalAccount)); } var externalIdentity = ExternalIdentity.FromClaims(user.Claims); if (externalIdentity == null) { Logger.Error("no subject or unique identifier claims from external identity provider"); return(await RenderLoginPage(signInMessage, signInId, Messages.NoMatchingExternalAccount)); } Logger.InfoFormat("external user provider: {0}, provider ID: {1}", externalIdentity.Provider, externalIdentity.ProviderId); var authResult = await _userService.AuthenticateExternalAsync(externalIdentity); if (authResult == null) { Logger.Warn("user service failed to authenticate external identity"); return(await RenderLoginPage(signInMessage, signInId, Messages.NoMatchingExternalAccount)); } if (authResult.IsError) { Logger.WarnFormat("user service returned error message: {0}", authResult.ErrorMessage); return(await RenderLoginPage(signInMessage, signInId, authResult.ErrorMessage)); } return(SignInAndRedirect(signInMessage, signInId, authResult)); }
private HttpResponseMessage Execute() { Logger.Info("Redirecting to login page"); var cookie = new MessageCookie<SignInMessage>(this.env, this.options); var id = cookie.Write(this.message); var url = env.GetIdentityServerBaseUrl() + Constants.RoutePaths.Login; var uri = new Uri(url.AddQueryString("signin=" + id)); var response = new HttpResponseMessage(HttpStatusCode.Redirect); response.Headers.Location = uri; return response; }
private HttpResponseMessage Execute() { Logger.Info("Redirecting to login page"); var cookie = new MessageCookie <SignInMessage>(this.env, this.options); var id = cookie.Write(this.message); var url = env.GetIdentityServerBaseUrl() + Constants.RoutePaths.Login; var uri = new Uri(url.AddQueryString("signin=" + id)); var response = new HttpResponseMessage(HttpStatusCode.Redirect); response.Headers.Location = uri; return(response); }
/// <summary> /// Gets the sign in message. /// </summary> /// <param name="env">The OWIN environment.</param> /// <param name="id">The signin identifier.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// env /// or /// id /// </exception> public static SignInMessage GetSignInMessage(this IDictionary <string, object> env, string id) { if (env == null) { throw new ArgumentNullException("env"); } if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException("id"); } var options = env.ResolveDependency <IdentityServerOptions>(); var cookie = new MessageCookie <SignInMessage>(env, options); return(cookie.Read(id)); }
public async Task <IHttpActionResult> LoginExternal(string signin, string provider) { Logger.InfoFormat("External login requested for provider: {0}", provider); if (provider.IsMissing()) { Logger.Error("No provider passed"); return(RenderErrorPage()); } if (signin.IsMissing()) { Logger.Error("No signin id passed"); return(RenderErrorPage()); } var cookie = new MessageCookie <SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signin); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return(RenderErrorPage()); } var providerFilter = await GetProviderFilterForClientAsync(signInMessage); if (providerFilter != null && providerFilter.Any() && !providerFilter.Contains(provider)) { Logger.ErrorFormat("Provider {0} not allowed for client: {1}", provider, signInMessage.ClientId); return(RenderErrorPage()); } var authProp = new Microsoft.Owin.Security.AuthenticationProperties { RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null) }; // add the id to the dictionary so we can recall the cookie id on the callback authProp.Dictionary.Add(Constants.Authentication.SigninId, signin); authProp.Dictionary.Add(Constants.Authentication.KatanaAuthenticationType, provider); Request.GetOwinContext().Authentication.Challenge(authProp, provider); return(Unauthorized()); }
private string WriteMessageToCookie <T>(T msg) where T : class { var headers = new Dictionary <string, string[]>(); var env = new Dictionary <string, object>() { { "owin.RequestScheme", "https" }, { "owin.ResponseHeaders", headers } }; var ctx = new OwinContext(env); var signInCookie = new MessageCookie <T>(ctx, this.options); var id = signInCookie.Write(msg); client.SetCookies(headers["Set-Cookie"]); return(id); }
/// <summary> /// Creates and writes the signin cookie to the response and returns the associated URL to the login page. /// </summary> /// <param name="env">The OWIN environment.</param> /// <param name="message">The signin message.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// env /// or /// message /// </exception> public static string CreateSignInRequest(this IDictionary <string, object> env, SignInMessage message) { if (env == null) { throw new ArgumentNullException("env"); } if (message == null) { throw new ArgumentNullException("message"); } // if there's no return url, then use current request's URL if (message.ReturnUrl.IsMissing()) { var ctx = new OwinContext(env); message.ReturnUrl = ctx.Request.Uri.AbsoluteUri; } if (message.ReturnUrl.StartsWith("~/")) { message.ReturnUrl = message.ReturnUrl.Substring(1); } if (message.ReturnUrl.StartsWith("/")) { message.ReturnUrl = env.GetIdentityServerBaseUrl().RemoveTrailingSlash() + message.ReturnUrl; } var options = env.ResolveDependency <IdentityServerOptions>(); var cookie = new MessageCookie <SignInMessage>(env, options); var id = cookie.Write(message); var url = env.GetIdentityServerBaseUrl() + Constants.RoutePaths.Login; var queryString = HttpUtility.ParseQueryString(string.Empty); queryString.Add("signin", id); foreach (var queryStringParams in message.QueryString) { queryString.Add(queryStringParams.Key, queryStringParams.Value); } var uri = new Uri(url.AddQueryString(queryString.ToString())); return(uri.AbsoluteUri); }
public async Task <IHttpActionResult> Login(string signin) { Logger.Info("Login page requested"); if (signin.IsMissing()) { Logger.Error("No signin id passed"); return(RenderErrorPage()); } var cookie = new MessageCookie <SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signin); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return(RenderErrorPage()); } Logger.DebugFormat("signin message passed to login: {0}", JsonConvert.SerializeObject(signInMessage, Formatting.Indented)); var authResult = await _userService.PreAuthenticateAsync(Request.GetOwinEnvironment(), signInMessage); if (authResult != null) { if (authResult.IsError) { Logger.WarnFormat("user service returned an error message: {0}", authResult.ErrorMessage); return(RenderErrorPage(authResult.ErrorMessage)); } Logger.Info("user service returned a login result"); return(SignInAndRedirect(signInMessage, signin, authResult)); } if (signInMessage.IdP.IsPresent()) { Logger.InfoFormat("identity provider requested, redirecting to: {0}", signInMessage.IdP); return(Redirect(Url.Link(Constants.RouteNames.LoginExternal, new { provider = signInMessage.IdP, signin }))); } return(await RenderLoginPage(signInMessage, signin)); }
protected string WriteMessageToCookie <T>(T msg) where T : class { var headers = new Dictionary <string, string[]>(); var env = new Dictionary <string, object>() { { "owin.RequestScheme", "https" }, { "owin.ResponseHeaders", headers }, { Constants.OwinEnvironment.IdentityServerBasePath, "/" }, }; var ctx = new OwinContext(env); var signInCookie = new MessageCookie <T>(ctx, options); var id = signInCookie.Write(msg); client.SetCookies(headers["Set-Cookie"]); return(id); }
/// <summary> /// Creates and writes the signin cookie to the response and returns the associated URL to the login page. /// </summary> /// <param name="env">The OWIN environment.</param> /// <param name="message">The signin message.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// env /// or /// message /// </exception> public static string CreateSignInRequest(this IDictionary <string, object> env, SignInMessage message) { if (env == null) { throw new ArgumentNullException("env"); } if (message == null) { throw new ArgumentNullException("message"); } var options = env.ResolveDependency <IdentityServerOptions>(); var cookie = new MessageCookie <SignInMessage>(env, options); var id = cookie.Write(message); var url = env.GetIdentityServerBaseUrl() + Constants.RoutePaths.Login; var uri = new Uri(url.AddQueryString("signin=" + id)); return(uri.AbsoluteUri); }
public async Task<IHttpActionResult> Login(string signin) { Logger.Info("Login page requested"); if (signin.IsMissing()) { Logger.Error("No signin id passed"); return RenderErrorPage(); } var cookie = new MessageCookie<SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signin); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return RenderErrorPage(); } Logger.DebugFormat("signin message passed to login: {0}", JsonConvert.SerializeObject(signInMessage, Formatting.Indented)); var authResult = await _userService.PreAuthenticateAsync(signInMessage); if (authResult != null) { if (authResult.IsError) { Logger.WarnFormat("user service returned an error message: {0}", authResult.ErrorMessage); return RenderErrorPage(authResult.ErrorMessage); } Logger.Info("user service returned a login result"); return SignInAndRedirect(signInMessage, signin, authResult); } if (signInMessage.IdP.IsPresent()) { Logger.InfoFormat("identity provider requested, redirecting to: {0}", signInMessage.IdP); return Redirect(Url.Link(Constants.RouteNames.LoginExternal, new { provider = signInMessage.IdP, signin })); } return await RenderLoginPage(signInMessage, signin); }
public IHttpActionResult LoginExternal(string signin, string provider) { Logger.InfoFormat("External login requested for provider: {0}", provider); if (provider.IsMissing()) { Logger.Error("No provider passed"); return(RenderErrorPage()); } if (signin.IsMissing()) { Logger.Error("No signin id passed"); return(RenderErrorPage()); } var cookie = new MessageCookie <SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signin); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return(RenderErrorPage()); } var authProp = new Microsoft.Owin.Security.AuthenticationProperties { RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null) }; // add the id to the dictionary so we can recall the cookie id on the callback authProp.Dictionary.Add("signin", signin); authProp.Dictionary.Add("katanaAuthenticationType", provider); Request.GetOwinContext().Authentication.Challenge(authProp, provider); return(Unauthorized()); }
public async Task<IHttpActionResult> LoginLocal(string signin, LoginCredentials model) { Logger.Info("Login page submitted"); if (this._options.AuthenticationOptions.EnableLocalLogin == false) { Logger.Warn("EnableLocalLogin disabled -- returning 405 MethodNotAllowed"); return StatusCode(HttpStatusCode.MethodNotAllowed); } if (signin.IsMissing()) { Logger.Error("No signin id passed"); return RenderErrorPage(); } var cookie = new MessageCookie<SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signin); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return RenderErrorPage(); } if (model == null) { Logger.Error("no data submitted"); return await RenderLoginPage(signInMessage, signin, Messages.InvalidUsernameOrPassword); } // the browser will only send 'true' if ther user has checked the checkbox // it will pass nothing if the user does not check the checkbox // this check here is to establish if the user deliberatly did not check the checkbox // or if the checkbox was not presented as an option (and thus AllowRememberMe is not allowed) // true means they did check it, false means they did not, null means they were not presented with the choice if (_options.AuthenticationOptions.CookieOptions.AllowRememberMe) { if (model.RememberMe != true) { model.RememberMe = false; } } else { model.RememberMe = null; } if (!ModelState.IsValid) { Logger.Warn("validation error: username or password missing"); return await RenderLoginPage(signInMessage, signin, ModelState.GetError(), model.Username, model.RememberMe == true); } var authResult = await _userService.AuthenticateLocalAsync(model.Username, model.Password, signInMessage); if (authResult == null) { Logger.WarnFormat("user service indicated incorrect username or password for username: {0}", model.Username); return await RenderLoginPage(signInMessage, signin, Messages.InvalidUsernameOrPassword, model.Username, model.RememberMe == true); } if (authResult.IsError) { Logger.WarnFormat("user service returned an error message: {0}", authResult.ErrorMessage); return await RenderLoginPage(signInMessage, signin, authResult.ErrorMessage, model.Username, model.RememberMe == true); } RaiseLocalLoginSuccessEvent(model.Username, signInMessage, authResult); IssueLastUsernameCookie(model.Username); return SignInAndRedirect(signInMessage, signin, authResult, model.RememberMe); }
public async Task <IHttpActionResult> LoginLocal(string signin, LoginCredentials model) { Logger.Info("Login page submitted"); if (this._options.AuthenticationOptions.EnableLocalLogin == false) { Logger.Warn("EnableLocalLogin disabled -- returning 405 MethodNotAllowed"); return(StatusCode(HttpStatusCode.MethodNotAllowed)); } if (signin.IsMissing()) { Logger.Error("No signin id passed"); return(RenderErrorPage()); } var cookie = new MessageCookie <SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signin); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return(RenderErrorPage()); } if (model == null) { Logger.Error("no data submitted"); return(await RenderLoginPage(signInMessage, signin, Messages.InvalidUsernameOrPassword)); } // the browser will only send 'true' if ther user has checked the checkbox // it will pass nothing if the user does not check the checkbox // this check here is to establish if the user deliberatly did not check the checkbox // or if the checkbox was not presented as an option (and thus AllowRememberMe is not allowed) // true means they did check it, false means they did not, null means they were not presented with the choice if (_options.AuthenticationOptions.CookieOptions.AllowRememberMe) { if (model.RememberMe != true) { model.RememberMe = false; } } else { model.RememberMe = null; } if (!ModelState.IsValid) { Logger.Warn("validation error: username or password missing"); return(await RenderLoginPage(signInMessage, signin, ModelState.GetError(), model.Username, model.RememberMe == true)); } var authResult = await _userService.AuthenticateLocalAsync(model.Username, model.Password, signInMessage); if (authResult == null) { Logger.WarnFormat("user service indicated incorrect username or password for username: {0}", model.Username); return(await RenderLoginPage(signInMessage, signin, Messages.InvalidUsernameOrPassword, model.Username, model.RememberMe == true)); } if (authResult.IsError) { Logger.WarnFormat("user service returned an error message: {0}", authResult.ErrorMessage); return(await RenderLoginPage(signInMessage, signin, authResult.ErrorMessage, model.Username, model.RememberMe == true)); } RaiseLocalLoginSuccessEvent(model.Username, signInMessage, authResult); return(SignInAndRedirect(signInMessage, signin, authResult, model.RememberMe)); }
public CookieMessageStore(MessageCookie <TModel> cookie) { _cookie = cookie; }
private void ClearSignInCookie(string signin) { var cookie = new MessageCookie<SignInMessage>(Request.GetOwinContext(), this._options); cookie.Clear(signin); }
private void ClearSignInCookies() { var cookie = new MessageCookie<SignInMessage>(Request.GetOwinContext(), this._options); cookie.ClearAll(); }
private SignOutMessage GetSignOutMessage(string id) { if (!String.IsNullOrWhiteSpace(id)) { var cookie = new MessageCookie<SignOutMessage>(Request.GetOwinContext(), this._options); return cookie.Read(id); } return null; }
public async Task<IHttpActionResult> ResumeLoginFromRedirect(string resume) { Logger.Info("Callback requested to resume login from partial login"); if (resume.IsMissing()) { Logger.Error("no resumeId passed"); return RenderErrorPage(); } var user = await GetIdentityFromPartialSignIn(); if (user == null) { Logger.Error("no identity from partial login"); return RenderErrorPage(); } var type = GetClaimTypeForResumeId(resume); var resumeClaim = user.FindFirst(type); if (resumeClaim == null) { Logger.Error("no claim matching resumeId"); return RenderErrorPage(); } var signInId = resumeClaim.Value; if (signInId.IsMissing()) { Logger.Error("No signin id found in resume claim"); return RenderErrorPage(); } var cookie = new MessageCookie<SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signInId); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return RenderErrorPage(); } AuthenticateResult result = null; var externalProviderClaim = user.FindFirst(Constants.ClaimTypes.ExternalProviderUserId); if (externalProviderClaim == null) { // the user/subject was known, so pass thru (without the redirect claims) user.RemoveClaim(user.FindFirst(Constants.ClaimTypes.PartialLoginReturnUrl)); user.RemoveClaim(user.FindFirst(GetClaimTypeForResumeId(resume))); result = new AuthenticateResult(new ClaimsPrincipal(user)); } else { // the user was not known, we need to re-execute AuthenticateExternalAsync // to obtain a subject to proceed var provider = externalProviderClaim.Issuer; var providerId = externalProviderClaim.Value; var externalId = new ExternalIdentity { Provider = provider, ProviderId = providerId, Claims = user.Claims }; result = await _userService.AuthenticateExternalAsync(externalId); if (result == null) { Logger.Warn("user service failed to authenticate external identity"); return await RenderLoginPage(signInMessage, signInId, Messages.NoMatchingExternalAccount); } if (result.IsError) { Logger.WarnFormat("user service returned error message: {0}", result.ErrorMessage); return await RenderLoginPage(signInMessage, signInId, result.ErrorMessage); } } return SignInAndRedirect(signInMessage, signInId, result); }
public async Task<IHttpActionResult> LoginExternalCallback() { Logger.Info("Callback invoked from external identity provider "); var signInId = await GetSignInIdFromExternalProvider(); if (signInId.IsMissing()) { Logger.Error("No signin id passed"); return RenderErrorPage(); } var cookie = new MessageCookie<SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signInId); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return RenderErrorPage(); } var user = await GetIdentityFromExternalProvider(); if (user == null) { Logger.Error("no identity from external identity provider"); return await RenderLoginPage(signInMessage, signInId, Messages.NoMatchingExternalAccount); } var externalIdentity = ExternalIdentity.FromClaims(user.Claims); if (externalIdentity == null) { Logger.Error("no subject or unique identifier claims from external identity provider"); return await RenderLoginPage(signInMessage, signInId, Messages.NoMatchingExternalAccount); } Logger.InfoFormat("external user provider: {0}, provider ID: {1}", externalIdentity.Provider, externalIdentity.ProviderId); var authResult = await _userService.AuthenticateExternalAsync(externalIdentity); if (authResult == null) { Logger.Warn("user service failed to authenticate external identity"); return await RenderLoginPage(signInMessage, signInId, Messages.NoMatchingExternalAccount); } if (authResult.IsError) { Logger.WarnFormat("user service returned error message: {0}", authResult.ErrorMessage); return await RenderLoginPage(signInMessage, signInId, authResult.ErrorMessage); } return SignInAndRedirect(signInMessage, signInId, authResult); }
public async Task<IHttpActionResult> LoginExternal(string signin, string provider) { Logger.InfoFormat("External login requested for provider: {0}", provider); if (provider.IsMissing()) { Logger.Error("No provider passed"); return RenderErrorPage(); } if (signin.IsMissing()) { Logger.Error("No signin id passed"); return RenderErrorPage(); } var cookie = new MessageCookie<SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signin); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return RenderErrorPage(); } var providerFilter = await GetProviderFilterForClientAsync(signInMessage); if (providerFilter != null && providerFilter.Any() && !providerFilter.Contains(provider)) { Logger.ErrorFormat("Provider {0} not allowed for client: {1}", provider, signInMessage.ClientId); return RenderErrorPage(); } var authProp = new Microsoft.Owin.Security.AuthenticationProperties { RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null) }; // add the id to the dictionary so we can recall the cookie id on the callback authProp.Dictionary.Add(Constants.Authentication.SigninId, signin); authProp.Dictionary.Add(Constants.Authentication.KatanaAuthenticationType, provider); Request.GetOwinContext().Authentication.Challenge(authProp, provider); return Unauthorized(); }
/// <summary> /// Gets the sign in message. /// </summary> /// <param name="env">The OWIN environment.</param> /// <param name="id">The signin identifier.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// env /// or /// id /// </exception> public static SignInMessage GetSignInMessage(this IDictionary<string, object> env, string id) { if (env == null) throw new ArgumentNullException("env"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); var options = env.ResolveDependency<IdentityServerOptions>(); var cookie = new MessageCookie<SignInMessage>(env, options); return cookie.Read(id); }
public static void ProcessRemovalOfSignOutMessageCookie(this IOwinContext context, MessageCookie <SignOutMessage> signOutMessageCookie) { if (context == null) { throw new ArgumentNullException("context"); } if (signOutMessageCookie == null) { throw new ArgumentNullException("signOutMessageCookie"); } if (context.Response.StatusCode == 200 && context.Environment.ContainsKey(SignOutMessageCookieIdtoRemove)) { signOutMessageCookie.Clear((string)context.Environment[SignOutMessageCookieIdtoRemove]); } }
public async Task <IHttpActionResult> ResumeLoginFromRedirect(string resume) { Logger.Info("Callback requested to resume login from partial login"); if (resume.IsMissing()) { Logger.Error("no resumeId passed"); return(RenderErrorPage()); } var user = await GetIdentityFromPartialSignIn(); if (user == null) { Logger.Error("no identity from partial login"); return(RenderErrorPage()); } var type = GetClaimTypeForResumeId(resume); var resumeClaim = user.FindFirst(type); if (resumeClaim == null) { Logger.Error("no claim matching resumeId"); return(RenderErrorPage()); } var signInId = resumeClaim.Value; if (signInId.IsMissing()) { Logger.Error("No signin id found in resume claim"); return(RenderErrorPage()); } var cookie = new MessageCookie <SignInMessage>(Request.GetOwinContext(), this._options); var signInMessage = cookie.Read(signInId); if (signInMessage == null) { Logger.Error("No cookie matching signin id found"); return(RenderErrorPage()); } AuthenticateResult result = null; var externalProviderClaim = user.FindFirst(Constants.ClaimTypes.ExternalProviderUserId); if (externalProviderClaim == null) { // the user/subject was known, so pass thru (without the redirect claims) user.RemoveClaim(user.FindFirst(Constants.ClaimTypes.PartialLoginReturnUrl)); user.RemoveClaim(user.FindFirst(GetClaimTypeForResumeId(resume))); result = new AuthenticateResult(new ClaimsPrincipal(user)); } else { // the user was not known, we need to re-execute AuthenticateExternalAsync // to obtain a subject to proceed var provider = externalProviderClaim.Issuer; var providerId = externalProviderClaim.Value; var externalId = new ExternalIdentity { Provider = provider, ProviderId = providerId, Claims = user.Claims }; result = await _userService.AuthenticateExternalAsync(externalId); if (result == null) { Logger.Warn("user service failed to authenticate external identity"); return(await RenderLoginPage(signInMessage, signInId, Messages.NoMatchingExternalAccount)); } if (result.IsError) { Logger.WarnFormat("user service returned error message: {0}", result.ErrorMessage); return(await RenderLoginPage(signInMessage, signInId, result.ErrorMessage)); } } return(SignInAndRedirect(signInMessage, signInId, result)); }
private void ClearSignInCookie(string signin) { var cookie = new MessageCookie <SignInMessage>(Request.GetOwinContext(), this._options); cookie.Clear(signin); }
/// <summary> /// Creates the sign out request. /// </summary> /// <param name="env">The env.</param> /// <param name="message">The message.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">message</exception> public static string CreateSignOutRequest(this IDictionary<string, object> env, SignOutMessage message) { if (message == null) throw new ArgumentNullException("message"); // if there's no return url, then use current request's URL if (message.ReturnUrl.IsMissing()) { var ctx = new OwinContext(env); message.ReturnUrl = ctx.Request.Uri.AbsoluteUri; } if (message.ReturnUrl.StartsWith("~/")) { message.ReturnUrl = message.ReturnUrl.Substring(1); } if (message.ReturnUrl.StartsWith("/")) { message.ReturnUrl = env.GetIdentityServerBaseUrl().RemoveTrailingSlash() + message.ReturnUrl; } var options = env.ResolveDependency<IdentityServerOptions>(); var cookie = new MessageCookie<SignOutMessage>(env, options); var id = cookie.Write(message); var url = env.GetIdentityServerBaseUrl() + Constants.RoutePaths.Logout; var uri = new Uri(url.AddQueryString("id=" + id)); return uri.AbsoluteUri; }
private void ClearSignInCookies() { var cookie = new MessageCookie <SignInMessage>(Request.GetOwinContext(), this._options); cookie.ClearAll(); }
public ConsentMessageStore(MessageCookie <ConsentResponse> cookie) { Cookie = cookie; }