public void LogIn(IUserAuthData user, bool isPersistent, params Claim[] extraClaims)
        {
            ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie
                                                         , ClaimsIdentity.DefaultNameClaimType
                                                         , ClaimsIdentity.DefaultRoleClaimType);

            identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider"
                                        , _title
                                        , ClaimValueTypes.String));

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.String));
            identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, user.FirstName, ClaimValueTypes.String));



            if (user.Roles != null && user.Roles.Any())
            {
                foreach (string singleRole in user.Roles)
                {
                    identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, singleRole, ClaimValueTypes.String));
                }
            }

            identity.AddClaims(extraClaims);

            Microsoft.Owin.Security.AuthenticationProperties props = new Microsoft.Owin.Security.AuthenticationProperties
            {
                IsPersistent = isPersistent,
                IssuedUtc    = DateTime.UtcNow,
                ExpiresUtc   = DateTime.UtcNow.AddDays(60),
                AllowRefresh = true
            };

            HttpContext.Current.GetOwinContext().Authentication.SignIn(props, identity);
        }
Example #2
0
        private void IssueAuthenticationCookie(string signInMessageId, AuthenticateResult authResult, bool?rememberMe = null)
        {
            if (authResult == null)
            {
                throw new ArgumentNullException("authResult");
            }

            if (authResult.IsPartialSignIn)
            {
                Logger.Info("issuing partial signin cookie");
            }
            else
            {
                Logger.Info("issuing primary signin cookie");
            }

            var props = new Microsoft.Owin.Security.AuthenticationProperties();

            var id = authResult.User.Identities.First();

            if (authResult.IsPartialSignIn)
            {
                // add claim so partial redirect can return here to continue login
                // we need a random ID to resume, and this will be the query string
                // to match a claim added. the claim added will be the original
                // signIn ID.
                var resumeId = CryptoRandom.CreateUniqueId();

                var resumeLoginUrl   = context.GetPartialLoginResumeUrl(resumeId);
                var resumeLoginClaim = new Claim(Constants.ClaimTypes.PartialLoginReturnUrl, resumeLoginUrl);
                id.AddClaim(resumeLoginClaim);
                id.AddClaim(new Claim(GetClaimTypeForResumeId(resumeId), signInMessageId));
            }
            else
            {
                signInMessageCookie.Clear(signInMessageId);
                sessionCookie.IssueSessionId(rememberMe);
            }

            if (!authResult.IsPartialSignIn)
            {
                // don't issue persistnt cookie if it's a partial signin
                if (rememberMe == true ||
                    (rememberMe != false && this.options.AuthenticationOptions.CookieOptions.IsPersistent))
                {
                    // only issue persistent cookie if user consents (rememberMe == true) or
                    // if server is configured to issue persistent cookies and user has not explicitly
                    // denied the rememberMe (false)
                    // if rememberMe is null, then user was not prompted for rememberMe
                    props.IsPersistent = true;
                    if (rememberMe == true)
                    {
                        var expires = DateTimeHelper.UtcNow.Add(options.AuthenticationOptions.CookieOptions.RememberMeDuration);
                        props.ExpiresUtc = new DateTimeOffset(expires);
                    }
                }
            }

            context.Authentication.SignIn(props, id);
        }
