Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error after adding authentication #1102

Closed
sojan1 opened this issue Sep 13, 2023 · 12 comments
Closed

Error after adding authentication #1102

sojan1 opened this issue Sep 13, 2023 · 12 comments

Comments

@sojan1
Copy link

sojan1 commented Sep 13, 2023

Hi
It fails after sync reaches 100% and it says UNIQUE constraint failed Is this related to #974 , #907?

I am using the sample application (HelloWebAuthSync).
Hub Database - SQL Server
Client Database -SQLite
i tried from both console application and MAUI. it both shows the same error.

Authentication works well, as i tested it by giving a 'key' different from that of server. and it responds 'unauthorised'
i have also tried [AllowAnonymous] on server still the error is the same.

Error: Dotmim.Sync.SyncException: '[InternalSaveScopeInfoClientAsync]..SQLite Error 19: UNIQUE constraint failed: scope_info_client.sync_scope_id, scope_info_client.sync_scope_name, scope_info_client.sync_scope_hash'.'

Same scope 'v0' synchronizes through a different port (81) [ Sample WebApi with NoAuth under MAUI folder].
image

image

Client
private static async Task SynchronizeAsync()
{
string clientConnectionString = $"Data Source=C:\Users\sojan.GEROC\Documents\Projects\Dotmim.Sync-master\Samples\HelloWebAuthSync\HelloWebAuthSyncClient\CoreDatabase.db";

        var token = GenerateJwtToken("spertus@microsoft.com", "SPERTUS01");
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var serverOrchestrator = new WebRemoteOrchestrator("http://192.168.1.77:82/api/sync", client: httpClient);
        var clientProvider = new SqliteSyncProvider(clientConnectionString);

        // Set the web server Options
        var options = new SyncOptions
        {
            BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDirectory(), "client")
        };
        //options.TransactionMode = TransactionMode.AllOrNothing;
        var agent = new SyncAgent(clientProvider, serverOrchestrator, options);


        var progress = new SynchronousProgress<ProgressArgs>(
              pa => Console.WriteLine($"{pa.ProgressPercentage:p}\t {pa.Message}"));

        var parameters2 = new SyncParameters
            {
                { "CLNT_ID","D1" },
                { "PROJ_ID","MASTER" }
            };


        var s1 = await agent.SynchronizeAsync("v0", SyncType.Normal, parameters2, progress);
        Console.WriteLine(s1);

        Console.WriteLine("End");
    }

Server

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddDistributedMemoryCache();
        services.AddSession(options => options.IdleTimeout = TimeSpan.FromMinutes(30));

        
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidIssuer = "Dotmim.Sync.Bearer",
                        ValidAudience = "Dotmim.Sync.Bearer",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SOME_RANDOM_KEY_DO_NOT_SHARE"))
                    };

                    options.Events = new JwtBearerEvents
                    {
                        OnAuthenticationFailed = context =>
                        {
                            Debug.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                            return Task.CompletedTask;
                        },
                        OnTokenValidated = context =>
                        {
                            Debug.WriteLine("OnTokenValidated: " + context.SecurityToken);
                            return Task.CompletedTask;
                        }
                    };
                });
        var connectionString = Configuration.GetSection("ConnectionStrings")["SqlConnection"];
        var scopeName =  Configuration.GetSection("Scope")["ScopeName"];

        // Set the web server Options
        var options = new SyncOptions
        {
            BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDirectory(), "server")
        };
        var setup = new SyncSetup();
        services.AddSyncServer<SqlSyncChangeTrackingProvider>(connectionString, setup, null, null, scopeName);
    }
@sojan1 sojan1 changed the title getting an error after adding authentication Error after adding authentication Sep 13, 2023
@sojan1
Copy link
Author

sojan1 commented Sep 13, 2023

@Mimetis any idea what the error is?

Sample app with No Authentication - It works perfectly with the same database that is provisioned with no authentication.
Sample app with Authentication - i can see that the client's provisioning tables getting synchronized, but data is not synced.

With authentication
image

Without authentication
image

@Mimetis
Copy link
Owner

Mimetis commented Sep 14, 2023

No Idea
Best solution is to create a sample reproduction solution, that I can use to debug

@sojan1
Copy link
Author

sojan1 commented Sep 19, 2023

Hi @Mimetis
Please see the attached.

[HelloWebAuthSyncClient.zip]
[HelloWebAuthSyncServer.zip]
[Other Files.zip]

@Mimetis
Copy link
Owner

Mimetis commented Sep 20, 2023

plz create a github repository

@sojan1
Copy link
Author

sojan1 commented Sep 20, 2023

Hi @Mimetis

github.com/sojan1/Dotmim.Sync.Samples

@Mimetis
Copy link
Owner

Mimetis commented Sep 20, 2023

Please create a repository with your sample only.
What should I do with a repository with ALL THE DMS SAMPLES ?

@sojan1
Copy link
Author

sojan1 commented Sep 21, 2023

Hi

i have removed all other samples and uploaded again
github.com/sojan1/Dotmim.Sync.Samples1

@Mimetis
Copy link
Owner

Mimetis commented Sep 21, 2023

link is not working
last link still the same

@sojan1
Copy link
Author

sojan1 commented Sep 23, 2023

i am so sorry for that.
The repository was defaulted to private when uploaded from Visual Studio
i have tested the latest version and have also confirmed that it is a public

https://github.com/sojan1/Dotmim.Sync.Samples2

@sojan1
Copy link
Author

sojan1 commented Sep 26, 2023

@Mimetis , Hi, have you had a chance to see the error?

@Mimetis
Copy link
Owner

Mimetis commented Oct 2, 2023

In the sample you provided, you forgot to add tables to your SyncSetup instance:

// [Required]: Get a connection string to your server data source
var connectionString = Configuration.GetSection("ConnectionStrings")["SqlConnection"];

// Set the web server Options
var options = new SyncOptions
{
    BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDirectory(), "server")
};

// ADD TABLES !!!!!!!!!!!!!!!!!!!!
var setup = new SyncSetup();
// ADD


var provider = new SqlSyncChangeTrackingProvider(connectionString);


services.AddSyncServer(provider, setup, options, null);

Before testing, be sure you are using a fresh server / client database
My advice, for any test, be sure you have provision correctly your database.

Last thing, your sample is not running correctly and is not raising the issue you are mentionning.
Please do the effort to provider a clean sample I can use to reproduce your error, otherwise I will not be able to help you.

@sojan1
Copy link
Author

sojan1 commented Oct 3, 2023

provisioning is already done for the database. So should i again have the tables added in the SyncSetup().
i am already synching the other examples with the hub using the same code above.

@Mimetis Mimetis closed this as completed Oct 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants