Example #1
0
 private static IEnumerable <string> ScopeStrings(AuthorizationScope scope)
 {
     if ((scope & AuthorizationScope.Collection) != 0)
     {
         yield return("collection");
     }
     if ((scope & AuthorizationScope.EMail) != 0)
     {
         yield return("email");
     }
     if ((scope & AuthorizationScope.Profile) != 0)
     {
         yield return("profile");
     }
     if ((scope & AuthorizationScope.Rating) != 0)
     {
         yield return("rating");
     }
     if ((scope & AuthorizationScope.SubmitBarcode) != 0)
     {
         yield return("submit_barcode");
     }
     if ((scope & AuthorizationScope.SubmitIsrc) != 0)
     {
         yield return("submit_isrc");
     }
     if ((scope & AuthorizationScope.Tag) != 0)
     {
         yield return("tag");
     }
 }
        public void InitializeAuthorizationScopeWorksWithCsdl()
        {
            // Arrange
            string annotation = @"<Annotation Term=""NS.MyAuthorizationScope"">
                <Record Type=""Org.OData.Authorization.V1.AuthorizationScope"" >
                  <PropertyValue Property=""Scope"" String=""Scope name"" />
                  <PropertyValue Property=""Description"" String=""Description of the scope"" />
                  <PropertyValue Property=""Grant"" String=""grant access"" />
                </Record>
              </Annotation>";

            IEdmModel model = GetEdmModel(annotation);

            Assert.NotNull(model); // guard
            Assert.NotNull(model.EntityContainer);

            // Act
            AuthorizationScope scope = model.GetRecord <AuthorizationScope>(model.EntityContainer, "NS.MyAuthorizationScope");

            // Assert
            Assert.NotNull(scope);
            Assert.Equal("Scope name", scope.Scope);
            Assert.Equal("Description of the scope", scope.Description);
            Assert.Equal("grant access", scope.Grant);
        }
Example #3
0
        /// <summary>
        /// Gets the authorization URL.
        /// </summary>
        /// <param name="scope">An enum of permissions.</param>
        /// <param name="state">A unique identifier to use as a CSRF check.</param>
        /// <param name="redirectUri">The redirect URI.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">
        /// The value cannot be empty;state
        /// or
        /// The value cannot be empty;redirectUri
        /// </exception>
        public Uri GetAuthorizationUrl(AuthorizationScope scope, string state, string redirectUri)
        {
            if (string.IsNullOrEmpty(state))
            {
                throw new ArgumentException("The value cannot be empty", "state");
            }
            if (string.IsNullOrEmpty(redirectUri))
            {
                throw new ArgumentException("The value cannot be empty", "redirectUri");
            }

            this.CheckConfiguration(apiKey: true);

            var flags = Enum.GetValues(typeof(AuthorizationScope))
                        .Cast <AuthorizationScope>()
                        .Where(s => (scope & s) == s)
                        .Select(s => s.GetAuthorizationName())
                        .ToArray();
            var scopeAsString = string.Join(" ", flags);

            var url = string.Format(
                "{0}/oauth/v2/authorization?response_type=code&client_id={1}&scope={2}&state={3}&redirect_uri={4}",
                this.LinkedInApi.Configuration.BaseOAuthUrl,
                Uri.EscapeDataString(this.LinkedInApi.Configuration.ApiKey),
                Uri.EscapeDataString(scopeAsString),
                Uri.EscapeDataString(state),
                Uri.EscapeDataString(redirectUri));

            return(new Uri(url));
        }
Example #4
0
        public void UnauthenticatedActivityNullDefaultFalse()
        {
            var scope = new AuthorizationScope
            {
                Activities =
                {
                    new Activity
                    {
                        Resource = "Home",
                        Action   = "Index",
                        //AllowUnauthenticated = true,
                        // NB This allows us to override the top level default
                        Default = false,
                    }
                }
            };

            var provider   = new StaticAuthorizationScopeProvider(scope);
            var authorizer = new ActivityAuthorizer(provider, false, null, false);

            var principal = CreatePrincipal("fred", new List <string>(), null, false);
            var candidate = authorizer.IsAuthorized("Home", "Index", principal);

            Assert.That(candidate.IsAuthorized, Is.False, "IsAuthorized differs");
            Assert.That(candidate.Reason, Is.Null, "Reason differs");
        }
        /// <summary>Creates the URI to use to request an authorization code.</summary>
        /// <param name="redirectUri">The URI that should receive the authorization code; use <see cref="OutOfBandUri"/> for out-of-band requests.</param>
        /// <param name="scope">The authorization scopes that should be included in the authorization code.</param>
        /// <param name="state">An optional string that will be included in the response sent to <paramref name="redirectUri"/>.</param>
        /// <param name="offlineAccess">Requests offline use (a refresh token will be provided alongside the access token).</param>
        /// <param name="forcePrompt">If true, the user will be required to confirm authorization even if the requested scopes have already been granted.</param>
        /// <returns>The generated URI.</returns>
        public Uri CreateAuthorizationRequest(Uri redirectUri, AuthorizationScope scope, string?state = null, bool offlineAccess = false, bool forcePrompt = false)
        {
            if (scope == AuthorizationScope.None)
            {
                throw new ArgumentException("At least one authorization scope must be selected.", nameof(scope));
            }
            var uri   = this.BuildEndPointUri(OAuth2.AuthorizationEndPoint);
            var query = new StringBuilder();

            query.Append("response_type=code");
            query.Append("&client_id=").Append(Uri.EscapeDataString(this.ClientId));
            query.Append("&redirect_uri=").Append(Uri.EscapeDataString(redirectUri.ToString()));
            query.Append("&scope=").Append(string.Join("+", OAuth2.ScopeStrings(scope)));
            if (state != null)
            {
                query.Append("&state=").Append(Uri.EscapeDataString(state));
            }
            if (offlineAccess)
            {
                query.Append("&access_type=offline");
            }
            if (forcePrompt)
            {
                query.Append("&approval_prompt=force");
            }
            uri.Query = query.ToString();
            return(uri.Uri);
        }
        public void User_ReadWrite()
        {
            var sut    = new AuthorizationScope(AuthorizationRole.User, AuthorizationPermission.ReadWrite);
            var result = sut.ToString();

            Assert.AreEqual("user,rw", result);
        }
        public void Owner_ReadOnly()
        {
            var sut    = new AuthorizationScope(AuthorizationRole.Owner, AuthorizationPermission.ReadOnly);
            var result = sut.ToString();

            Assert.AreEqual("owner,ro", result);
        }
        public void Admin_ReadOnly()
        {
            var sut    = new AuthorizationScope(AuthorizationRole.Admin, AuthorizationPermission.ReadOnly);
            var result = sut.ToString();

            Assert.AreEqual("admin,ro", result);
        }
Example #9
0
        static void Main(string[] args)
        {
            Console.Write("Client ID: ");
            var clientId = Console.ReadLine();

            Console.Write("Client Secret: ");
            var clientSecret = Console.ReadLine();

            Console.WriteLine("Please authenticate to HiDrive in your browser and come back here.");
            var authenticator = new HiDriveAuthenticator(clientId, clientSecret);
            var scope         = new AuthorizationScope(AuthorizationRole.User, AuthorizationPermission.ReadWrite);
            var authUrl       = authenticator.GetAuthorizationCodeRequestUrl(scope);

            Process.Start(authUrl);

            Console.Write("Code: ");
            var code = Console.ReadLine();

            Console.WriteLine("Gathering RefreshToken...");
            var token = authenticator.AuthenticateByAuthorizationCodeAsync(code);

            token.Wait();

            Console.WriteLine("RefreshToken: {0}", token.Result.RefreshToken);

            WriteClientConfiguration(clientId, clientSecret, token.Result.RefreshToken);

            Console.ReadLine();
        }
        public void Standard()
        {
            var source = new AuthorizationScope
            {
                DefaultActivity = "Foo",
                Activities      =
                {
                    new Activity
                    {
                        Resource = "Home",
                        Action   = "Index",
                        Deny     = new Permission
                        {
                            Users  = { "A",     "D" },
                            Claims =
                            {
                                new Claim("team", "E", string.Empty, "bar")
                            }
                        },
                        Allow = new Permission
                        {
                            Roles  = { "B",     "C" },
                            Claims =
                            {
                                new Claim("team", "F", string.Empty, "bar"),
                                new Claim("team", "G", string.Empty, "bar")
                            }
                        }
                    },
                    new Activity
                    {
                        Resource = "Foo",
                        Deny     = new Permission
                        {
                            Users  = { "A",     "D" },
                            Claims =
                            {
                                new Claim("team", "E", string.Empty, "bar")
                            }
                        },
                        Allow = new Permission
                        {
                            Roles  = { "B",     "C" },
                            Claims =
                            {
                                new Claim("team", "F", string.Empty, "bar"),
                                new Claim("team", "G", string.Empty, "bar")
                            }
                        }
                    }
                }
            };

            var json = source.ToJson();

            var candidate = json.ToAuthorizations();

            Check(source, candidate);
        }
 public SettingsAuthorizationException(AuthorizationScope scope, AuthorizationLevel level, string objectName, int identity)
     : base(string.Format("{0} {1} {2}: {3}.", level, scope, objectName ?? "unknown", Constants.ERROR_ACCESS_DENIED))
 {
     _scope = scope;
     _level = level;
     _objectName = objectName;
     _identity = identity;
 }
 public SettingsAuthorizationException(AuthorizationScope scope, AuthorizationLevel level, string objectName, int identity)
     : base(string.Format("{0} {1} {2}: {3}.", level, scope, objectName ?? "unknown", Constants.ERROR_ACCESS_DENIED))
 {
     _scope      = scope;
     _level      = level;
     _objectName = objectName;
     _identity   = identity;
 }