Example #3
0
        private void IssueAuthenticationCookie(SignInMessage signInMessage, string signInMessageId, AuthenticateResult authResult, bool?rememberMe = null)
        {
            if (signInMessage == null)
            {
                throw new ArgumentNullException("signInId");
            }
            if (authResult == null)
            {
                throw new ArgumentNullException("authResult");
            }

            Logger.InfoFormat("issuing cookie{0}", authResult.IsPartialSignIn ? " (partial login)" : "");

            var props = new Microsoft.Owin.Security.AuthenticationProperties();

            var id = authResult.User.Identities.First();

            if (authResult.IsPartialSignIn)
            {
                // add claim so partial redirect can return here to continue login
                // we need a random ID to resume, and this will be the query string
                // to match a claim added. the claim added will be the original
                // signIn ID.
                var resumeId = Guid.NewGuid().ToString("N");

                var resumeLoginUrl   = Url.Link(Constants.RouteNames.ResumeLoginFromRedirect, new { resume = resumeId });
                var resumeLoginClaim = new Claim(Constants.ClaimTypes.PartialLoginReturnUrl, resumeLoginUrl);
                id.AddClaim(resumeLoginClaim);
                id.AddClaim(new Claim(GetClaimTypeForResumeId(resumeId), signInMessageId));
            }
            else
            {
                ClearSignInCookie(signInMessageId);
            }

            if (!authResult.IsPartialSignIn)
            {
                // don't issue persistnt cookie if it's a partial signin
                if (rememberMe == true ||
                    (rememberMe != false && this._options.AuthenticationOptions.CookieOptions.IsPersistent))
                {
                    // only issue persistent cookie if user consents (rememberMe == true) or
                    // if server is configured to issue persistent cookies and user has not explicitly
                    // denied the rememberMe (false)
                    // if rememberMe is null, then user was not prompted for rememberMe
                    props.IsPersistent = true;
                    if (rememberMe == true)
                    {
                        var expires = DateTime.UtcNow.Add(_options.AuthenticationOptions.CookieOptions.RememberMeDuration);
                        props.ExpiresUtc = new DateTimeOffset(expires);
                    }
                }
            }

            ClearAuthenticationCookies();

            var ctx = Request.GetOwinContext();

            ctx.Authentication.SignIn(props, id);
        }
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
     IdentityUser user;
     using (AuthRepository _repo = new AuthRepository())
     {
          user = await _repo.FindUser(context.UserName, context.Password);
         if (user == null)
         {
             context.SetError("invalid_grant", "The user name or password is incorrect.");
             return;
         }
     }
     var identity = new ClaimsIdentity(context.Options.AuthenticationType);
     identity.AddClaim(new Claim("sub", context.UserName));
     identity.AddClaim(new Claim("role", "user"));
     Microsoft.Owin.Security.AuthenticationProperties properties = new Microsoft.Owin.Security.AuthenticationProperties(new Dictionary<string, string>
             {
                 { "userId", user.Id }
     
             });
     Microsoft.Owin.Security.AuthenticationTicket ticket = new Microsoft.Owin.Security.AuthenticationTicket(identity, properties);
     // the above didn't worked so working around for the same
     context.Validated(ticket);
    // context.Validated(identity);
 }
Example #5
0
 private async Task<string> GenerateUserToken(ApplicationUser validatedUser)
 {
     CustomJwtFormat jwt = new CustomJwtFormat("http://jv.com");
     var identity = await validatedUser.GenerateUserIdentityAsync(AppUserManager, "password");
     Microsoft.Owin.Security.AuthenticationProperties properties = new Microsoft.Owin.Security.AuthenticationProperties();
     properties.IssuedUtc = DateTime.Now.ToUniversalTime();
     properties.ExpiresUtc = DateTime.Now.AddMinutes(5).ToUniversalTime();
     return jwt.Protect(new Microsoft.Owin.Security.AuthenticationTicket(identity, properties));
 }
 protected override void Postprocess(Microsoft.Owin.IOwinContext ctx)
 {
     if (SignInIdentity != null)
     {
         var props = new Microsoft.Owin.Security.AuthenticationProperties();
         props.Dictionary.Add("signin", SignInId);
         ctx.Authentication.SignIn(props, SignInIdentity);
         SignInIdentity = null;
     }
 }
Example #7
0
        private async Task <string> GenerateUserToken(ApplicationUser validatedUser)
        {
            CustomJwtFormat jwt      = new CustomJwtFormat("http://jv.com");
            var             identity = await validatedUser.GenerateUserIdentityAsync(AppUserManager, "password");

            Microsoft.Owin.Security.AuthenticationProperties properties = new Microsoft.Owin.Security.AuthenticationProperties();
            properties.IssuedUtc  = DateTime.Now.ToUniversalTime();
            properties.ExpiresUtc = DateTime.Now.AddMinutes(5).ToUniversalTime();
            return(jwt.Protect(new Microsoft.Owin.Security.AuthenticationTicket(identity, properties)));
        }
Example #8
0
        public override void ExecuteResult(ControllerContext Context)
        {
            var Properties = new Microsoft.Owin.Security.AuthenticationProperties() { RedirectUri = RedirectUri };

            if (UserId != null)
            {
                Properties.Dictionary[XsrfKey] = UserId;
            }

            Context.HttpContext.GetOwinContext().Authentication.Challenge(Properties, Provider);
        }
            public override void ExecuteResult(ControllerContext context)
            {
                var properties = new Microsoft.Owin.Security.AuthenticationProperties {
                    RedirectUri = RedirectUri
                };

                if (UserId != null)
                {
                    properties.Dictionary[XsrfKey] = UserId;
                }
                context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
            }
