简体   繁体   中英

Trying so save user data to dbcontext after first signup with Auth0 in asp.net core

What I am trying to achieve: 1. Getting all the claims after OnTicketReceived event from Auth0. 2. Checking if the user is signing up for first time (bool value in 1 of the claims). 3. Saving new user object into localdb (if it's the first time logging in). Currently I am stuck on third step. In order to use OnTicketReceived I need a static method on the right side but then I cannot use DbContext in my controller class because it is not a static variable.

Startup.cs

services.AddAuthentication(options =>
            ...
            .AddOpenIdConnect("Auth0", options =>
            {
                options.Scope.Add("openid");
                ...
                options.Events = new OpenIdConnectEvents
                {
                    OnTicketReceived = UsersController.CreateOnSignUp,
                ...
                };
            });

UsersController.cs

        public static async Task<Task> CreateOnSignUp(TicketReceivedContext ticketReceivedContext)
        {
            List<Claim> claims = ticketReceivedContext.Principal.Claims.ToList();
            var claim = claims.FirstOrDefault(x => x.Type.EndsWith("isNewUser"));
            bool isNewUser = bool.Parse(claim.Value);

            if (isNewUser)
            {
                string userOId = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
                User user = new User() { ExternalId = userOId };
                //insert new value into DB
                //_context.Add(user);
                //await _context.SaveChangesAsync();
            }

            return Task.CompletedTask;
        }

Commented code lines are currently not working. Could anyone recommend a better way of saving user data to DB after authentication or a workaround to my current solution?

First of all, the controllers are instantiated per call (or for each HTTP request). You shouldn't maintain any state by introducing static properties, fields or methods inside the controllers.

In your case, I would create a service class ServiceSignUp that consists of the CreateOnSignUp method.

 public interface IServiceSignUp
 {
    async Task CreateOnSignUp(TicketReceivedContext ticketReceivedContext);
 }

 public class ServiceSignUp : IServiceSignUp
 {
    public async Task CreateOnSignUp(TicketReceivedContext ticketReceivedContext)
    {
       ....
    } 
 }

Then register them with the build-in IoC container like services.AddSingleton<IServiceSignUp, ServiceSignUp>();

In the ConfigureServices() method inside the StartUp class:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IServiceSignUp, ServiceSignUp>();

    services.AddAuthentication(options =>
                ...

            .AddOpenIdConnect("Auth0", options =>
            {
                options.Scope.Add("openid");
                ...
                options.Events = new OpenIdConnectEvents
                {
                    OnTicketReceived += ServiceSignUp.CreateOnSignUp,
                    ...
                };
            });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM