|
You can also simply review the services listing to see the name of your SQL Server instance...
Steve Naidamast
Sr. Software Engineer
Black Falcon Software, Inc.
blackfalconsoftware@outlook.com
|
|
|
|
|
Hi,
Can any one please explain this change in "Change Authentication" dialog box. Previously it was easy creating a project with Individual user accounts, but now this is annoying, because I am forced to fill in the options.
Since there is no Image upload option I am typing it out:-
----------------------------------------------------------------
| Change Authentication - Individual User Accounts |
----------------------------------------------------------------
Domain Name
__________________________
Application ID
__________________________
Sign-up or Sign-in Policy
__________________________
What should I do to get past it and still have it create individual user accounts for me. Please point me to any available resources so that I can understand this dialog box and what should be done. I have tried searching but I couldn't find it anywhere.
|
|
|
|
|
I'm having some strange behavior in 2 or my API controller functions, in which I get a status code 401.
So say I delete my authToken in Local Storage, and Login for the first time. A redirect occurs to my "overview" page, in which the "overview" page loads the overview data, called with a client request, and then loads the "performance bar" data that is on every page. These 2 client calls always result in a status 401, unauthorized with a fresh sign in, But if I refresh the page, the 2 client calls work just fine. If I login say an hour later, the automatic login based on token expire data works fine.
What I tried:
I removed the Authorize flags from the 2 API controller functions and it works just fine in all scenarios.
All the other API controllers with the Authorize flag work just fine as well.
So I'm scratching my head on this. I'm thinking it has something to do with roles, in which I added them about 2 months ago. I was careful in how I programed the roles into the AuthToken, having 3 roles to enhance security.
I was also thinking that perhaps the localStorage of the token is lazy, and that the token is not present when the client call is made. But I did research on the internet and all says no, not the case.
I wonder if I can modify the client header to do a retry.
Startup to declare roles
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
auth.AddPolicy("RequireAdminOnly", policy =>
policy.RequireRole("Administrator"));
auth.AddPolicy("RequireAccountOnly", policy =>
policy.RequireRole("Customer"));
auth.AddPolicy("RequireEitherOnly", policy =>
policy.RequireRole("Administrator, Customer"));
});
Token Generation from my .Net Core Auth Service
var claims = new List<Claim>
{
new Claim("userID", wsUser.Id),
new Claim("userName", wsUser.AccountName),
new Claim("role", wsUser.Role ?? "Administrator"),
new Claim(ClaimTypes.Name, wsUser.FirstName),
new Claim(ClaimTypes.Email, wsUser.EmailAddress)
};
API Controller Function
[HttpGet("GetOverview"), Authorize(Policy = "RequireAdminOnly")]
public async Task<GetOverview> GetOverview()
{
return await _overviewRepository.GetOverview();
}
Client Header that is being sent
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + getAuthToken
})
};
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Looks like I have to write my own custom middleware to read the header, for the token and process it.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Well after another failed day to figure it out ...
What I did learn is that there are new methods in .Net Core 3.1 to validate views or razor pages, and new methods to validate a client API call from say Angular or React. Looks like the latter requires a new package called Microsoft.AspNetCore.ApiAuthorization.IdentityServer
So basically using a straight Autorize Attribute doesn't understand how to read the JWT token and authenticate it, thus me thinking that the token wasn't read fast enough for the API controller action to pickup. And then toss the Roles and Policies out the window because the token is not even read.
Now that I have to write an identity server, basically redesign and rewrite my entire Auth system. Like rethink the entire thing and implement it again. What a pain in the as.. But I guess I'll get a better app in the long run. I wasn't that happy with my current Auth system anyways, and those little glitches shows that it was poorly designed anyways.
Now I'm wondering if I should just shoot straight to .Net Core 5, so I can avoid another rewrite of my app's back end and configuration. The downside seems to be the lack of examples, or a clutter of examples that are outdated and pollute the internet. Feels like going through a pile of trash and cherry picking what I need.
Side Note:
I need roles or policies so I can store a single token, that can work on both the customer side and back end, without having several different Auth systems.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
After looking at hundreds of examples and tutorials on the subject, most tutorials where repeats of the age 21
I rewrote the way my app auths using JWT. Wasn't really a complete rewrite but rewritten anyways.
Finally got it to Authorize on a plain Authorize attribute. I got the error that the token needs 3 or 5 parts and that opened my eyes up to what the ValidIssuer and ValidAudience is, An account at Auth0 in which you use a third party Authority to generate extra secure parts of the JWT token. I suspect that the people that wrote the tutorials earlier never really explained what this does, and that my upgrade to.Net Core 3.1 simply exposed my security flaws.
The other confusion was that 3/4 of the tutorials were for authenticating razor pages and not api calls.
So I went from status 401 to 403, to 3 or 5 parts needed.
I'll turn off ValidateIssuer , ValidateAudience , ValidateIssuerSigningKey and ValidateLifetime and work on Roles and Policies.
So I'm back to not authenticating after login again, but I think I know why now. Might have something to do with cookie authentication. I must have some View and Razor stuff mixed in wrong. Or it's not aware of falling back to Bearer after login.
Something like that.
I'll sign up for a personal Auth0 account and program the authority later this week.
The Authorize attribute works, just didn't have a way to see the errors.
I have new authentication schemes now, injected into services
services.AddAuthorization(auth =>
{
auth.AddPolicy(AuthPolicies.Admin, AuthPolicies.AdminPolicy());
auth.AddPolicy(AuthPolicies.Account, AuthPolicies.AccountPolicy());
});
And a new AddAuthentication
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerJwt()
.AddCookie(option => option.SlidingExpiration = true)<br />
.AddGoogle(CertificateAuthenticationDefaults.AuthenticationScheme, option =>
{
var googleAuthNSection = Config.GetSection("Authentication:Google");<br />
option.ClientId = googleAuthNSection["ClientId"];
option.ClientSecret = googleAuthNSection["ClientSecret"];
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
var settings = Config.GetSection("Settings");
var secretKey = settings.GetValue<string>("Auth0:Secret");
var authority = settings.GetValue<string>("Auth0:Authority");
var audience = settings.GetValue<string>("Auth0:Audience");
var issuer = settings.GetValue<string>("Auth0:Issuer");
var expiresDays = settings.GetValue<int>("Auth0:ExpireDays");
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
options.Audience = audience;
options.Authority = authority;<br />
options.SaveToken = false;
options.RequireHttpsMetadata = false;
options.Configuration = new OpenIdConnectConfiguration();<br />
options.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.FromMinutes(0),
ValidateIssuerSigningKey = false,
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false,
ValidIssuer = issuer,
ValidAudience = audience,<br />
IssuerSigningKey = signingKey
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
services.AddCors();
});
New Auth Polices with authentication schemes added, and more roles.
I'll test this later tonight to see if it works now.
public class AuthPolicies
{
public const string Admin = "Admin";
public const string Account = "Account";
public static AuthorizationPolicy AdminPolicy()
{
return new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Cookies", "Bearer")
.RequireAuthenticatedUser()
.RequireRole(Admin)
.RequireClaim("jti", "sub", "unique_name", "role", "idpId")<br />
.Build();
}
public static AuthorizationPolicy AccountPolicy()
{
return new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Cookies", "Bearer")
.RequireAuthenticatedUser()
.RequireRole(Account)
.RequireClaim("jti", "sub", "unique_name", "role", "idpId")<br />
.Build();
}
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Got it to work by accident.
I figured out the JWT Token 3 segment 5 segment issue after reading tons of material. That was an issue with a null token value being passed by Angular V7. The answer was to change the key from "authToken" to just "Token" in localStorage. Go Figure.
I didn't fixed the SignIn, it still fails after redirect to the overview page. But at least I know that it's the client side passing a null token.
Got my Authentication schemes straightened out. So now I'm just down to the policies.
This works ...
I went through each claim one at a time, and only the jti works, in which jti has to be a unique GUID value. Well that is not proven yet.
public static AuthorizationPolicy AdminPolicy()
{
return new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Bearer")
.RequireAuthenticatedUser()
.RequireRole(Admin)
.RequireClaim("jti")
.Build();
}
This doesn't work ... Trying to add all the claims compiles, but doesn't authenticate.
Of course I need to test a token from the another role to validate that it really works.
public static AuthorizationPolicy AccountPolicy()
{
return new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("Bearer")
.RequireAuthenticatedUser()
.RequireRole(Account)
.RequireClaim("jti", "sub", "unique_name", "role", "bsonId", "idpId")
.Build();
}
What is interesting is that I read that "Roles" will no longer be supported, and that "Claims" will replace it. Of course you can place a "Role" inside a "Claim".
Now to test the policies with other account tokens.
What sucks is that so many people copied the same examples of how it works and claimed them as their own writings polluting the internet with trash on the subject. And the pollution of so many examples and descriptions of every .Net Core Version makes it confusing as well. And then add Views, Context, Razor, Blazer, API into the mix, plus Azure support as well. Then Auth0 vs OpenIdConnect, and trying to build Authorization that works for all in Startup, plus your policies.
But overall in the end so far, what I thought was going to be a huge Authorization build just ended up being a cleanup and rework of my current design.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
modified 23-Jul-20 16:50pm.
|
|
|
|
|
So there was really nothing wrong with my code, or my design. It wasn't like a block of code was going to fix everything.
I have everything working now, except for new ideas such as a 15 minute token expiration that just keeps refreshing. So I need to read up on how to refresh tokens, but I've made preparation for it in my token claims and storage system.
What it boils down to is that I took a simple example of how to integrate Angular V5 with .Net Core 2.0 designed like learning how to walk and modified it to be like Amazon and it crashed. I tried to take a simple example of authenticating a user and took it to handle multiple authenticated user roles with multiple systems such as Google SignIn, Admin SignIn, Customer SignIn.
I can now see the progress made on .Net Core 3.2, in which what I wanted to do with .Net Core 2.2 has been realized. I remember Asp.Net Microsoft.Identity and how it was this huge Auth system with all the bells and whistles, but you had to use it there way or no way. So I created a hack of it in a smaller package size. With .Net Core 3.2, it's alacarte now, and I can choose the components I want to use to create my Auth system, very nice. I can package anything I want inside the Jwt Token and use it to also hold info like the user name, email address without having to go to the database to get it.
Basically .Net Core and Angular has really matured and seems to be spot on now in terms of building a huge web app that is fast, reliable and durable. So I'm not going to post any code or lead anyone down the rabbit hole here. My issue simply just needed a complete rethink of what I had already implemented and just do a complete fresh redesign of my Auth system.
Frustrated at first and didn't want to change, very happy today and embraced the new changes.
I feel very confident that I have a great Auth system now that is very secure.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Was forced to upgrade yesterday. Went to publish a Docker Container and the 2.2 images were no longer available.
So I made it through the code changes; well at least I think I did, but can't run my web app because of the SSL error.
I get the SSL connection not trusted error on both Firefox and Chrome. No option to ignore and accept the risk. Says my certificate is totally unsafe.
Changed the project file to 3.1, upgraded NuGet packages.
I tried IIS Crypto and set back to preferred.
Did the Dotnet https clean and trust
Installed Win64 OpenSSL to look at my localhost.pfx but can't really figure out how to use the program.
I realize now that my startup.cs only loads Kestrel for running in a Docker container so my pfx files are not the issue.
Ruled out HTTP1 or HTTP2
Issue two, finding the right Docker image to use in the container.
I was using ...
FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base
FROM microsoft/dotnet:2.2-sdk AS build
Tried just changing the version number to 3.1, didn't work.
Yesterday just from about 15mins of research, I changed to
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
But the build bombs; Can't remember why, I'll build it again.
Fallback package Xamarin, That gives me something to go on ...
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: The "ResolvePackageAssets" task failed unexpectedly. [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: NuGet.Packaging.Core.PackagingException: Unable to find fallback package folder 'C:\Microsoft\Xamarin\NuGet\'. [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at NuGet.Packaging.FallbackPackagePathResolver..ctor(String userPackageFolder, IEnumerable
1 fallbackPackageFolders) [/src/jkirkerx/jkirkerx.csproj]<br />
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.NuGetPackageResolver.CreateResolver(IEnumerable 1 packageFolders) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.NuGetPackageResolver.CreateResolver(LockFile lockFile) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheWriter..ctor(ResolvePackageAssets task) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader.CreateReaderFromDisk(ResolvePackageAssets task, Byte[] settingsHash) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader..ctor(ResolvePackageAssets task) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ReadItemGroups() [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ExecuteCore() [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.TaskBase.Execute() [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute() [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask) [/src/jkirkerx/jkirkerx.csproj]
1>Build FAILED.
1>
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: The "ResolvePackageAssets" task failed unexpectedly. [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: NuGet.Packaging.Core.PackagingException: Unable to find fallback package folder 'C:\Microsoft\Xamarin\NuGet\'. [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at NuGet.Packaging.FallbackPackagePathResolver..ctor(String userPackageFolder, IEnumerable
1 fallbackPackageFolders) [/src/jkirkerx/jkirkerx.csproj]<br />
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.NuGetPackageResolver.CreateResolver(IEnumerable 1 packageFolders) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.NuGetPackageResolver.CreateResolver(LockFile lockFile) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheWriter..ctor(ResolvePackageAssets task) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader.CreateReaderFromDisk(ResolvePackageAssets task, Byte[] settingsHash) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader..ctor(ResolvePackageAssets task) [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ReadItemGroups() [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ExecuteCore() [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.NET.Build.Tasks.TaskBase.Execute() [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute() [/src/jkirkerx/jkirkerx.csproj]
1>/usr/share/dotnet/sdk/3.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(234,5): error MSB4018: at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask) [/src/jkirkerx/jkirkerx.csproj]
1> 0 Warning(s)
1> 1 Error(s)
1>
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Its my computer.
the browsers keep picking up an expired certificate when I run VS 2017 and 2019
I updated my localhost.pfx in my project that I use with Kestrel in a docker container.
Oh it's been years since I had to deal with this. Just happy coding.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
got it to work finally
I added this to appSettings.json
So now it uses the new pfx file that is not expired.
I still wonder where the other file was coming from, perhaps somewhere in app data.
And I didn't really program Kestrel to run in debug under the project name. Just for running in a Docker container.
hmm....
"Kestrel": {
"Certificates": {
"Default": {
"Path": "localhost.pfx",
"Password": ""
}
}
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Now the Docker container builds, didn't have to change the images
Had to do some adjustments on the startup.cs, and move some things around.
So far so good.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Good evening everyone, I want to know the best way to generate unique user ID even when number of registered users are more than two million.
The current way am using to achieve this is by initiating an ID i.e 2083928937 for instance, then checking Database if this ID exists. If it does, then I will increment it by 1 then make a search again for the incremented value until no match is found and the unfound ID will be used.
But am having the feeling that this will cause database issue or even slow down the site as the code have to iterate several times when the site start to have more users.
So, please what is the best way to achieve this?
www.emmason247.com.ng
|
|
|
|
|
Use a Guid / UUID. That way, you'll also mitigate any IDOR[^] issues at the same time.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Ok thanks. But is the method am using a good technique?
www.emmason247.com.ng
|
|
|
|
|
It depends on how you're generating the initial ID to check.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
No it is not a good method. You could take advantage of the identity/autoincrement field in the database or use the GUID/UUID method recommended.
Currently you create the ID and then check the DB, the above methods would eliminate the check requirement. You should also have a unique index on the id field in the database.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
Consider implementing a Sequence table like:
SequenceName, NextID
The table will consist of a single row such as UserID, 2083928937
This way you immediately know what the next UserID is.
Within a transaction, create the User, then update the sequence table by 1.
|
|
|
|
|
I up vote this method
I do it this way, in which I generate order numbers, where I have a sequence table.
In MongoDB, it can generate a unique Id, based on the server, date and time which is pretty cool.
In the past, I used SQL servers Unique ID with auto increments, but that backfired on me several times.
I forget, but auto increment forgot the last number it was on and added a 1000 to the next number.
I suppose if there was a GUID generator app that worked like Mongo's ObjectId, I would move towards that.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Sorry, but I downvoted this - for a number of reasons:
* It requires an additional two physical i/o calls - to get the latest value, and to update it afterwards
* It requires that you have a READ lock on the sequence table; to avoid duplicates, you must read the value, insert the new record, and update it all within a transaction and without allowing any other process to read the value. At best this requires an additional lock, but at worst - if poorly coded - can leave that lock in place for a prolonged period and cause a major performance bottleneck
* It creates sequential user ids; presumably you have secure password / two-factor authentication, but by using sequential numeric ids you're making it very easy for hackers as they can just generate sequential hacks on the id
If sequential IDs isn't an issue (and it may not be in all cases) the simplest thing is to use an auto-increment field and return the new ID from the insert statement. Any decent DBMS will keep track without issue. In the event of a transaction rollback there may be a "missing" ID but that shouldn't (be allowed) to cause your application a problem.
A method I use when generating IDs is to use a GUID value (or sometimes a truncated portion of a GUID) and simply INSERT into the table. With a unique key on the ID, then in the vanishingly small likelihood of a duplicate, the INSERT will fail. Catch the "duplicate record" exception, replace the ID with a new GUID and insert again. The performance hit from that is miniscule as it will probably never ever happen.
|
|
|
|
|
Message Removed
modified 16-Jul-20 8:55am.
|
|
|
|
|
Message Removed
modified 16-Jul-20 8:55am.
|
|
|
|
|
Server Error in '/' Application.
Runtime Error
Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.
|
|
|
|
|
If you want help then you need to provide proper detailed information. No one here can guess what your code is doing.
|
|
|
|
|
Richard MacCutchan wrote: No one here can guess what your code is doing. To be fair, I could guess.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|