Example #10
0
        /// <summary>
        /// 发放。授权资源访问凭证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async System.Threading.Tasks.Task GrantResourceOwnerCredentials(Microsoft.Owin.Security.OAuth.OAuthGrantResourceOwnerCredentialsContext context)
        {
            //return base.GrantResourceOwnerCredentials(context);
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            //鉴定ClientID之后。授权来源
            if (allowedOrigin == null)
            {
                allowedOrigin = this.userClientAuth? "*" : this.AnoymouseAllowedOrigins;
            }
            /////ngauthenticationweb Access-Control-Allow-Origin //来源鉴定
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", allowedOrigin.Split(','));
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET", "POST", "PUT", "DELETE" });


            Microsoft.AspNet.Identity.EntityFramework.IdentityUser user =
                await authRepository.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "用户名,密码不正确");
                return;
            }
            //claim based 认证
            var identity = new System.Security.Claims.ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, context.UserName));
            identity.AddClaim(new System.Security.Claims.Claim("sub", context.UserName));
            identity.AddClaim(new System.Security.Claims.Claim("role", "user"));
            //identity.AddClaim(new System.Security.Claims.Claim("test", "test"));
            var claims = MallAuth.ServerCache.GlobalCache.getInstance().getUserClaims(context.UserName);

            foreach (var item in claims)
            {
                identity.AddClaim(new System.Security.Claims.Claim(item.Type, item.Value));
            }
            ///额外的响应参数.注意这个和Claim不同
            var props = new Microsoft.Owin.Security.AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new Microsoft.Owin.Security.AuthenticationTicket(identity, props);

            context.Validated(ticket);

            //context.Validated(identity);
        }
 protected override void Postprocess(Microsoft.Owin.IOwinContext ctx)
 {
     if (SignInIdentity != null)
     {
         var props = new Microsoft.Owin.Security.AuthenticationProperties();
         props.Dictionary.Add("signin", SignInId);
         if (SignInIdentity.AuthenticationType == Constants.ExternalAuthenticationType)
         {
             props.Dictionary.Add("katanaAuthenticationType", "Google");
         }
         ctx.Authentication.SignIn(props, SignInIdentity);
         SignInIdentity = null;
     }
 }
Example #12
0
        /// <summary>
        /// This does the mechanics of getting IdSrv to log you in and set an auth cookie
        /// Basically copy & paste from the auth controller
        /// Suggest this is refactored in IdSrv to call it easily
        /// </summary>
        private void SetTheIdSrvAuthCookie(AuthenticateResult p)
        {
            var user = CreateFromPrincipal(p.User, Constants.PrimaryAuthenticationType);

            this.owinContext.Authentication.SignOut(
                Constants.PrimaryAuthenticationType,
                Constants.ExternalAuthenticationType,
                Constants.PartialSignInAuthenticationType);

            var props = new Microsoft.Owin.Security.AuthenticationProperties();
            var id    = user.Identities.First();

            this.owinContext.Authentication.SignIn(props, id);
        }
        public IHttpActionResult LoginExternal(string provider)
        {
            logger.Start("[AuthenticationController.LoginExternal] called");

            VerifyLoginRequestMessage();

            var ctx      = Request.GetOwinContext();
            var authProp = new Microsoft.Owin.Security.AuthenticationProperties
            {
                RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null)
            };

            Request.GetOwinContext().Authentication.Challenge(authProp, provider);
            return(Unauthorized());
        }
Example #14
0
        public IHttpActionResult LoginExternal(string provider)
        {
            Logger.InfoFormat("External login requested for provider: {0}", provider);

            VerifySignInMessage();

            var ctx      = Request.GetOwinContext();
            var authProp = new Microsoft.Owin.Security.AuthenticationProperties
            {
                RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null)
            };

            Request.GetOwinContext().Authentication.Challenge(authProp, provider);
            return(Unauthorized());
        }
