예제 #1
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationTicket      ticket = null;
            IReadableStringCollection query  = Request.Query;
            var redirectUrl = query.Get(Options.ReturnUrlParameter);
            var state       = query.Get("state");
            var grantType   = query.Get("");


            try
            {
                string cookie = Options.CookieManager.GetRequestCookie(Context, Options.CookieName);
                if (string.IsNullOrWhiteSpace(cookie))
                {
                    return(await GenerateEmptyTiket(redirectUrl));
                }

                ticket = Options.TicketDataFormat.Unprotect(cookie);
                if (ticket == null)
                {
                    _logger.WriteWarning(@"Unprotect ticket failed");
                    return(await GenerateEmptyTiket(redirectUrl));
                }
                if (Options.SessionStore != null)
                {
                    Claim claim = ticket.Identity.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim));
                    if (claim == null)
                    {
                        _logger.WriteWarning(@"SessoinId missing");
                        return(await GenerateEmptyTiket(redirectUrl));
                    }
                    _sessionKey = claim.Value;
                    ticket      = await Options.SessionStore.RetrieveAsync(_sessionKey);

                    if (ticket == null)
                    {
                        _logger.WriteWarning(@"Identity missing in session store");
                        return(await GenerateEmptyTiket(redirectUrl));
                    }
                }
                DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
                DateTimeOffset?issuedUtc  = ticket.Properties.IssuedUtc;
                DateTimeOffset?expiresUtc = ticket.Properties.ExpiresUtc;

                if (expiresUtc != null && expiresUtc.Value < currentUtc)
                {
                    return(await GenerateEmptyTiket(redirectUrl));
                }
                ticket.Properties.RedirectUri = redirectUrl;
                return(ticket);
            }
            catch (Exception exception)
            {
                _logger.WriteError("Authenticate error", exception);
                ticket = new AuthenticationTicket(null, new AuthenticationProperties());
                ticket.Properties.RedirectUri = redirectUrl;
                return(ticket);
            }
        }
