internal static MappedResult <T> CreateSuccessfull(T result, HttpStatusCode statusCode)
        {
            var mappedResult = new MappedResult <T>(result, (int)statusCode)
            {
                IsSuccessfull = true
            };

            return(mappedResult);
        }
        internal static MappedResult <T> CreateUnsuccessfull(int statusCode, string reasonPhrase)
        {
            var mappedResult = new MappedResult <T>(null, statusCode)
            {
                ReasonPhrase  = reasonPhrase,
                IsSuccessfull = false
            };

            return(mappedResult);
        }
Пример #3
0
        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("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);
                }

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

                var tokenRequestParameters = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                    new KeyValuePair <string, string>("redirect_uri", GenerateRedirectUri()),
                    new KeyValuePair <string, string>("client_secret", Options.ClientSecret),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                };

                var requestContent = new FormUrlEncodedContent(tokenRequestParameters);

                HttpResponseMessage response = await _httpClient.PostAsync(Options.Endpoints.TokenEndpoint, requestContent, Request.CallCancelled);

                response.EnsureSuccessStatusCode();
                string oauthTokenResponse = await response.Content.ReadAsStringAsync();

                JObject oauth2Token = JObject.Parse(oauthTokenResponse);
                string  accessToken = oauth2Token["access_token"].Value <string>();

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

                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                MappedResult <JObject> accountInformation = await _httpClient.DownloadJsonAsync <JObject>(Options.Endpoints.UserInfoEndpoint);

                SurveyMonkeyAuthenticatedContext context = new SurveyMonkeyAuthenticatedContext(Context, _httpClient, Options.AuthenticationType, accountInformation.Result, accessToken);

                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim(ClaimTypes.GivenName, context.FirstName, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim(ClaimTypes.Surname, context.LastName, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:" + Options.AuthenticationType + ":username", context.UserName, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:" + Options.AuthenticationType + ":account_type", context.AccountType, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:" + Options.AuthenticationType + ":language", context.Language, Constants.XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:" + Options.AuthenticationType + ":date_created", context.DateCreated, Constants.XmlSchemaString, Options.AuthenticationType)
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                //To Do
                if (!string.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, Constants.XmlSchemaString, Options.AuthenticationType));
                }

                await Options.Provider.Authenticated(context);

                context.Properties = properties;

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Пример #4
0
        /// <summary>
        /// Authenticate users using SurveyMonkey Account.
        /// </summary>
        /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
        /// <param name="clientId">The application client ID assigned by the  authentication service</param>
        /// <param name="clientSecret">The application client secret assigned by the  authentication service</param>
        /// <param name="callbackPath">The return URL specified in the SurveyMonkey API App</param>
        /// <param name="apiKey">The SurveyMonkey API Key</param>

        public static IAppBuilder UseSurveyMonkeyAuthentication(this IAppBuilder app, string clientId, string clientSecret, string callbackPath, string apiKey)
        {
            Error Errors = new Error();
            SurveyMonkeyAuthenticationOptions surveyMonkeyAuthenticationOptions = new SurveyMonkeyAuthenticationOptions(Constants.DefaultAuthenticationType, apiKey, callbackPath);

            surveyMonkeyAuthenticationOptions.ClientId     = clientId;
            surveyMonkeyAuthenticationOptions.ClientSecret = clientSecret;
            surveyMonkeyAuthenticationOptions.Provider     = new SurveyMonkeyAuthenticationProvider
            {
                OnAuthenticated = async context =>
                {
                    if (context.AccountType != "select_yearly" && context.AccountType != "basic")
                    {
                        MappedResult <GroupRequestResult> group = await context.Client.DownloadJsonAsync <GroupRequestResult>(surveyMonkeyAuthenticationOptions.Endpoints.UserGroupEndpoint);

                        if (group.IsSuccessfull)
                        {
                            var    groupData       = group.Result.Data;
                            string groupMembersUri = string.Format(surveyMonkeyAuthenticationOptions.Endpoints.GroupMemberEndpoint, groupData.First().Id);
                            MappedResult <GroupMembersRequestResult> groupMembers = await context.Client.DownloadJsonAsync <GroupMembersRequestResult>(groupMembersUri);

                            if (groupMembers.IsSuccessfull)
                            {
                                List <Member> groupMembersData = groupMembers.Result.Data;
                                Member        memberData       = groupMembersData.Where(e => e.Username == context.UserName).First();
                                string        groupMemberUri   = string.Format(surveyMonkeyAuthenticationOptions.Endpoints.MemberEndpoint, group.Result.Data.First().Id, memberData.Id);
                                MappedResult <MemberRequestResult> groupMember = await context.Client.DownloadJsonAsync <MemberRequestResult>(groupMemberUri);

                                if (groupMember.IsSuccessfull)
                                {
                                    var UserGroup = group.Result.Data.First().Name;
                                    var Role      = groupMember.Result.Type;

                                    context.Identity.AddClaim(new Claim("urn:" + context.AuthenticationType + ":access_token", context.AccessToken, Constants.XmlSchemaString, context.AuthenticationType));
                                    if (!string.IsNullOrWhiteSpace(UserGroup))
                                    {
                                        context.Identity.AddClaim(new Claim("urn:" + context.AuthenticationType + ":group", UserGroup, Constants.XmlSchemaString, context.AuthenticationType));
                                    }

                                    if (!string.IsNullOrWhiteSpace(Role))
                                    {
                                        context.Identity.AddClaim(new Claim(ClaimTypes.Role, Role, Constants.XmlSchemaString, context.AuthenticationType));
                                    }
                                }
                                else
                                {
                                    Errors.Add("member", groupMember.ReasonPhrase);
                                }
                            }
                            else
                            {
                                Errors.Add("members", groupMembers.ReasonPhrase);
                            }
                        }
                        else
                        {
                            Errors.Add("groups", group.ReasonPhrase);
                        }
                    }

                    if (Errors.Count > 0)
                    {
                        await Task.FromResult(Errors);
                    }
                },
                OnApplyRedirect = context => context.Response.Redirect(context.RedirectUri)
            };

            return(UseSurveyMonkeyAuthentication(
                       app,
                       surveyMonkeyAuthenticationOptions
                       ));
        }
Пример #5
0
 public MappedResult(MappedResult anotherPreMapped)
 {
     AnotherPreMapped = anotherPreMapped;
 }