Example #15
0
        public ActionResult Login(LoginModel model)
        {
            if (model.Password == null || model.EmailAddress == null)
            {
                return(View());
            }
            //var getTokenUrl = string.Format(ApiEndPoints.AuthorisationTokenEndpoint.Post.Token, ConfigurationManager.AppSettings["ApiBaseUri"]);
            var getTokenUrl = "http://localhost:57359/token";

            using (HttpClient httpClient = new HttpClient())
            {
                HttpContent content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", model.EmailAddress),
                    //new KeyValuePair<string, string>("username", "ElenaElena2"),
                    new KeyValuePair <string, string>("password", model.Password)
                    //new KeyValuePair<string, string>("password", "SuperPass")
                });

                HttpResponseMessage result = httpClient.PostAsync(getTokenUrl, content).Result;

                string resultContent = result.Content.ReadAsStringAsync().Result;

                var token = JsonConvert.DeserializeObject <Token>(resultContent);

                Microsoft.Owin.Security.AuthenticationProperties options = new Microsoft.Owin.Security.AuthenticationProperties();

                options.AllowRefresh = true;
                options.IsPersistent = true;
                options.ExpiresUtc   = DateTime.UtcNow.AddSeconds(int.Parse(token.expires_in));

                var claims = new[]
                {
                    //new Claim(ClaimTypes.Name, model.EmailAddress),
                    new Claim(ClaimTypes.Name, "ElenaElena2"),
                    new Claim("AcessToken", string.Format("Bearer {0}", token.access_token)),
                };

                var identity = new ClaimsIdentity(claims, "ApplicationCookie");

                Request.GetOwinContext().Authentication.SignIn(options, identity);
            }

            return(RedirectToAction("Index", "OrderList"));
        }
Example #16
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());
        }
        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(localizationService.GetMessage(MessageIds.NoExternalProvider)));
            }

            if (signin.IsMissing())
            {
                Logger.Error("No signin id passed");
                return(RenderErrorPage(localizationService.GetMessage(MessageIds.NoSignInCookie)));
            }

            var signInMessage = signInMessageCookie.Read(signin);

            if (signInMessage == null)
            {
                Logger.Error("No cookie matching signin id found");
                return(RenderErrorPage(localizationService.GetMessage(MessageIds.NoSignInCookie)));
            }

            if (!(await clientStore.IsValidIdentityProviderAsync(signInMessage.ClientId, 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);
            context.Authentication.Challenge(authProp, provider);

            return(Unauthorized());
        }
Example #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                List <string> providerNames =
                    HttpContext.Current.GetOwinContext().Authentication
                    .GetAuthenticationTypes((d) => d.Properties != null && d.Properties.ContainsKey("Caption"))
                    .Select(t => t.AuthenticationType).ToList();

                ListView1.DataSource = providerNames;
                ListView1.DataBind();
            }
            else
            {
                var provider = Request.Form["provider"];
                if (provider == null)
                {
                    return;
                }
                else
                {
                    string returnUrl = Request["ReturnUrl"];

                    if (String.IsNullOrEmpty(returnUrl))
                    {
                        returnUrl = "/";
                    }

                    var properties = new Microsoft.Owin.Security.AuthenticationProperties
                    {
                        RedirectUri = returnUrl
                    };

                    HttpContext.Current.GetOwinContext().Authentication.Challenge(properties, provider);
                }
            }
        }
        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 SignInMessageCookie(Request.GetOwinContext(), this._options);
            var signInMessage = cookie.Read(signin);

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

            var ctx      = Request.GetOwinContext();
            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);
            Request.GetOwinContext().Authentication.Challenge(authProp, provider);
            return(Unauthorized());
        }