Example #13
0
        internal static string GetAuthorizationName(this AuthorizationScope scope)
        {
            switch (scope)
            {
            case AuthorizationScope.ReadBasicProfile:
                return("r_basicprofile");

            case AuthorizationScope.ReadFullProfile:
                return("r_fullprofile");

            case AuthorizationScope.ReadEmailAddress:
                return("r_emailaddress");

            case AuthorizationScope.ReadNetwork:
                return("r_network");

            case AuthorizationScope.ReadContactInfo:
                return("r_contactinfo");

            case AuthorizationScope.ReadWriteNetworkUpdates:
                return("rw_nus");

            case AuthorizationScope.ReadWriteCompanyPage:
                return("rw_company_admin");

            case AuthorizationScope.ReadWriteGroups:
                return("rw_groups");

            case AuthorizationScope.WriteMessages:
                return("w_messages");

            case AuthorizationScope.WriteShare:
                return("w_share");

            case AuthorizationScope.ReadWriteOrganization:
                return("rw_organization");

            case AuthorizationScope.ReadFirstConnectionsSize:
                return("r_1st_connections_size");

            case AuthorizationScope.ReadLiteProfile:
                return("r_liteprofile");

            case AuthorizationScope.ReadAdsReporting:
                return("r_ads_reporting");

            case AuthorizationScope.ReadOrganizationSocial:
                return("r_organization_social");

            default:
                throw new NotSupportedException("Scope of value '" + scope.ToString() + " is not supported");
            }
        }
Example #14
0
        public void DefaultFalseUnauthenticatedFalse()
        {
            var scope      = new AuthorizationScope();
            var provider   = new StaticAuthorizationScopeProvider(scope);
            var authorizer = new ActivityAuthorizer(provider, false, null, false);

            var principal = CreatePrincipal("fred", new List <string>(), null, false);
            var candidate = authorizer.IsAuthorized("Test", null, principal);

            Assert.That(candidate.IsAuthorized, Is.False, "IsAuthorized differs");
            Assert.That(candidate.Reason, Is.EqualTo("IsAuthenticated: false"), "Reason differs");
        }
Example #15
0
        public void AuthorizerDefaultAuthorizationFalse()
        {
            var scope      = new AuthorizationScope();
            var provider   = new StaticAuthorizationScopeProvider(scope);
            var authorizer = new ActivityAuthorizer(provider, false);

            Assert.AreEqual(false, authorizer.DefaultAuthorization, "Default authorization differs");

            var principal = CreatePrincipal("charlie", new List <string>());
            var candidate = authorizer.IsAuthorized("Test", null, principal);

            Assert.That(candidate.IsAuthorized, Is.False, "IsAuthorized differs");
        }
