Exemplo n.º 1
0
        public static void UseBasicUserTokenAuthentication(this IAppBuilder app, UserAuthenticationOptions userAuthenticationOptions)
        {
            /* Remove ability to have auth token in URL */
            //app.Use(async (context, next) =>
            //{
            //    if (context.Request.QueryString.HasValue)
            //    {
            //        if (String.IsNullOrWhiteSpace(context.Request.Headers.Get("Authorization")))
            //        {
            //            var queryString = HttpUtility.ParseQueryString(context.Request.QueryString.Value);
            //            string token = queryString.Get("token");

            //            if (!String.IsNullOrWhiteSpace(token))
            //            {
            //                context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
            //            }
            //        }
            //    }

            //    await next.Invoke();
            //});

            var userManager              = new CoreUserManager(userAuthenticationOptions.UserContext, app.GetDataProtectionProvider());
            var accessTokenLifeSpan      = userAuthenticationOptions.AccessTokenExpireTimeSpan;
            var refreshTokenLifeSpan     = userAuthenticationOptions.RefreshTokenExpireTimeSpan;
            var accessControlAllowOrigin = userAuthenticationOptions.AccessControlAllowOrigin;
            var clientId = userAuthenticationOptions.ClientId;

            userManager.PasswordValidator = userAuthenticationOptions.PasswordValidator;

            var OAuthServerOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp           = userAuthenticationOptions.AllowInsecureHttp,
                TokenEndpointPath           = userAuthenticationOptions.TokenEndpointPath,
                AccessTokenExpireTimeSpan   = accessTokenLifeSpan,
                ApplicationCanDisplayErrors = true,
                Provider             = new SimpleAuthorizationServerProvider(userManager, accessControlAllowOrigin, clientId),
                RefreshTokenProvider = new SimpleRefreshTokenProvider(userManager, refreshTokenLifeSpan, accessControlAllowOrigin),
            };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
            {
                AccessTokenProvider = OAuthServerOptions.RefreshTokenProvider,
                AccessTokenFormat   = OAuthServerOptions.AccessTokenFormat
            });

            userManager.UserContext.Initialize();
        }
Exemplo n.º 2
0
        public override void SetupDefaults()
        {
            // This code will create an admin user, user role and add all new menu items to the admin user roles, even if you create new ones later.

            // It is recommended to change your admin email and password asap.


            // Get a UserManager for CustomUser class, this is used to add, find, and work with our custom users.
            var customUserContext      = Container.Resolve <CustomUserContext>();
            var dataProtectionProvider = Container.Resolve <IDataProtectionProvider>();
            var customUserManager      = new CoreUserManager(customUserContext, dataProtectionProvider);

            using (var session = DataService.OpenSession())
            {
                SetupDefaultUsersAndMenus(session);

                // Create a CustomUser if one doesn't exist
                var bob = session.QueryOver <CustomUser>().Where(x => x.Email == "*****@*****.**").SingleOrDefault();
                if (bob == null) // only create this user if it doesn't already exist
                {
                    bob = new CustomUser()
                    {
                        Address        = "The big house in the big street",
                        Age            = 50,
                        Email          = "*****@*****.**",
                        EmailConfirmed = true,                                   // if email is not confirmed, we can't log in, until we confirm the account, but since we're using example.com as the email, we by-pass this.
                    };
                    var result = customUserManager.CreateAsync(bob, "password"); // set password to "password"
                    result.Wait();                                               // this method should be async, but currently it's not. Might fix...

                    if (!result.Result.Succeeded)
                    {
                        throw new Exception("Unable to create custom user: "******"Bob");
                        // you can do something else with this error, log it, etc.
                    }
                }

                session.Flush();
            }
        }
 public SimpleAuthorizationServerProvider(CoreUserManager userManager, string accessControlAllowOrigin, string clientId)
 {
     UserManager = userManager;
     AccessControlAllowOrigin = accessControlAllowOrigin;
     ClientId = clientId;
 }
 public UserProvider(CoreUserManager <TUser> userManager, SignInManager <TUser> signInManager)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
 }
Exemplo n.º 5
0
 public CoreUserController(CoreDbContext ctx, CoreUserManager <U> coreUserManager, ApplicationService app) : base(ctx, app)
 {
     _coreUserManager = coreUserManager;
 }
Exemplo n.º 6
0
 public SimpleRefreshTokenProvider(CoreUserManager userManager, TimeSpan tokenLifeSpan, string accessControlAllowOrigin)
 {
     UserManager              = userManager;
     TokenLifeSpan            = tokenLifeSpan;
     AccessControlAllowOrigin = accessControlAllowOrigin;
 }
Exemplo n.º 7
0
        public async Task <string> SendAcccountFonfirmationEmail(string userId, string userName, string emailAddress, CoreUserManager userManager = null)
        {
            CoreUserManager theUserManager = UserManager;

            if (userManager != null)
            {
                theUserManager = userManager;
            }

            Models.SystemSettings settings;
            using (var session = DataService.OpenSession())
            {
                settings = session.QueryOver <Models.SystemSettings>().SingleOrDefault <Models.SystemSettings>();
            }

            if (settings == null)
            {
                throw new Exception("No system settings have been setup.");
            }

            Logger.Info("Sending account confirmation email to " + emailAddress);

            var emailToken = theUserManager.GenerateEmailConfirmationTokenAsync(userId).Result;

            var myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);

            var body = "Hi " + userName;

            body += "\nWelcome to " + ApplicationSettings.GetApplicationName();

            body += "\n\nPlease click on the following link to activate your account and confirm your email address:\n";

            body += GetCurrentUrl() + "/api/v1/menu/ConfirmEmail?userId=" + userId + "&token=" + HttpUtility.UrlEncode(emailToken);

            var mailMessage = new MailMessage(settings.EmailFromAddress, emailAddress, "Email Confirmation", body);

            var sendEmailTask = Task.Run(() =>
            {
                try
                {
                    var smtpClient = new SmtpClient(settings.EmailHost, settings.EmailPort);

                    var password              = Encryption.Decrypt(settings.EmailPassword, ApplicationSettings.ApplicationPassPhrase);
                    smtpClient.Credentials    = new System.Net.NetworkCredential(settings.EmailUserName, password);
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtpClient.EnableSsl      = settings.EmailEnableSsl;

                    Logger.Info("Sending email...");
                    smtpClient.Send(mailMessage);
                    Logger.Info("Email sent...");
                }
                catch (Exception e)
                {
                    var message = e.Message + "\n" + e.ToString();
                    Console.WriteLine(message);
                    Logger.Error("Error sending email:\n" + message, e);
                    System.Diagnostics.Trace.WriteLine(message);
                    System.Diagnostics.Debug.WriteLine(message);
                    return(message);
                }
                return(String.Empty);
            });

            return(await sendEmailTask);
        }
 public UsersController(CoreDbContext ctx, CoreUserManager <Users> coreUserManager, ApplicationService app) : base(ctx, coreUserManager, app)
 {
 }