Example #20
0
        private void IssueAuthenticationCookie(
            AuthenticateResult authResult,
            string authenticationMethod,
            string identityProvider,
            long authTime)
        {
            if (authResult == null)
            {
                throw new ArgumentNullException("authResult");
            }
            if (String.IsNullOrWhiteSpace(authenticationMethod))
            {
                throw new ArgumentNullException("authenticationMethod");
            }
            if (String.IsNullOrWhiteSpace(identityProvider))
            {
                throw new ArgumentNullException("identityProvider");
            }

            Logger.InfoFormat("logging user in as subject: {0}, name: {1}{2}", authResult.Subject, authResult.Name, authResult.IsPartialSignIn ? " (partial login)" : "");

            var issuer = authResult.IsPartialSignIn ?
                         Constants.PartialSignInAuthenticationType :
                         Constants.PrimaryAuthenticationType;

            var principal = IdentityServerPrincipal.Create(
                authResult.Subject,
                authResult.Name,
                authenticationMethod,
                identityProvider,
                issuer,
                authTime);

            var props = new Microsoft.Owin.Security.AuthenticationProperties();

            var id = principal.Identities.First();

            if (authResult.IsPartialSignIn)
            {
                // add claim so partial redirect can return here to continue login
                var resumeLoginUrl   = Url.Link(Constants.RouteNames.ResumeLoginFromRedirect, null);
                var resumeLoginClaim = new Claim(Constants.ClaimTypes.PartialLoginReturnUrl, resumeLoginUrl);
                id.AddClaim(resumeLoginClaim);

                // store original authorization url as claim
                // so once we result we can return to authorization page
                var signInMessage         = LoadSignInMessage();
                var authorizationUrl      = signInMessage.ReturnUrl;
                var authorizationUrlClaim = new Claim(Constants.ClaimTypes.AuthorizationReturnUrl, authorizationUrl);
                id.AddClaim(authorizationUrlClaim);

                // allow redircting code to add claims for target page
                id.AddClaims(authResult.RedirectClaims);
            }
            else if (this._options.CookieOptions.IsPersistent)
            {
                props.IsPersistent = true;
            }

            ClearAuthenticationCookies();

            var ctx = Request.GetOwinContext();

            ctx.Authentication.SignIn(props, id);
        }
        public override async Task GrantResourceOwnerCredentials(Microsoft.Owin.Security.OAuth.OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
            if (allowedOrigin == null)
            {
                allowedOrigin = "*";
            }
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            using (AuthRepository repo = new AuthRepository())
            {
                Microsoft.AspNet.Identity.EntityFramework.IdentityUser user = await repo.FindUser(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name and password doesnt match the records");
                    return;
                }
            }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            var props = new Microsoft.Owin.Security.AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new Microsoft.Owin.Security.AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
        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();
        }
Example #23
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(localizationService.GetMessage(MessageIds.NoExternalProvider)));
            }

            if (provider.Length > options.InputLengthRestrictions.IdentityProvider)
            {
                Logger.Error("Provider parameter passed was larger than max length");
                return(RenderErrorPage());
            }

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

            if (!(await clientStore.IsValidIdentityProviderAsync(signInMessage.ClientId, provider)))
            {
                var msg = String.Format("External login error: provider {0} not allowed for client: {1}", provider, signInMessage.ClientId);
                Logger.ErrorFormat(msg);
                await eventService.RaiseFailureEndpointEventAsync(EventConstants.EndpointNames.Authenticate, msg);

                return(RenderErrorPage());
            }

            if (context.IsValidExternalAuthenticationProvider(provider) == false)
            {
                var msg = String.Format("External login error: provider requested {0} is not a configured external provider", provider);
                Logger.ErrorFormat(msg);
                await eventService.RaiseFailureEndpointEventAsync(EventConstants.EndpointNames.Authenticate, msg);

                return(RenderErrorPage());
            }

            var authProp = new Microsoft.Owin.Security.AuthenticationProperties
            {
                RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null)
            };

            Logger.Info("Triggering challenge for external identity provider");

            // 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);
            context.Authentication.Challenge(authProp, provider);

            return(Unauthorized());
        }
        public IHttpActionResult LoginExternal(string provider)
        {
            Logger.InfoFormat("External login requested for provider: {0}", provider);

            VerifySignInMessage();

            var ctx = Request.GetOwinContext();
            var authProp = new Microsoft.Owin.Security.AuthenticationProperties
            {
                RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null)
            };
            Request.GetOwinContext().Authentication.Challenge(authProp, provider);
            return Unauthorized();
        }