Example #16
0
        /// <summary>
        /// Build Authorization URI.
        /// </summary>
        /// <param name="state">Identifying tag. This tag will be transmitted both sent link and callback link.</param>
        /// <param name="scope">Access scope option.</param>
        /// <returns>Generated user authorization link.</returns>
        public Uri BuildAuthorizationLink(string state, AuthorizationScope scope)
        {
            var sb = new StringBuilder($"{AuthorizationLink}?");

            string responseType = "code";

            sb.Append($"client_id={_clientId}");
            sb.Append($"&redirect_uri={HttpUtility.UrlEncode(_registeredRedirectUri.OriginalString)}");
            sb.Append($"&response_type={responseType}");
            sb.Append($"&scope={HttpUtility.UrlEncode(string.Join(" ", scope.GetRequestArray()))}");
            sb.Append($"&state={HttpUtility.UrlEncode(state)}");

            return(new Uri(sb.ToString()));
        }
Example #17
0
        /// <summary>
        /// Build Authorization URI.
        /// </summary>
        /// <param name="redirectUri">Client redirect URI (URL encoded)</param>
        /// <param name="tag">Identifying tag. This tag will be transmitted both sent link and callback link.</param>
        /// <param name="scope">Access scope option.</param>
        /// <returns>Generated user authorization link.</returns>
        public Uri BuildLink(Uri redirectUri, string tag, AuthorizationScope scope)
        {
            var sb = new StringBuilder($"{RequestLink}?");

            string responseType = "code";

            sb.Append($"response_type={responseType}");
            sb.Append($"&client_id={_clientId}");
            sb.Append($"&redirect_uri={redirectUri.AbsoluteUri}");
            sb.Append($"&state={tag}");
            sb.Append($"&scope={string.Join(" ", scope.GetRequestArray())}");

            return(new Uri(sb.ToString()));
        }
Example #18
0
            public void Works()
            {
                AuthorizationScope scope       = AuthorizationScope.ReadBasicProfile | AuthorizationScope.ReadEmailAddress;
                string             state       = "AZERTYUIOP";
                string             redirectUri = "http://localhost/Callbacks/LinkedIN?Redirect=" + Uri.EscapeDataString("/Profile?LinkedIN");

                var config = new LinkedInApiConfiguration {
                    ApiKey = "HELLOAPI", BaseOAuthUrl = "https://linkedin.com",
                };
                var api = new LinkedInApi(config);

                var result = api.OAuth2.GetAuthorizationUrl(scope, state, redirectUri);

                Assert.AreEqual("https://linkedin.com/uas/oauth2/authorization?response_type=code&client_id=HELLOAPI&scope=r_basicprofile%20r_emailaddress&state=AZERTYUIOP&redirect_uri=http%3A%2F%2Flocalhost%2FCallbacks%2FLinkedIN%3FRedirect%3D%252FProfile%253FLinkedIN", result.OriginalString);
            }
Example #19
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            PersonalDataAuthorizationScope = await _context.AuthorizationScopes.FirstOrDefaultAsync(m => m.Id == id);

            if (PersonalDataAuthorizationScope == null)
            {
                return(NotFound());
            }
            return(Page());
        }
        public void InitializeAuthorizationScopeWithRecordSuccess()
        {
            // Arrange
            IEdmRecordExpression record = new EdmRecordExpression(
                new EdmPropertyConstructor("Scope", new EdmStringConstant("ScopeName")),
                new EdmPropertyConstructor("Grant", new EdmStringConstant("GrantAccess")));

            AuthorizationScope scope = new AuthorizationScope();

            Assert.Null(scope.Scope);
            Assert.Null(scope.Description);
            Assert.Null(scope.Grant);

            // Act
            scope.Initialize(record);

            // Assert
            Assert.Equal("ScopeName", scope.Scope);
            Assert.Null(scope.Description);
            Assert.Equal("GrantAccess", scope.Grant);
        }
