/// <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));
        }
示例#2
0
        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());
        }
示例#3
0
        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));
        }
        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> 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();
        }
        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);
        }
示例#10
0
        public async Task <IHttpActionResult> Login(string signin = null)
        {
            Logger.Info("Login page requested");

            if (signin.IsMissing())
            {
                Logger.Info("No signin id passed");
                return(HandleNoSignin());
            }

            if (signin.Length > MaxSignInMessageLength)
            {
                Logger.Error("Signin parameter passed was larger than max length");
                return(RenderErrorPage());
            }

            var signInMessage = signInMessageCookie.Read(signin);

            if (signInMessage == null)
            {
                Logger.Info("No cookie matching signin id found");
                return(HandleNoSignin());
            }

            Logger.DebugFormat("signin message passed to login: {0}", JsonConvert.SerializeObject(signInMessage, Formatting.Indented));

            var preAuthContext = new PreAuthenticationContext {
                SignInMessage = signInMessage
            };
            await userService.PreAuthenticateAsync(preAuthContext);

            var authResult = preAuthContext.AuthenticateResult;

            if (authResult != null)
            {
                if (authResult.IsError)
                {
                    Logger.WarnFormat("user service returned an error message: {0}", authResult.ErrorMessage);

                    await eventService.RaisePreLoginFailureEventAsync(signin, signInMessage, authResult.ErrorMessage);

                    if (preAuthContext.ShowLoginPageOnErrorResult)
                    {
                        Logger.Debug("ShowLoginPageOnErrorResult set to true, showing login page with error");
                        return(await RenderLoginPage(signInMessage, signin, authResult.ErrorMessage));
                    }
                    else
                    {
                        Logger.Debug("ShowLoginPageOnErrorResult set to false, showing error page with error");
                        return(RenderErrorPage(authResult.ErrorMessage));
                    }
                }

                Logger.Info("user service returned a login result");

                await eventService.RaisePreLoginSuccessEventAsync(signin, signInMessage, authResult);

                return(await SignInAndRedirectAsync(signInMessage, signin, authResult));
            }

            if (signInMessage.IdP.IsPresent())
            {
                Logger.InfoFormat("identity provider requested, redirecting to: {0}", signInMessage.IdP);
                return(await LoginExternal(signin, signInMessage.IdP));
            }

            return(await RenderLoginPage(signInMessage, signin));
        }
示例#11
0
        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));
        }
示例#12
0
 public virtual Task <Message <ConsentResponse> > ReadAsync(string id)
 {
     return(Task.FromResult(Cookie.Read(id)));
 }
        /// <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);
        }
示例#14
0
    public virtual Task <Message <ConsentResponse> > ReadAsync(string id)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("ConsentMessageStore.Read");

        return(Task.FromResult(Cookie.Read(id)));
    }
 public Task <Message <TModel> > ReadAsync(string id)
 {
     return(Task.FromResult(_cookie.Read(id)));
 }
 private SignOutMessage GetSignOutMessage(string id)
 {
     if (!String.IsNullOrWhiteSpace(id))
     {
         var cookie = new MessageCookie<SignOutMessage>(Request.GetOwinContext(), this._options);
         return cookie.Read(id);
     }
     return null;
 }
示例#17
0
        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));
        }