asp.net-corenext.jsentity-framework-coreasp.net-core-identity

is it possible to use Identity EF Core as login/signup on a REST API using nextjs?


I was wondering is it possible to use Identity Framework from dotnet core as a authentication and authorization for a rest API app.

So I was thinking a Landing page using nextjs then a button for login that redirects you on a dotnet razor pages for you to login or get authenticated and then, redirects you again to nextjs with something like JWT as a payload?

I'm asking this question because I'm not sure where to get this flow for documentation or any examples that I could read.


Solution

  • Yes,since .net 8 Identity provides APIs that handle authentication, authorization, and identity management. you could follow the steps in the document

    If you use AppUser class driven from IdentityUser

    public class AppUser : IdentityUser
    {
      .......
    }
    

    register related services as below:

    var connectionString = builder.Configuration.GetConnectionString("AppDbContextConnection") ?? throw new InvalidOperationException("Connection string 'IdentityForApiContextConnection' not found.");
    
    builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connectionString));
    
    builder.Services.AddIdentityApiEndpoints<AppUser>()
        .AddSignInManager<SignInManager<AppUser>>()
        .AddEntityFrameworkStores<AppDbContext>();
    

    a Landing page using nextjs then a button for login that redirects you on a dotnet razor pages for you to login or get authenticated and then, redirects you again to nextjs with something like JWT as a payload

    After you've register ab account,send a request to /login endpoint as below:

    enter image description here

    You would get token in response directly:

    enter image description here