Example #21
0
        /// <summary>Creates the URI to use to request an authorization code.</summary>
        /// <param name="redirectUri">The URI that should receive the authorization code; use <see cref="OutOfBandUri"/> for out-of-band requests.</param>
        /// <param name="scope">The authorization scopes that should be included in the authorization code.</param>
        /// <param name="state">An optional string that will be included in the response sent to <paramref name="redirectUri"/>.</param>
        /// <param name="offlineAccess">Requests offline use (a refresh token will be provided alongside the access token).</param>
        /// <param name="forcePrompt">If true, the user will be required to confirm authorization even if the requested scopes have already been granted.</param>
        /// <returns>The generated URI.</returns>
        public Uri CreateAuthorizationRequest(Uri redirectUri, AuthorizationScope scope, string state = null, bool offlineAccess = false, bool forcePrompt = false)
        {
            if (redirectUri == null)
            {
                throw new ArgumentNullException(nameof(redirectUri));
            }
            if (scope == AuthorizationScope.None)
            {
                throw new ArgumentException("At least one authorization scope must be selected.", nameof(scope));
            }
            if (this.WebSite == null || this.WebSite.Trim().Length == 0)
            {
                throw new InvalidOperationException("No website has been set.");
            }
            if (this.ClientId == null || this.ClientId.Trim().Length == 0)
            {
                throw new InvalidOperationException("No client ID has been set.");
            }
            var uri   = new UriBuilder(this.UrlScheme, this.WebSite, this.Port, OAuth2.AuthorizationEndPoint);
            var query = new StringBuilder();

            query.Append("response_type=code");
            query.Append("&client_id=").Append(Uri.EscapeDataString(this.ClientId));
            query.Append("&redirect_uri=").Append(Uri.EscapeDataString(redirectUri.ToString()));
            query.Append("&scope=").Append(string.Join("+", OAuth2.ScopeStrings(scope)));
            if (state != null)
            {
                query.Append("&state=").Append(Uri.EscapeDataString(state));
            }
            if (offlineAccess)
            {
                query.Append("&access_type=offline");
            }
            if (forcePrompt)
            {
                query.Append("&approval_prompt=force");
            }
            uri.Query = query.ToString();
            return(uri.Uri);
        }
        public void DefaultAuthorizationTrue()
        {
            var source = new AuthorizationScope
            {
                DefaultAuthorization = true,
                AllowUnauthenticated = true,
                Activities           =
                {
                    new Activity
                    {
                        Default = true,
                        AllowUnauthenticated = true,
                        Resource             = "Home",
                        Action = "Index",
                        Deny   = new Permission
                        {
                            Users  = { "A",     "C" },
                            Claims =
                            {
                                new Claim("team", "E")
                            }
                        },
                        Allow = new Permission
                        {
                            Roles  = { "B" },
                            Claims =
                            {
                                new Claim("team", "F")
                            }
                        }
                    }
                }
            };

            var json = source.ToJson();

            var candidate = json.ToAuthorizations();

            Check(source, candidate);
        }
Example #23
0
        internal static string GetAuthorizationName(this AuthorizationScope scope)
        {
            switch (scope)
            {
            case AuthorizationScope.ReadBasicProfile:
                return("r_basicprofile");

            case AuthorizationScope.ReadFullProfile:
                return("r_fullprofile");

            case AuthorizationScope.ReadEmailAddress:
                return("r_emailaddress");

            case AuthorizationScope.ReadNetwork:
                return("r_network");

            case AuthorizationScope.ReadContactInfo:
                return("r_contactinfo");

            case AuthorizationScope.ReadWriteNetworkUpdates:
                return("rw_nus");

            case AuthorizationScope.ReadWriteCompanyPage:
                return("rw_company_admin");

            case AuthorizationScope.ReadWriteGroups:
                return("rw_groups");

            case AuthorizationScope.WriteMessages:
                return("w_messages");

            case AuthorizationScope.WriteShare:
                return("w_share");

            default:
                throw new NotSupportedException("Scope of value '" + scope.ToString() + " is not supported");
            }
        }
Example #24
0
        private static string GetScopeString(AuthorizationScope scope)
        {
            switch (scope)
            {
            case AuthorizationScope.Bot:
                return("bot");

            case AuthorizationScope.Chat_Write:
                return("chat.write");

            case AuthorizationScope.Friends_Read:
                return("friends.read");

            case AuthorizationScope.Identify:
                return("identify");

            case AuthorizationScope.Public:
                return("public");

            default:
                throw new ArgumentOutOfRangeException(nameof(scope), scope, null);
            }
        }