예제 #2
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                IReadableStringCollection query = Request.Query;

                // TODO: Is this a standard error returned by servers?
                var value = query.Get("error");
                if (!string.IsNullOrEmpty(value))
                {
                    Logger.WriteVerbose("Remote server returned an error: " + Request.QueryString);
                    // TODO: Fail request rather than passing through?
                    return(null);
                }

                string code  = query.Get("code");
                string state = query.Get("state");

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, Logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                if (string.IsNullOrEmpty(code))
                {
                    // Null if the remote server returns an error.
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + RequestPathBase + Options.CallbackPath;

                var tokens = await ExchangeCodeAsync(code, redirectUri);

                if (string.IsNullOrWhiteSpace(tokens.AccessToken))
                {
                    Logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                return(await GetUserInformationAsync(properties, tokens));
            }
            catch (Exception ex)
            {
                Logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
        private static PageSizer ContainsResultLimit(IReadableStringCollection collection)
        {
            if (collection.Get("take") != null)
            {
                return(PageSizer.Take);
            }

            if (collection.Get("$top") != null)
            {
                return(PageSizer.Top);
            }

            return(PageSizer.None);
        }
예제 #4
0
        public void Get_Merged()
        {
            IReadableStringCollection query = CreateQuery(RawValues);
            string values = query.Get(QueryItemKey);

            Assert.Equal(JoinedValues, values);
        }
예제 #5
0
        public void ParseQuery()
        {
            IDictionary <string, object> environment = new Dictionary <string, object>();

            environment["owin.RequestQueryString"] = OriginalQueryString;
            IOwinRequest request = new OwinRequest(environment);

            Assert.Equal(OriginalQueryString, request.QueryString.Value);

            IReadableStringCollection query = request.Query;

            Assert.Equal("v1", query.Get("q1"));
            Assert.Equal("v2,b", query.Get("Q2"));
            Assert.Equal("v3,v4", query.Get("q3"));
            Assert.Null(query.Get("q4"));
            Assert.Equal("v5,v5", query.Get("Q5"));
        }
예제 #6
0
        public void GetMissing_null()
        {
            IReadableStringCollection query = CreateQuery(null);

            Assert.Null(query[QueryItemKey]);
            Assert.Null(query.Get(QueryItemKey));
            Assert.Null(query.GetValues(QueryItemKey));
        }
예제 #7
0
        public ValidateLocalTokenEndpointRequestContext(
            IOwinContext context, LocalTokenAuthenticationOptions options)
            : base(context, options)
        {
            IReadableStringCollection parameters = Request.Query;

            foreach (var parameter in parameters)
            {
                AddParameter(parameter.Key, parameters.Get(parameter.Key));
            }
        }
        private Dictionary <string, string> ToDictionary(IReadableStringCollection nameValueCollection)
        {
            var result = new Dictionary <string, string>();

            foreach (var kvp in nameValueCollection)
            {
                result[kvp.Key] = nameValueCollection.Get(kvp.Key);
            }

            return(result);
        }
        /// <summary>
        /// Creates a new instance populated with values from the query string parameters.
        /// </summary>
        /// <param name="parameters">Query string parameters from a request.</param>
        public AuthorizeEndpointRequest(IReadableStringCollection parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            Scope = new List<string>();

            foreach (var parameter in parameters)
            {
                AddParameter(parameter.Key, parameters.Get(parameter.Key));
            }
        }
예제 #10
0
        /// <summary>
        /// Creates a new instance populated with values from the query string parameters.
        /// </summary>
        /// <param name="parameters">Query string parameters from a request.</param>
        public AuthorizeEndpointRequest(IReadableStringCollection parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            Scope = new List <string>();

            foreach (var parameter in parameters)
            {
                AddParameter(parameter.Key, parameters.Get(parameter.Key));
            }
        }
예제 #11
0
        public string GetString(string name)
        {
            var urlValue  = urlData.Get(name);
            var formValue = formData.Get(name);

            if (string.IsNullOrWhiteSpace(urlValue))
            {
                return(formValue);
            }

            if (string.IsNullOrWhiteSpace(formValue))
            {
                return(urlValue);
            }

            return(string.Format("{0},{1}", urlValue, formValue));
        }
예제 #12
0
        public virtual async Task <ValueProviderResult> GetValueAsync([NotNull] string key)
        {
            var collection = await GetValueCollectionAsync();

            var values = collection.GetValues(key);

            ValueProviderResult result;

            if (values == null)
            {
                result = null;
            }
            else if (values.Count == 1)
            {
                var value = (string)values[0];
                result = new ValueProviderResult(value, value, _culture);
            }
            else
            {
                result = new ValueProviderResult(values, _values.Get(key), _culture);
            }

            return(result);
        }
예제 #13
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var campaignId = parameters.Get(MarketplaceClaimTypes.CampaignId);
            // context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var authorizationTrackId = GenerateAuthorizationTrackId();

            var usuario = new Usuario();

            if (usuario == null)
            {
                context.Rejected();
                context.SetError("participant not found!");
                return;
            }
            else
            {
                var identity = GetClaims(context, authorizationTrackId, usuario);
                var ticket   = new AuthenticationTicket(identity, GetAppProperties(authorizationTrackId, app, usuario));

                SetExpireTime(context.Options);

                context.Validated(ticket);
            }
        }
예제 #14
0
        /// <summary>
        ///  Returns true if the request was handled, false if the next middleware should be invoked.
        /// </summary>
        /// <returns></returns>
        private async Task <bool> InvokeReplyPathAsync()
        {
            //apply /login redirect to dongbo passport
            if (Request.Path == Options.LoginPath)
            {
                IReadableStringCollection query = Request.Query;
                string redirectUri = query.Get(Options.ReturnUrlParameter);

                if (String.IsNullOrWhiteSpace(redirectUri))
                {
                    redirectUri = Request.Scheme +
                                  Uri.SchemeDelimiter +
                                  Request.Host +
                                  Request.PathBase +
                                  "/";
                }
                else
                {
                    //var reg = new System.Text.RegularExpressions.Regex("http(s?)://.*");
                    //var abs=reg.IsMatch(redirectUri);
                    //var uri = new Uri(redirectUri);
                    if (IsHostRelative(redirectUri))
                    {
                        redirectUri = Request.Scheme +
                                      Uri.SchemeDelimiter +
                                      Request.Host + redirectUri;
                    }
                }
                string loginUri =
                    Options.AuthorizationEndpoint +
                    new QueryString(Options.ReturnUrlParameter, redirectUri);
                loginUri = WebUtilities.AddQueryString(loginUri, "appid", Options.AppId);
                Response.Redirect(loginUri);
                return(true);
            }
            if (Request.Path == Options.LogoutPath && Request.Method.ToLower() == "post")
            {
                var redirectUri = Request.Scheme +
                                  Uri.SchemeDelimiter +
                                  Request.Host +
                                  Request.PathBase +
                                  "/";
                string logoutUri =
                    Options.SignOutEndpoint +
                    new QueryString(Options.ReturnUrlParameter, redirectUri);
                Response.Redirect(logoutUri);
                return(true);
            }
            if (Request.Path == Options.SignupPath)
            {
                var redirectUri = Request.Scheme +
                                  Uri.SchemeDelimiter +
                                  Request.Host +
                                  Request.PathBase +
                                  "/";
                string signup =
                    Options.SignupEndpoint +
                    new QueryString(Options.ReturnUrlParameter, redirectUri);
                signup = WebUtilities.AddQueryString(signup, "appid", Options.AppId);
                Response.Redirect(signup);
                return(true);
            }
            return(false);
        }
예제 #15
0
 public string Get(string key)
 {
     return(_readableStringCollection.Get(key));
 }
예제 #16
0
        private Dictionary<string, string> ToDictionary(IReadableStringCollection nameValueCollection)
        {
            var result = new Dictionary<string, string>();

            foreach (var kvp in nameValueCollection)
            {
                result[kvp.Key] = nameValueCollection.Get(kvp.Key);
            }

            return result;
        }
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
            bool shouldSignin = signin != null;
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
            bool shouldSignout = signout != null;

            if (shouldSignin || shouldSignout || _shouldRenew)
            {
                var cookieOptions = new CookieOptions
                {
                    Domain   = Options.CookieDomain,
                    HttpOnly = Options.CookieHttpOnly,
                    Path     = Options.CookiePath ?? "/",
                };
                if (Options.CookieSecure == CookieSecureOption.SameAsRequest)
                {
                    cookieOptions.Secure = Request.IsSecure;
                }
                else
                {
                    cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always;
                }

                if (shouldSignin)
                {
                    var context = new CookieResponseSignInContext(
                        Context,
                        Options,
                        Options.AuthenticationType,
                        signin.Identity,
                        signin.Properties);

                    DateTimeOffset issuedUtc  = Options.SystemClock.UtcNow;
                    DateTimeOffset expiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);

                    context.Properties.IssuedUtc  = issuedUtc;
                    context.Properties.ExpiresUtc = expiresUtc;

                    Options.Provider.ResponseSignIn(context);

                    if (context.Properties.IsPersistent)
                    {
                        cookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime;
                    }

                    var    model       = new AuthenticationTicket(context.Identity, context.Properties);
                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    Response.Cookies.Append(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }
                else if (shouldSignout)
                {
                    Response.Cookies.Delete(
                        Options.CookieName,
                        cookieOptions);
                }
                else if (_shouldRenew)
                {
                    AuthenticationTicket model = await AuthenticateAsync();

                    model.Properties.IssuedUtc  = _renewIssuedUtc;
                    model.Properties.ExpiresUtc = _renewExpiresUtc;

                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    if (model.Properties.IsPersistent)
                    {
                        cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime;
                    }

                    Response.Cookies.Append(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }

                Response.Headers.Set(
                    HeaderNameCacheControl,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNamePragma,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNameExpires,
                    HeaderValueMinusOne);

                bool shouldLoginRedirect  = shouldSignin && Options.LoginPath.HasValue && Request.Path == Options.LoginPath;
                bool shouldLogoutRedirect = shouldSignout && Options.LogoutPath.HasValue && Request.Path == Options.LogoutPath;

                if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
                {
                    IReadableStringCollection query = Request.Query;
                    string redirectUri = query.Get(Options.ReturnUrlParameter);
                    if (!string.IsNullOrWhiteSpace(redirectUri) &&
                        IsHostRelative(redirectUri))
                    {
                        var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri);
                        Options.Provider.ApplyRedirect(redirectContext);
                    }
                }
            }
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                IReadableStringCollection query = Request.Query;
                string protectedRequestToken    = Request.Cookies[StateCookie];

                RequestToken requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken);

                if (requestToken == null)
                {
                    logger.WriteWarning("Invalid state");
                    return(null);
                }

                properties = requestToken.Properties;

                string returnedToken = query.Get("oauth_token");
                if (string.IsNullOrWhiteSpace(returnedToken))
                {
                    logger.WriteWarning("Missing oauth_token");
                    return(new AuthenticationTicket(null, properties));
                }

                if (returnedToken != requestToken.Token)
                {
                    logger.WriteWarning("Unmatched token");
                    return(new AuthenticationTicket(null, properties));
                }

                string oauthVerifier = query.Get("oauth_verifier");
                if (string.IsNullOrWhiteSpace(oauthVerifier))
                {
                    logger.WriteWarning("Missing or blank oauth_verifier");
                    return(new AuthenticationTicket(null, properties));
                }

                AccessToken accessToken = await ObtainAccessTokenAsync(Options.AppKey, Options.AppSecret, requestToken, oauthVerifier);

                var context = new FlickrAuthenticatedContext(Context, accessToken);

                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!String.IsNullOrEmpty(context.UserId))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId,
                                                        XmlSchemaString, Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName,
                                                        XmlSchemaString, Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.FullName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.FullName,
                                                        XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = requestToken.Properties;

                Response.Cookies.Delete(StateCookie);

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
예제 #19
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                IReadableStringCollection query = Request.Query;
                string protectedRequestToken    = Request.Cookies[StateCookie];

                RequestToken requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken);

                if (requestToken == null)
                {
                    _logger.WriteWarning("Invalid state");
                    return(null);
                }

                properties = requestToken.Properties;

                string returnedToken = query.Get("oauth_token");
                if (string.IsNullOrWhiteSpace(returnedToken))
                {
                    _logger.WriteWarning("Missing oauth_token");
                    return(new AuthenticationTicket(null, properties));
                }

                if (returnedToken != requestToken.Token)
                {
                    _logger.WriteWarning("Unmatched token");
                    return(new AuthenticationTicket(null, properties));
                }

                AccessToken accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken);

                JObject profileObject = await ObtainUserProfile(Options.ConsumerKey, Options.ConsumerSecret, accessToken);

                var context = new TripItAuthenticatedContext(Context, profileObject, accessToken.Token, accessToken.TokenSecret);

                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!String.IsNullOrEmpty(context.ScreenName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.ScreenName,
                                                        "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.DisplayName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.DisplayName,
                                                        "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email,
                                                        "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.UserId))
                {
                    context.Identity.AddClaim(new Claim("urn:tripit:userid", context.UserId,
                                                        "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.ScreenName))
                {
                    context.Identity.AddClaim(new Claim("urn:tripit:sreenname", context.ScreenName,
                                                        "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                context.Properties = requestToken.Properties;

                Response.Cookies.Delete(StateCookie);

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
        public static ScimQueryOptions GetScimQueryOptions(this IReadableStringCollection collection, ScimServerConfiguration configuration)
        {
            var queryOptions = new ScimQueryOptions();

            queryOptions.Attributes = collection.GetValues("attributes")
                                      .ToMaybe()
                                      .Bind(attributes => new HashSet <string>(attributes.Distinct(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase).ToMaybe())
                                      .FromMaybe(new HashSet <string>());

            queryOptions.ExcludedAttributes = collection.GetValues("excludedAttributes")
                                              .ToMaybe()
                                              .Bind(attributes => new HashSet <string>(attributes.Distinct(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase).ToMaybe())
                                              .FromMaybe(new HashSet <string>());

            queryOptions.Filter = collection.Get("filter")
                                  .ToMaybe()
                                  .Bind(filter => new ScimFilter(configuration.ResourceExtensionSchemas.Keys, filter).Paths.MaybeSingle())
                                  .FromMaybe(null);

            queryOptions.SortBy = collection.Get("sortBy");

            queryOptions.SortOrder = collection.Get("sortOrder")
                                     .ToMaybe()
                                     .Bind(
                sortOrder =>
                (sortOrder.Equals("descending", StringComparison.OrdinalIgnoreCase)
                            ? SortOrder.Descending
                            : SortOrder.Ascending).ToMaybe())
                                     .FromMaybe(SortOrder.Ascending); // default

            queryOptions.StartIndex = collection.Get("startIndex")
                                      .ToMaybe()
                                      .Bind(index =>
            {
                // The 1-based index of the first query result. A value less than 1 SHALL be interpreted as 1.

                int indexInt = 1;
                try { indexInt = Convert.ToInt32(index); } catch {}

                return((indexInt < 1 ? 1 : indexInt).ToMaybe());
            })
                                      .FromMaybe(1); // default

            queryOptions.Count = collection.Get("count")
                                 .ToMaybe()
                                 .Bind(count =>
            {
                // Non-negative integer. Specifies the desired maximum number of query
                // results per page, e.g., 10. A negative value SHALL be interpreted as
                // "0". A value of "0" indicates that no resource indicates that no resource
                // except for "totalResults".

                int countInt = 0;
                try { countInt = Convert.ToInt32(count); } catch { }

                return((countInt < 0 ? 0 : countInt).ToMaybe());
            })
                                 .FromMaybe(configuration.GetFeature <ScimFeatureFilter>(ScimFeatureType.Filter).MaxResults); // default

            return(queryOptions);
        }
예제 #21
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                IReadableStringCollection query = Request.Query;
                string protectedRequestToken    = Options.CookieManager.GetRequestCookie(Context, StateCookie);

                RequestToken requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken);

                if (requestToken == null)
                {
                    _logger.WriteWarning("Invalid state");
                    return(null);
                }

                properties = requestToken.Properties;

                string returnedToken = query.Get("oauth_token");
                if (string.IsNullOrWhiteSpace(returnedToken))
                {
                    _logger.WriteWarning("Missing oauth_token");
                    return(new AuthenticationTicket(null, properties));
                }

                if (returnedToken != requestToken.Token)
                {
                    _logger.WriteWarning("Unmatched token");
                    return(new AuthenticationTicket(null, properties));
                }

                string oauthVerifier = query.Get("oauth_verifier");
                if (string.IsNullOrWhiteSpace(oauthVerifier))
                {
                    _logger.WriteWarning("Missing or blank oauth_verifier");
                    return(new AuthenticationTicket(null, properties));
                }

                AccessToken accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier);

                var context = new TwitterAuthenticatedContext(Context, accessToken.UserId, accessToken.ScreenName, accessToken.Token, accessToken.TokenSecret);

                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim(ClaimTypes.Name, accessToken.ScreenName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim("urn:twitter:userid", accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
                    new Claim("urn:twitter:screenname", accessToken.ScreenName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                context.Properties = requestToken.Properties;

                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Secure   = Request.IsSecure
                };

                Options.CookieManager.DeleteCookie(Context, StateCookie, cookieOptions);

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
예제 #22
0
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
            bool shouldSignin = signin != null;
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
            bool shouldSignout = signout != null;

            if (!(shouldSignin || shouldSignout || _shouldRenew))
            {
                return;
            }

            AuthenticationTicket model = await AuthenticateAsync();

            try
            {
                var cookieOptions = new CookieOptions
                {
                    Domain   = Options.CookieDomain,
                    HttpOnly = Options.CookieHttpOnly,
                    Path     = Options.CookiePath ?? "/",
                };
                if (Options.CookieSecure == CookieSecureOption.SameAsRequest)
                {
                    cookieOptions.Secure = Request.IsSecure;
                }
                else
                {
                    cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always;
                }

                #region == 登陆,登出,刷新 ==

                // 登陆
                if (shouldSignin)
                {
                    var signInContext = new CookieResponseSignInContext(
                        Context,
                        Options,
                        Options.AuthenticationType,
                        signin.Identity,
                        signin.Properties,
                        cookieOptions);

                    DateTimeOffset issuedUtc;
                    if (signInContext.Properties.IssuedUtc.HasValue)
                    {
                        issuedUtc = signInContext.Properties.IssuedUtc.Value;
                    }
                    else
                    {
                        issuedUtc = Options.SystemClock.UtcNow;
                        signInContext.Properties.IssuedUtc = issuedUtc;
                    }

                    if (!signInContext.Properties.ExpiresUtc.HasValue)
                    {
                        signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
                    }

                    Options.Provider.ResponseSignIn(signInContext);

                    if (signInContext.Properties.IsPersistent)
                    {
                        DateTimeOffset expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan);
                        signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime;
                    }

                    model = new AuthenticationTicket(signInContext.Identity, signInContext.Properties);
                    if (Options.SessionStore != null)
                    {
                        if (_sessionKey != null)
                        {
                            await Options.SessionStore.RemoveAsync(_sessionKey);
                        }
                        _sessionKey = await Options.SessionStore.StoreAsync(model);

                        ClaimsIdentity identity = new ClaimsIdentity(
                            new[] { new Claim(SessionIdClaim, _sessionKey) },
                            Options.AuthenticationType);
                        model = new AuthenticationTicket(identity, null);
                    }

                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    Options.CookieManager.AppendResponseCookie(
                        Context,
                        Options.CookieName,
                        cookieValue,
                        signInContext.CookieOptions);

                    var signedInContext = new CookieResponseSignedInContext(
                        Context,
                        Options,
                        Options.AuthenticationType,
                        signInContext.Identity,
                        signInContext.Properties);

                    Options.Provider.ResponseSignedIn(signedInContext);
                }
                // 登出
                else if (shouldSignout)
                {
                    if (Options.SessionStore != null && _sessionKey != null)
                    {
                        await Options.SessionStore.RemoveAsync(_sessionKey);
                    }

                    var context = new CookieResponseSignOutContext(
                        Context,
                        Options,
                        cookieOptions);

                    Options.Provider.ResponseSignOut(context);

                    Options.CookieManager.DeleteCookie(
                        Context,
                        Options.CookieName,
                        context.CookieOptions);
                }
                // 刷新
                else if (_shouldRenew)
                {
                    model.Properties.IssuedUtc  = _renewIssuedUtc;
                    model.Properties.ExpiresUtc = _renewExpiresUtc;

                    if (Options.SessionStore != null && _sessionKey != null)
                    {
                        await Options.SessionStore.RenewAsync(_sessionKey, model);

                        ClaimsIdentity identity = new ClaimsIdentity(
                            new[] { new Claim(SessionIdClaim, _sessionKey) },
                            Options.AuthenticationType);
                        model = new AuthenticationTicket(identity, null);
                    }

                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    if (model.Properties.IsPersistent)
                    {
                        cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime;
                    }

                    Options.CookieManager.AppendResponseCookie(
                        Context,
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }

                #endregion

                Response.Headers.Set(
                    HeaderNameCacheControl,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNamePragma,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNameExpires,
                    HeaderValueMinusOne);

                // 跳转
                bool shouldLoginRedirect  = shouldSignin && Options.LoginPath.HasValue && Request.Path == Options.LoginPath;
                bool shouldLogoutRedirect = shouldSignout && Options.LogoutPath.HasValue && Request.Path == Options.LogoutPath;

                if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
                {
                    IReadableStringCollection query = Request.Query;
                    string redirectUri = query.Get(Options.ReturnUrlParameter); // 根据url参数读取 跳转url
                    if (!string.IsNullOrWhiteSpace(redirectUri) &&
                        IsHostRelative(redirectUri))
                    {
                        var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri);
                        Options.Provider.ApplyRedirect(redirectContext);
                    }
                }
            }
            catch (Exception exception)
            {
                CookieExceptionContext exceptionContext = new CookieExceptionContext(Context, Options,
                                                                                     CookieExceptionContext.ExceptionLocation.ApplyResponseGrant, exception, model);
                Options.Provider.Exception(exceptionContext);
                if (exceptionContext.Rethrow)
                {
                    throw;
                }
            }
        }