public override async Task Authenticated(VkAuthenticatedContext context)
 {
     context.Identity.AddClaim(new Claim("token", context.AccessToken));
     await base.Authenticated(context);
 }
示例#2
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            _logger.WriteVerbose("AuthenticateCore");

            AuthenticationProperties properties = null;

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

                var query  = Request.Query;
                var 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);
                }

                string tokenEndpoint = "https://oauth.vk.com/access_token";

                string requestPrefix = Request.GetRealRequestScheme() + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.ReturnEndpointPath;

                string tokenRequest =
                    "?client_id=" + Uri.EscapeDataString(Options.AppId) +
                    "&client_secret=" + Uri.EscapeDataString(Options.AppSecret) +
                    "&code=" + Uri.EscapeDataString(code) +
                    "&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
                    "&v=" + vkApiVersion;

                HttpResponseMessage tokenResponse = await _httpClient.GetAsync(tokenEndpoint + tokenRequest, Request.CallCancelled);

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

                var form = JsonConvert.DeserializeObject <Dictionary <string, object> >(text);

                var accessToken = (string)form["access_token"];
                var userId      = (long)form["user_id"];

                string graphApiEndpoint = "https://api.vk.com/method/users.get" +
                                          "?user_id=" + userId +
                                          "&fields=sex,photo_100,screen_name" +
                                          "&name_case=Nom" +
                                          "&access_token=" + Uri.EscapeDataString(accessToken) +
                                          "&v=" + vkApiVersion;

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(graphApiEndpoint, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject data = JObject.Parse(text);
                var     user = (JObject)data["response"].First;

                var context = new VkAuthenticatedContext(Context, user, accessToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString,
                                                        Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString,
                                                        Options.AuthenticationType));
                }

                if (!string.IsNullOrEmpty(context.FirstName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.GivenName, context.FirstName));
                }
                if (!string.IsNullOrEmpty(context.LastName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Surname, context.LastName));
                }
                if (!string.IsNullOrEmpty(context.AvatarUrl))
                {
                    context.Identity.AddClaim(new Claim("AvatarUrl", context.AvatarUrl));
                }
                context.Identity.AddClaim(new Claim(ClaimTypes.Gender, context.Sex.ToString()));
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }

            return(new AuthenticationTicket(null, properties));
        }
        //step 2.3
        //making AuthenticationTicket after client return from Vk.com
        //here we make actually autorization work
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code = "";

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");

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

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

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

                string requestPrefix = Request.Scheme + Uri.SchemeDelimiter + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                //https://oauth.vk.com/access_token?client_id=APP_ID&client_secret=APP_SECRET&code=7a6fa4dff77a228eeda56603b8f53806c883f011c40b72630bb50df056f6479e52a&redirect_uri=REDIRECT_URI
                string tokenRequest = TokenEndpoint + "?client_id=" + Uri.EscapeDataString(Options.AppId) +
                                      "&client_secret=" + Uri.EscapeDataString(Options.AppSecret) +
                                      "&code=" + Uri.EscapeDataString(code) +
                                      "&redirect_uri=" + Uri.EscapeDataString(redirectUri);

                HttpResponseMessage tokenResponse = await _httpClient.GetAsync(tokenRequest, Request.CallCancelled);

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

                //IFormCollection form = WebHelpers.ParseForm(text);
                var JsonResponse = JsonConvert.DeserializeObject <dynamic>(text);
                //JObject TokenResponse = JObject.Parse(text);

                string accessToken = JsonResponse["access_token"];
                string expires     = JsonResponse["expires_in"];
                string userid      = JsonResponse["user_id"];
                string email       = JsonResponse["email"];

                //public method which dont require token
                string userInfoLink = GraphApiEndpoint + "users.get.xml" +
                                      "?user_ids=" + Uri.EscapeDataString(userid) +
                                      "&fields=" + Uri.EscapeDataString("nickname,screen_name,photo_50");

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(userInfoLink, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                XmlDocument UserInfoResponseXml = new XmlDocument();
                UserInfoResponseXml.LoadXml(text);

                var context = new VkAuthenticatedContext(Context, UserInfoResponseXml, accessToken, expires, Options.PreferedNameClaim);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.DefaultName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.DefaultName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FullName))
                {
                    context.Identity.AddClaim(new Claim("urn:vkontakte:name", context.FullName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:vkontakte:link", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, email, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
示例#4
0
 public override Task Authenticated(VkAuthenticatedContext context)
 {
     context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
     context.Identity.AddClaim(new Claim("UserId", context.Id));
     return(Task.FromResult <object>(null));
 }
 public override Task Authenticated(VkAuthenticatedContext context)
 {
     context.Identity.AddClaim(
         new Claim(ServiceClaimTypes.ProviderAccessToken, context.AccessToken));
     return(base.Authenticated(context));
 }