Example #25
0
        /*
         *  signup or signin with nonce.
         *  nonce is the parameter which help more accurate validation of idToken on your application server.
         *
         *  recommended way of the SIWA authentication with nonce is below.
         *  1. client gets the nonce from your application server. server should record generated nonce.
         *  2. client should use the nonce to execute SignupOrSignin(nonce, (isSignup, SIWA userInfo) => {do sending idToken and other data to your server}) method.
         *  3. application server receives the idToken included the nonce. do delete record of the nonce and validate idToken with nonce. this way gives you to accurate JWT verification and avoid replay attack.
         */
        public static void SignupOrSignin(string nonce, AuthorizationScope authorizationScope, Action <bool, UserInfo> onSucceeded, Action <string> onFailed)
        {
            switch (state)
            {
            case State.None:
                break;

            default:
                onFailed("another process running. waiting for end of:" + state);
                return;
            }

            state = State.SignUpProcessing;

            signupCompletedCallback = args =>
            {
                state = State.None;


                var userInfo = args.userInfo;;

                // success
                if (string.IsNullOrEmpty(userInfo.error))
                {
                    /*
                     *  success
                     *  {
                     *      "userId": "000692.40362e95611641bbb392d7dddc6b25ca.1447",
                     *      "email": "[email protected]",
                     *      "displayName": "xxxxx",
                     *      "authorizationCode": "c4902247f521c4104ba925bbc17143b8c.0.nwzs.l8YIwin6RbYr9aYGlRMoQg",
                     *      "idToken": "eyJraWQiOiI4NkQ4OEtmIiwiYWxnIjoiUlMyNTYifQ.eyJpc3MiOiJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiYXVkIjoiY29tLmtpYWFraS50ZXN0IiwiZXhwIjoxNTg0MDExMTk1LCJpYXQiOjE1ODQwMTA1OTUsInN1YiI6IjAwMDY5Mi40MDM2MmU5NTYxMTY0MWJiYjM5MmQ3ZGRkYzZiMjVjYS4xNDQ3IiwiY19oYXNoIjoiUms5RHk4aGhvSUhUR2NTWlVjbkFhdyIsImVtYWlsIjoiOHp0OGpteTVieEBwcml2YXRlcmVsYXkuYXBwbGVpZC5jb20iLCJlbWFpbF92ZXJpZmllZCI6InRydWUiLCJpc19wcml2YXRlX2VtYWlsIjoidHJ1ZSIsImF1dGhfdGltZSI6MTU4NDAxMDU5NSwibm9uY2Vfc3VwcG9ydGVkIjp0cnVlfQ.LWDdtt-AS42QbgfO6q2zfe2uJ7rvsQNgUz8phrOO4sltT4fNPMdJDAcdpHj7wuEYUhSoC4lKSTzEyVOSqXzxHNrWah6VEki49vWmNlHObTTdEHyfh6zhjj5Keve5WWO-1s7kmPu6eEFeyz3gAbvRPpck_tTWgx6N6-oijdccTy4jdstAt5mxUtzhT-oPw8LvEC0kLpRhZyOcjfiFsMZ2AFXzkQAbl6JaKdrvSZNcgM-VbzJrfg4b_bS14FAPqKN3ZJ_ksSvyaY3ugI0NBT_rUeINugOoABwk1h1bv7RW4R66Pmg5oAGDH_m3AwKkFkltIbZyAMXsmP3HU6iMr2iquA",
                     *      "error": "",
                     *      "userDetectionStatus": 1
                     *  }
                     */

                    // Debug.Log("data:" + JsonUtility.ToJson(userInfo));

                    var publicUserInfo = new UserInfo(
                        userInfo.authorizationCode,
                        userInfo.userId,
                        userInfo.email,
                        userInfo.displayName,
                        userInfo.idToken,
                        userInfo.userDetectionStatus
                        );

                    // check if requested authorizationScope data is contained or not.
                    // if requested but not contained, the request is not first one.
                    // determine the result as "signin".
                    var isSignin = false;
                    switch (authorizationScope)
                    {
                    case AuthorizationScope.Email:
                        isSignin = string.IsNullOrEmpty(publicUserInfo.email);
                        break;

                    case AuthorizationScope.FullName:
                        isSignin = string.IsNullOrEmpty(publicUserInfo.displayName);
                        break;

                    case AuthorizationScope.EmailAndFullName:
                        isSignin = string.IsNullOrEmpty(publicUserInfo.email) && string.IsNullOrEmpty(publicUserInfo.displayName);
                        break;
                    }

                    if (isSignin)
                    {
                        // signin.
                        onSucceeded(false, publicUserInfo);
                        return;
                    }

                    // signup.
                    onSucceeded(true, publicUserInfo);
                    return;
                }

                /*
                 *  {
                 *      "userInfo": {
                 *          "userId": "",
                 *          "email": "",
                 *          "displayName": "",
                 *          "authorizationCode": "",
                 *          "idToken": "",
                 *          "error": "",
                 *          "userDetectionStatus": 0
                 *      }
                 *      "error": "The operation couldn’t be completed. (com.apple.AuthenticationServices.AuthorizationError error 1001.)"
                 *  }
                 */
                // error
                onFailed(userInfo.error);
            };

#if UNITY_EDITOR
            state = State.None;
            onSucceeded(
                true,
                new UserInfo(
                    "dummy authorizationCode",
                    "dummy userId",
                    "dummy email",
                    "dummy displayName",
                    "dummy idToken",
                    UserDetectionStatus.LikelyReal
                    )
                );
#elif UNITY_IOS
            IntPtr          cback = IntPtr.Zero;
            SignupCompleted d     = SignupCompletedCallback;
            cback = Marshal.GetFunctionPointerForDelegate(d);

            SignInWithApple_Signup(nonce, (int)authorizationScope, cback);
#endif
        }
