Пример #1
0
 /// <summary>
 /// Invoked whenever VanLang succesfully authenticates a user
 /// </summary>
 /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
 /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
 public virtual Task Authenticated(VanLangAuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query = Request.Query;

                IList <string> values = query.GetValues("error");
                if (values != null && values.Count >= 1)
                {
                    _logger.WriteVerbose("Remote server returned an error: " + Request.QueryString);
                }

                values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

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

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

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

                var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("code", Uri.EscapeDataString(code))
                });

                HttpResponseMessage tokenResponse = await _httpClient.PostAsync(Options.UserInformationEndpoint, formContent, Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string user = await tokenResponse.Content.ReadAsStringAsync();

                JObject response = JObject.Parse(user);

                string accessToken = response.Value <string>("access_token");

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

                var email           = response.Value <string>("Email");
                var defaultUserName = response.Value <string>("DefaultUserName");

                var context = new VanLangAuthenticatedContext(Context);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, accessToken, XmlSchemaString, Options.AuthenticationType));
                if (!string.IsNullOrEmpty(defaultUserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, defaultUserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, email, XmlSchemaString, Options.AuthenticationType));
                }
                //TO-DO: fix bug

                var idClaim = context.Identity.FindFirst(ClaimTypes.NameIdentifier);

                //if (HttpContext.Current != null)
                HttpContext.Current.Session["ExternalLoginInfo"] = new ExternalLoginInfo
                {
                    ExternalIdentity = context.Identity,
                    Login            = new UserLoginInfo(idClaim.Issuer, idClaim.Value),
                    DefaultUserName  = defaultUserName,
                    Email            = email
                };

                context.Properties = properties;

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