locked
Problem implementing Admin Panel Login in user interface of Web API MVC 5 RRS feed

  • Question

  • User628531343 posted

    Hello All,

    I need some help regarding an issue I am facing in Web API. Tried many solutions but no luck.

    I am using two type of authentication in my web API, first is OAuth - to generate tokens for my web api and manage ClaimsIdentity.

    Secondly I am using SignInManager for UI login - admin panel.

    API token authentication (OAuth) is working fine. But SignInManager is not working properly. It is returning success at login, returning I identity User only at the time of GenerateUserIdentityAsync. After that UserIdentity is always null.

     public class ApplicationUser : IdentityUser<UserLoginIntPk, UserRoleIntPk, UserClaimIntPk>
        {
            public virtual UserProfile UserProfile { get; set; }
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
            {
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); //returns user here
                return userIdentity;
            }
    
            public static implicit operator ApplicationUser(IdentityResult v)
            {
                throw new NotImplementedException();
            }
        }

    Returns success but identity user is null here

    [System.Web.Mvc.HttpPost]
    [ValidateAntiForgeryToken]
    [Layout("_Layout")]
    public async Task<ActionResult> Login(Models.LoginModel model, string returnUrl)
    {
       var result = await SignInManager.PasswordSignInAsync(model.Mobile, model.Password, false, shouldLockout: false); //sign in state is Success here
       ----------------
    }

    OAuth is using ExternalLoginCookie

    SignInManager is using ApplicationCookie

    I am not able to track the mistake. Please guide.

    Wednesday, April 19, 2017 5:28 AM

All replies

  • User-2057865890 posted

    Hi nmathur,

    OAuth is using ExternalLoginCookie

    SignInManager is using ApplicationCookie

    I am not able to track the mistake. Please guide.

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); //returns user here
        return userIdentity;
    }
    

    Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType. You could refer https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on.

    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    
        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    
        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");
    
        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");
    
        //app.UseFacebookAuthentication(
        //   appId: "",
        //   appSecret: "");
    
        //app.UseGoogleAuthentication(
        //   clientId: "",
        //   clientSecret: "");
    }

    Best Regards,

    Chris

    Thursday, April 20, 2017 9:00 AM
  • User628531343 posted

    Hi there,

    Thanks for reply.

    OAuth, which is I am using for API refresh token (for API request) is using ExternalLoginCookie. And for UI I am using SignInManager which is using ApplicationCookie.

    Sorry that I was not so clear. Here I am sharing code from StartUp.Auth.cs file

     public void ConfigureAuth(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
    
            //the one for API token
          
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            
            app.UseOAuthAuthorizationServer(AuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
    
    
            //The one for API User Interface
            DataProtectionProvider = app.GetDataProtectionProvider();        
            app.CreatePerOwinContext(MyDataBaseContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
                        validateInterval: TimeSpan.FromHours(8),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                                 getUserIdCallback: (claim) => int.Parse(claim.GetUserId()))
                }
            });
    
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
            
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
    
            AreaRegistration.RegisterAllAreas();
            System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
    
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            BinderConfig.RegisterBinders(ModelBinders.Binders, ModelBinderProviders.BinderProviders);
            WebApiConfig.Register(config);
                  
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
    
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDataBaseContext, MyDataBase.Migrations.Configuration>());        
        }

    Also sharing original code for "GenerateUserIdentityAsync", previous was dummy

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
            {
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                return userIdentity;
            }

    May be it will help you to trigger my mistake.

    Friday, April 21, 2017 5:23 AM