Example #25
0
        private void IssueAuthenticationCookie(IOwinContext context, string signInMessageId, AuthenticateResult authResult, bool rememberMe)
        {
            if (authResult == null)
            {
                throw new ArgumentNullException("authResult");
            }

            var props = new Microsoft.Owin.Security.AuthenticationProperties();

            var id = authResult.User.Identities.First();

            if (authResult.IsPartialSignIn)
            {
                // add claim so partial redirect can return here to continue login
                // we need a random ID to resume, and this will be the query string
                // to match a claim added. the claim added will be the original
                // signIn ID.
                var resumeId         = Guid.NewGuid().ToString();
                var resumeLoginUrl   = context.Environment.GetIdentityServerBaseUrl() + Constants.RoutePaths.ResumeLoginFromRedirect + "?resume=" + resumeId;
                var resumeLoginClaim = new Claim(Constants.ClaimTypes.PartialLoginReturnUrl, resumeLoginUrl);
                id.AddClaim(resumeLoginClaim);
                id.AddClaim(new Claim(String.Format(Constants.ClaimTypes.PartialLoginResumeId, resumeId), signInMessageId));

                // add url to start login process over again (which re-triggers preauthenticate)
                var restartUrl = context.Environment.GetIdentityServerBaseUrl() + "custom/login?signin=" + signInMessageId;

                id.AddClaim(new Claim(Constants.ClaimTypes.PartialLoginRestartUrl, restartUrl));
            }
            else
            {
                context.Environment.IssueLoginCookie(new IdentityServer3.Core.Models.AuthenticatedLogin
                {
                    Subject         = authResult.User.Identity.GetSubjectId(),
                    Name            = authResult.User.Identity.Name,
                    PersistentLogin = rememberMe,
                    Claims          = id.Claims,
                });
            }

            if (!authResult.IsPartialSignIn)
            {
                // don't issue persistnt cookie if it's a partial signin
                if (rememberMe == true ||
                    (rememberMe != false && options.AuthenticationOptions.CookieOptions.IsPersistent))
                {
                    // only issue persistent cookie if user consents (rememberMe == true) or
                    // if server is configured to issue persistent cookies and user has not explicitly
                    // denied the rememberMe (false)
                    // if rememberMe is null, then user was not prompted for rememberMe
                    props.IsPersistent = true;
                    if (rememberMe == true)
                    {
                        var expires = DateTime.SpecifyKind(DateTimeOffset.UtcNow.DateTime, DateTimeKind.Utc).Add(options.AuthenticationOptions.CookieOptions.RememberMeDuration);
                        props.ExpiresUtc = new DateTimeOffset(expires);
                    }
                }
            }
            else
            {
                // if rememberme set, then store for later use once we need to issue login cookie
                props.Dictionary.Add(Constants.Authentication.PartialLoginRememberMe, rememberMe ? "true" : "false");
            }

            context.Authentication.SignIn(props, 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(localizationService.GetMessage(MessageIds.NoExternalProvider));
            }

            if (signin.IsMissing())
            {
                Logger.Error("No signin id passed");
                return RenderErrorPage(localizationService.GetMessage(MessageIds.NoSignInCookie));
            }

            var signInMessage = signInMessageCookie.Read(signin);
            if (signInMessage == null)
            {
                Logger.Error("No cookie matching signin id found");
                return RenderErrorPage(localizationService.GetMessage(MessageIds.NoSignInCookie));
            }

            if (!(await clientStore.IsValidIdentityProviderAsync(signInMessage.ClientId, 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);
            context.Authentication.Challenge(authProp, provider);
            
            return Unauthorized();
        }
        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(localizationService.GetMessage(MessageIds.NoExternalProvider));
            }

            if (provider.Length > options.InputLengthRestrictions.IdentityProvider)
            {
                Logger.Error("Provider parameter passed was larger than max length");
                return RenderErrorPage();
            }

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

            if (!(await clientStore.IsValidIdentityProviderAsync(signInMessage.ClientId, provider)))
            {
                var msg = String.Format("External login error: provider {0} not allowed for client: {1}", provider, signInMessage.ClientId);
                Logger.ErrorFormat(msg);
                await eventService.RaiseFailureEndpointEventAsync(EventConstants.EndpointNames.Authenticate, msg);
                return RenderErrorPage();
            }
            
            if (context.IsValidExternalAuthenticationProvider(provider) == false)
            {
                var msg = String.Format("External login error: provider requested {0} is not a configured external provider", provider);
                Logger.ErrorFormat(msg);
                await eventService.RaiseFailureEndpointEventAsync(EventConstants.EndpointNames.Authenticate, msg);
                return RenderErrorPage();
            }

            var authProp = new Microsoft.Owin.Security.AuthenticationProperties
            {
                RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null)
            };

            Logger.Info("Triggering challenge for external identity provider");

            // 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);
            context.Authentication.Challenge(authProp, provider);
            
            return Unauthorized();
        }
        private void IssueAuthenticationCookie(
            AuthenticateResult authResult, 
            string authenticationMethod, 
            string identityProvider, 
            long authTime)
        {
            if (authResult == null) throw new ArgumentNullException("authResult");
            if (String.IsNullOrWhiteSpace(authenticationMethod)) throw new ArgumentNullException("authenticationMethod");
            if (String.IsNullOrWhiteSpace(identityProvider)) throw new ArgumentNullException("identityProvider");
            
            Logger.InfoFormat("logging user in as subject: {0}, name: {1}{2}", authResult.Subject, authResult.Name, authResult.IsPartialSignIn ? " (partial login)" : "");
            
            var issuer = authResult.IsPartialSignIn ?
                Constants.PartialSignInAuthenticationType :
                Constants.PrimaryAuthenticationType;

            var principal = IdentityServerPrincipal.Create(
                authResult.Subject,
                authResult.Name,
                authenticationMethod,
                identityProvider,
                issuer,
                authTime);

            var props = new Microsoft.Owin.Security.AuthenticationProperties();

            var id = principal.Identities.First();
            if (authResult.IsPartialSignIn)
            {
                // add claim so partial redirect can return here to continue login
                var resumeLoginUrl = Url.Link(Constants.RouteNames.ResumeLoginFromRedirect, null);
                var resumeLoginClaim = new Claim(Constants.ClaimTypes.PartialLoginReturnUrl, resumeLoginUrl);
                id.AddClaim(resumeLoginClaim);

                // store original authorization url as claim
                // so once we result we can return to authorization page
                var signInMessage = LoadSignInMessage();
                var authorizationUrl = signInMessage.ReturnUrl;
                var authorizationUrlClaim = new Claim(Constants.ClaimTypes.AuthorizationReturnUrl, authorizationUrl);
                id.AddClaim(authorizationUrlClaim);

                // allow redircting code to add claims for target page
                id.AddClaims(authResult.RedirectClaims);
            }
            else if (this._options.CookieOptions.IsPersistent)
            {
                props.IsPersistent = true;
            }

            ClearAuthenticationCookies();

            var ctx = Request.GetOwinContext();
            ctx.Authentication.SignIn(props, id);
        }
        private void IssueAuthenticationCookie(string signInMessageId, AuthenticateResult authResult, bool? rememberMe = null)
        {
            if (authResult == null) throw new ArgumentNullException("authResult");

            Logger.InfoFormat("issuing cookie{0}", authResult.IsPartialSignIn ? " (partial login)" : "");

            var props = new Microsoft.Owin.Security.AuthenticationProperties();

            var id = authResult.User.Identities.First();
            if (authResult.IsPartialSignIn)
            {
                // add claim so partial redirect can return here to continue login
                // we need a random ID to resume, and this will be the query string
                // to match a claim added. the claim added will be the original 
                // signIn ID. 
                var resumeId = CryptoRandom.CreateUniqueId();

                var resumeLoginUrl = context.GetPartialLoginResumeUrl(resumeId);
                var resumeLoginClaim = new Claim(Constants.ClaimTypes.PartialLoginReturnUrl, resumeLoginUrl);
                id.AddClaim(resumeLoginClaim);
                id.AddClaim(new Claim(GetClaimTypeForResumeId(resumeId), signInMessageId));
            }
            else
            {
                signInMessageCookie.Clear(signInMessageId);
            }

            if (!authResult.IsPartialSignIn)
            {
                // don't issue persistnt cookie if it's a partial signin
                if (rememberMe == true ||
                    (rememberMe != false && this.options.AuthenticationOptions.CookieOptions.IsPersistent))
                {
                    // only issue persistent cookie if user consents (rememberMe == true) or
                    // if server is configured to issue persistent cookies and user has not explicitly
                    // denied the rememberMe (false)
                    // if rememberMe is null, then user was not prompted for rememberMe
                    props.IsPersistent = true;
                    if (rememberMe == true)
                    {
                        var expires = DateTimeHelper.UtcNow.Add(options.AuthenticationOptions.CookieOptions.RememberMeDuration);
                        props.ExpiresUtc = new DateTimeOffset(expires);
                    }
                }
            }

            ClearAuthenticationCookies();
            
            context.Authentication.SignIn(props, id);
        }
        public IHttpActionResult LoginExternal(string provider)
        {
            logger.Start("[AuthenticationController.LoginExternal] called");

            VerifyLoginRequestMessage();

            var ctx = Request.GetOwinContext();
            var authProp = new Microsoft.Owin.Security.AuthenticationProperties
            {
                RedirectUri = Url.Route(Constants.RouteNames.LoginExternalCallback, null)
            };
            Request.GetOwinContext().Authentication.Challenge(authProp, provider);
            return Unauthorized();
        }