Nikhil.Patel
Nikhil.Patel

Reputation: 959

Implement OAuth with ASP.NET WebAPI

Hello Friends I would like to ask you that can any one have an example to integrate oAuth in ASP.Net web api with out integrating any packages or Entity framework??i search it a lot but find a various way using nuget packages and other packages but i need the way using simple third party calls because i need this authorization in .net as well as java api's. Can any one help me out in this.

Thanks in advance...

Upvotes: 0

Views: 180

Answers (1)

Mostafa
Mostafa

Reputation: 3302

Yes you can do this, i implemented this in my web api using oAuth in web api 2 project.

First, have an asp.net project with oauth is configured since we will take cooy some files into web api project.

Here is the steps: 1) In the web api, add a new class file called "IdentityConfig.cs".

This class will have: ApplicationUser, ApplicationUserManager, ApplicationSignInManager and ApplicationDbContext classes.

2) Make sure that these classes above is under your api namespace so it is accessible through all your controllers.

// Configure the application user manager which is used in this api.
    public class ApplicationUser : IdentityUser
    {

        #region custom properties

        public string Name { get; set; }
        public int? ZipCode { get; set; }
        public long? CountryId { get; set; }
        public bool IsDeleted { get; set; }
        public bool EmailConfirmed { get; set; }
        public DateTime CreatedDate { get; set; }
        public long UserId { get; set; }

        #endregion

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = true,
                RequireUppercase = false,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            //manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    // Configure the application sign-in manager which is used in this api.
    public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DBCONNECTIONKEY", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }



    }

Note: DBCONNECTIONKEY is the key for the connection string in web.config

3) Add Startup.cs file to the root of your web api. copy the logic from the existing one you have in asp.net. feel free to tweak the configuration context properties as needed in the web api project.

4) Use objects from these classes to sign in users, and manager application user objects as you have in asp.net web app.

That's all :)

Hope this helps.

Upvotes: 1

Related Questions