Example #26
0
        /// <summary>
        /// Gets the authorization URL.
        /// </summary>
        /// <param name="scope">An enum of permissions.</param>
        /// <param name="state">A unique identifier to use as a CSRF check.</param>
        /// <param name="redirectUri">The redirect URI.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">
        /// The value cannot be empty;state
        /// or
        /// The value cannot be empty;redirectUri
        /// </exception>
        public Uri GetAuthorizationUrl(AuthorizationScope scope, string state, string redirectUri)
        {
            if (string.IsNullOrEmpty(state))
                throw new ArgumentException("The value cannot be empty", "state");
            if (string.IsNullOrEmpty(redirectUri))
                throw new ArgumentException("The value cannot be empty", "redirectUri");

            this.CheckConfiguration(apiKey: true);

            var flags = Enum.GetValues(typeof(AuthorizationScope))
                .Cast<AuthorizationScope>()
                .Where(s => (scope & s) == s)
                .Select(s => s.GetAuthorizationName())
                .ToArray();
            var scopeAsString = string.Join(" ", flags);

            var url = string.Format(
                "{0}/uas/oauth2/authorization?response_type=code&client_id={1}&scope={2}&state={3}&redirect_uri={4}",
                this.LinkedInApi.Configuration.BaseOAuthUrl,
                Uri.EscapeDataString(this.LinkedInApi.Configuration.ApiKey),
                Uri.EscapeDataString(scopeAsString),
                Uri.EscapeDataString(state),
                Uri.EscapeDataString(redirectUri));
            return new Uri(url);
        }
Example #27
0
 /// <summary>
 /// Get the api-supported string array of the specified scope option.
 /// </summary>
 /// <param name="scopeOption">Access scope option.</param>
 /// <returns></returns>
 public static string[] GetRequestArray(this AuthorizationScope scopeOption)
 {
     return(scopeOption.HasFlag(AuthorizationScope.All)
         ? AuthDictionary.Select(k => k.Value).ToArray()
         : GetFlags <AuthorizationScope>(scopeOption).Select(scope => AuthDictionary[scope]).ToArray());
 }
Example #28
0
        public async Task <bool> CreateAuthorizationScopeAsync(string realm, string resourceServerId, AuthorizationScope scope)
        {
            var response = await GetBaseUrl(realm)
                           .AppendPathSegment($"/admin/realms/{realm}/clients/{resourceServerId}/authz/resource-server/scope")
                           .PostJsonAsync(scope)
                           .ConfigureAwait(false);

            return(response.IsSuccessStatusCode);
        }
Example #29
0
 /// <summary>
 /// Get the api-supported string array of the specified scope option.
 /// </summary>
 /// <param name="scopeOption">Access scope option.</param>
 /// <returns></returns>
 public static string[] GetRequestArray(this AuthorizationScope scopeOption)
 {
     return(GetFlags(scopeOption).Select(GetScopeString).ToArray());
 }