public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var repo = new BaseDataRepository(DataContext.Create());

            ClaimsIdentity oAuthIdentity = await repo.GenerateUserIdentityAsync(user, userManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await repo.GenerateUserIdentityAsync(user, userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Esempio n. 2
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                 externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                var            repo          = new BaseDataRepository(DataContext.Create());
                ClaimsIdentity oAuthIdentity = await repo.GenerateUserIdentityAsync(user, UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await repo.GenerateUserIdentityAsync(user, UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
Esempio n. 3
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            var container = CastleHelper.Container;

            container.Register(
                Component
                .For <IAppBuilder>()
                .Instance(app),
                Component
                .For <IDbContext>()
                .ImplementedBy <DataContext>()
                .DependsOn(Dependency.OnValue <string>("DefaultConnection"))
                .LifestyleTransient(),
                Component
                .For <IUserStore <ApplicationUser, int> >()
                .ImplementedBy <UserStore <ApplicationUser, Role, int, UserLogin, UserRole, UserClaim> >()
                .DependsOn(Dependency.OnComponent <DbContext, DataContext>())
                .LifestyleTransient(),
                Component
                .For <ApplicationUserManager>()
                .UsingFactoryMethod(kernel =>
                                    CreateCustomUserManager(
                                        kernel.Resolve <IUserStore <ApplicationUser, int> >(),
                                        kernel.Resolve <IAppBuilder>()))
                .LifestyleTransient(),
                Component
                .For <IRoleStore <Role, int> >()
                .ImplementedBy <RoleStore <Role, int, UserRole> >()
                .DependsOn(Dependency.OnComponent <DbContext, DataContext>())
                .LifestyleTransient(),
                //Component
                //    .For<ApplicationRoleManager>()
                //    .LifestyleTransient(),
                Component
                .For <IAuthenticationManager>()
                .UsingFactoryMethod(kernel => HttpContext.Current.GetOwinContext().Authentication)
                .LifestyleTransient()
                //Component
                //    .For<ApplicationSignInManager>()
                //    .LifestyleTransient());
                , Component
                .For <IDataSerializer <AuthenticationTicket> >()
                .ImplementedBy <TicketSerializer>()
                , Component
                .For <ISecureDataFormat <AuthenticationTicket> >()
                .ImplementedBy <TicketDataFo‌​rmat>()
                , Component
                .For <IDataProtector>()
                .UsingFactoryMethod(kernel =>
                                    new DpapiDataProtectionProvider().Create("ASP.NET Identity"))

                );


            //     builder.RegisterType<TicketSerializer>()
            //.As<IDataSerializer<AuthenticationTicket>>();
            //     builder.Register(c => new DpapiDataProtectionProvider().Create("ASP.NET Identity"))
            //            .As<IDataProtector>();
            app.CreatePerOwinContext(() => container.Resolve <ApplicationUserManager>());


            // Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(DataContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);


            BaseDataRepository repo = new BaseDataRepository(DataContext.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
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator
                                         .OnValidateIdentity <ApplicationUserManager, ApplicationUser, int>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) =>
                        repo.GenerateUserIdentityAsync(user, manager, DefaultAuthenticationTypes.ApplicationCookie),
                        getUserIdCallback: (id) => (id.GetUserId <int>()))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true,
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // 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(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }