locked
How to use AspNet.Identity.MySQL. (Web forms - VB.net) RRS feed

  • Question

  • User1567609808 posted

    After changing

    Imports Microsoft.AspNet.Identity.EntityFramework

    to

    Imports AspNet.Identity.MySQL

    this class no longer works.

    #Region "Helpers"
    Public Class UserManager
    Inherits UserManager(Of ApplicationUser)
    Public Sub New()
        MyBase.New(New UserStore(Of ApplicationUser)(New ApplicationDbContext()))
    End Sub
    End Class

    How can I fix this problem?

    Thank you.

    Saturday, June 16, 2018 6:25 AM

Answers

  • User283571144 posted

    Hi VB_Blue,

    According to your pervious thread, I found the AspNet.Identity.MySQL library should be downloaded from the AspNet.Identity.MySQL (CodePlex).

    But this link dodesn't contains the url to download the AspNet.Identity.MySQL library.

    I guess you don't  add the AspNet.Identity.MySQL library in your solution, so you couldn't use the mysql as the dbcontext.

    Here is a workaround.

    If you want to use mysql as the database for identity, I suggest you try to use the MySql.AspNet.Identity libarary.

    Notice: By using this library, you will need to execute create script on your MySQL database which will create the tables required for the ASP.NET Identity provider.

    More details about how to use this library work well with mysql and vb, you could refer to below steps:

    1.Create a new ASP.NET MVC 5 project, choosing the Individual User Accounts authentication type.Remove the Entity Framework packages and replace with MySql.AspNet.Identity.

    Uninstall-Package Microsoft.AspNet.Identity.EntityFramework
    Uninstall-Package EntityFramework
    Install-Package MySql.AspNet.Identity
     Install NuGet Package called MySql.AspNet.Identity
    

    2.Modify the IdentityModels.vb as below:

    Imports System.Security.Claims
    Imports System.Threading.Tasks
    Imports Microsoft.AspNet.Identity
    Imports Microsoft.AspNet.Identity.Owin
    Imports MySql.AspNet.Identity
    
    ' You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    Public Class ApplicationUser
        Inherits IdentityUser
        Public Async Function GenerateUserIdentityAsync(manager As UserManager(Of ApplicationUser)) As Task(Of ClaimsIdentity)
            ' Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            Dim userIdentity = Await manager.CreateIdentityAsync(Me, DefaultAuthenticationTypes.ApplicationCookie)
            ' Add custom user claims here
            Return userIdentity
        End Function
    End Class
    
    'Public Class ApplicationDbContext
    '    Inherits IdentityDbContext(Of ApplicationUser)
    '    Public Sub New()
    '        MyBase.New("DefaultConnection", throwIfV1Schema:=False)
    '    End Sub
    
    '    Public Shared Function Create() As ApplicationDbContext
    '        Return New ApplicationDbContext()
    '    End Function
    'End Class
    

    3.In ~/App_Start/Startup.Auth.cs file, remove app.CreatePerOwinContext(ApplicationDbContext.Create);

    Like this:

    Imports Microsoft.AspNet.Identity
    Imports Microsoft.AspNet.Identity.Owin
    Imports Microsoft.Owin
    Imports Microsoft.Owin.Security.Cookies
    Imports Microsoft.Owin.Security.Google
    Imports Owin
    
    Partial Public Class Startup
        ' For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        Public Sub ConfigureAuth(app As IAppBuilder)
            ' Configure the db context, user manager and signin manager to use a single instance per request
            'app.CreatePerOwinContext(AddressOf ApplicationDbContext.Create)
            app.CreatePerOwinContext(Of ApplicationUserManager)(AddressOf ApplicationUserManager.Create)
            app.CreatePerOwinContext(Of ApplicationSignInManager)(AddressOf ApplicationSignInManager.Create)
    
            ' Enable the application to use a cookie to store information for the signed in user
            ' and to use a cookie to temporarily store inforation about a user logging in with a third party login provider
            ' Configure the sign in cookie
            ' OnValidateIdentity enables the application to validate the security stamp when the user logs in.
            ' This is a security feature which is used when you change a password or add an external login to your account.
            app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
                .AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                .Provider = New CookieAuthenticationProvider() With {
                    .OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(Of ApplicationUserManager, ApplicationUser)(
                        validateInterval:=TimeSpan.FromMinutes(30),
                        regenerateIdentity:=Function(manager, user) user.GenerateUserIdentityAsync(manager))},
                .LoginPath = New PathString("/Account/Login")})
    
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie)
    
            ' Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5))
    
            ' Enables the application to remember the second login verification factor such as phone or email.
            ' Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            ' This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie)
    
            ' 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() With {
            '   .ClientId = "",
            '   .ClientSecret = ""})
        End Sub
    End Class
    

    4.Modify the ~/App_Start/IdentityConfig.cs as below:

    Imports System.Threading.Tasks
    Imports System.Security.Claims
    Imports Microsoft.AspNet.Identity
    Imports Microsoft.AspNet.Identity.EntityFramework
    Imports Microsoft.AspNet.Identity.Owin
    Imports Microsoft.Owin
    Imports Microsoft.Owin.Security
    Imports MySql.AspNet.Identity
    
    Public Class EmailService
        Implements IIdentityMessageService
    
        Public Function SendAsync(message As IdentityMessage) As Task Implements IIdentityMessageService.SendAsync
            ' Plug in your email service here to send an email.
            Return Task.FromResult(0)
        End Function
    End Class
    
    Public Class SmsService
        Implements IIdentityMessageService
    
        Public Function SendAsync(message As IdentityMessage) As Task Implements IIdentityMessageService.SendAsync
            ' Plug in your SMS service here to send a text message.
            Return Task.FromResult(0)
        End Function
    End Class
    
    ' Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    Public Class ApplicationUserManager
        Inherits UserManager(Of ApplicationUser)
    
        Public Sub New(store As IUserStore(Of ApplicationUser))
            MyBase.New(store)
        End Sub
    
        Public Shared Function Create(options As IdentityFactoryOptions(Of ApplicationUserManager), context As IOwinContext) As ApplicationUserManager
            Dim manager = New ApplicationUserManager(New MySqlUserStore(Of ApplicationUser))
    
            ' Configure validation logic for usernames
            manager.UserValidator = New UserValidator(Of ApplicationUser)(manager) With {
                .AllowOnlyAlphanumericUserNames = False,
                .RequireUniqueEmail = True
            }
    
            ' Configure validation logic for passwords
            manager.PasswordValidator = New PasswordValidator With {
                .RequiredLength = 6,
                .RequireNonLetterOrDigit = True,
                .RequireDigit = True,
                .RequireLowercase = True,
                .RequireUppercase = True
            }
    
            ' 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(Of ApplicationUser) With {
                                              .MessageFormat = "Your security code is {0}"
                                          })
            manager.RegisterTwoFactorProvider("Email Code", New EmailTokenProvider(Of ApplicationUser) With {
                                              .Subject = "Security Code",
                                              .BodyFormat = "Your security code is {0}"
                                              })
            manager.EmailService = New EmailService()
            manager.SmsService = New SmsService()
            Dim dataProtectionProvider = options.DataProtectionProvider
            If (dataProtectionProvider IsNot Nothing) Then
                manager.UserTokenProvider = New DataProtectorTokenProvider(Of ApplicationUser)(dataProtectionProvider.Create("ASP.NET Identity"))
            End If
    
            Return manager
        End Function
    
    End Class
    
    ' Configure the application sign-in manager which is used in this application.
    Public Class ApplicationSignInManager
        Inherits SignInManager(Of ApplicationUser, String)
        Public Sub New(userManager As ApplicationUserManager, authenticationManager As IAuthenticationManager)
            MyBase.New(userManager, authenticationManager)
        End Sub
    
        Public Overrides Function CreateUserIdentityAsync(user As ApplicationUser) As Task(Of ClaimsIdentity)
            Return user.GenerateUserIdentityAsync(DirectCast(UserManager, ApplicationUserManager))
        End Function
    
        Public Shared Function Create(options As IdentityFactoryOptions(Of ApplicationSignInManager), context As IOwinContext) As ApplicationSignInManager
            Return New ApplicationSignInManager(context.GetUserManager(Of ApplicationUserManager)(), context.Authentication)
        End Function
    End Class
    

    5.Modfy the connections string in the web config as below:

      <connectionStrings>
        <add name="DefaultConnection" connectionString="Server={server};Port=3306;Database=vbidentity;Uid={user};Pwd={password};" providerName="MySql.Data.MySqlClient" />
      </connectionStrings>

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 18, 2018 2:55 AM

All replies

  • User283571144 posted

    Hi VB_Blue,

    According to your pervious thread, I found the AspNet.Identity.MySQL library should be downloaded from the AspNet.Identity.MySQL (CodePlex).

    But this link dodesn't contains the url to download the AspNet.Identity.MySQL library.

    I guess you don't  add the AspNet.Identity.MySQL library in your solution, so you couldn't use the mysql as the dbcontext.

    Here is a workaround.

    If you want to use mysql as the database for identity, I suggest you try to use the MySql.AspNet.Identity libarary.

    Notice: By using this library, you will need to execute create script on your MySQL database which will create the tables required for the ASP.NET Identity provider.

    More details about how to use this library work well with mysql and vb, you could refer to below steps:

    1.Create a new ASP.NET MVC 5 project, choosing the Individual User Accounts authentication type.Remove the Entity Framework packages and replace with MySql.AspNet.Identity.

    Uninstall-Package Microsoft.AspNet.Identity.EntityFramework
    Uninstall-Package EntityFramework
    Install-Package MySql.AspNet.Identity
     Install NuGet Package called MySql.AspNet.Identity
    

    2.Modify the IdentityModels.vb as below:

    Imports System.Security.Claims
    Imports System.Threading.Tasks
    Imports Microsoft.AspNet.Identity
    Imports Microsoft.AspNet.Identity.Owin
    Imports MySql.AspNet.Identity
    
    ' You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    Public Class ApplicationUser
        Inherits IdentityUser
        Public Async Function GenerateUserIdentityAsync(manager As UserManager(Of ApplicationUser)) As Task(Of ClaimsIdentity)
            ' Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            Dim userIdentity = Await manager.CreateIdentityAsync(Me, DefaultAuthenticationTypes.ApplicationCookie)
            ' Add custom user claims here
            Return userIdentity
        End Function
    End Class
    
    'Public Class ApplicationDbContext
    '    Inherits IdentityDbContext(Of ApplicationUser)
    '    Public Sub New()
    '        MyBase.New("DefaultConnection", throwIfV1Schema:=False)
    '    End Sub
    
    '    Public Shared Function Create() As ApplicationDbContext
    '        Return New ApplicationDbContext()
    '    End Function
    'End Class
    

    3.In ~/App_Start/Startup.Auth.cs file, remove app.CreatePerOwinContext(ApplicationDbContext.Create);

    Like this:

    Imports Microsoft.AspNet.Identity
    Imports Microsoft.AspNet.Identity.Owin
    Imports Microsoft.Owin
    Imports Microsoft.Owin.Security.Cookies
    Imports Microsoft.Owin.Security.Google
    Imports Owin
    
    Partial Public Class Startup
        ' For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        Public Sub ConfigureAuth(app As IAppBuilder)
            ' Configure the db context, user manager and signin manager to use a single instance per request
            'app.CreatePerOwinContext(AddressOf ApplicationDbContext.Create)
            app.CreatePerOwinContext(Of ApplicationUserManager)(AddressOf ApplicationUserManager.Create)
            app.CreatePerOwinContext(Of ApplicationSignInManager)(AddressOf ApplicationSignInManager.Create)
    
            ' Enable the application to use a cookie to store information for the signed in user
            ' and to use a cookie to temporarily store inforation about a user logging in with a third party login provider
            ' Configure the sign in cookie
            ' OnValidateIdentity enables the application to validate the security stamp when the user logs in.
            ' This is a security feature which is used when you change a password or add an external login to your account.
            app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
                .AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                .Provider = New CookieAuthenticationProvider() With {
                    .OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(Of ApplicationUserManager, ApplicationUser)(
                        validateInterval:=TimeSpan.FromMinutes(30),
                        regenerateIdentity:=Function(manager, user) user.GenerateUserIdentityAsync(manager))},
                .LoginPath = New PathString("/Account/Login")})
    
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie)
    
            ' Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5))
    
            ' Enables the application to remember the second login verification factor such as phone or email.
            ' Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            ' This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie)
    
            ' 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() With {
            '   .ClientId = "",
            '   .ClientSecret = ""})
        End Sub
    End Class
    

    4.Modify the ~/App_Start/IdentityConfig.cs as below:

    Imports System.Threading.Tasks
    Imports System.Security.Claims
    Imports Microsoft.AspNet.Identity
    Imports Microsoft.AspNet.Identity.EntityFramework
    Imports Microsoft.AspNet.Identity.Owin
    Imports Microsoft.Owin
    Imports Microsoft.Owin.Security
    Imports MySql.AspNet.Identity
    
    Public Class EmailService
        Implements IIdentityMessageService
    
        Public Function SendAsync(message As IdentityMessage) As Task Implements IIdentityMessageService.SendAsync
            ' Plug in your email service here to send an email.
            Return Task.FromResult(0)
        End Function
    End Class
    
    Public Class SmsService
        Implements IIdentityMessageService
    
        Public Function SendAsync(message As IdentityMessage) As Task Implements IIdentityMessageService.SendAsync
            ' Plug in your SMS service here to send a text message.
            Return Task.FromResult(0)
        End Function
    End Class
    
    ' Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    Public Class ApplicationUserManager
        Inherits UserManager(Of ApplicationUser)
    
        Public Sub New(store As IUserStore(Of ApplicationUser))
            MyBase.New(store)
        End Sub
    
        Public Shared Function Create(options As IdentityFactoryOptions(Of ApplicationUserManager), context As IOwinContext) As ApplicationUserManager
            Dim manager = New ApplicationUserManager(New MySqlUserStore(Of ApplicationUser))
    
            ' Configure validation logic for usernames
            manager.UserValidator = New UserValidator(Of ApplicationUser)(manager) With {
                .AllowOnlyAlphanumericUserNames = False,
                .RequireUniqueEmail = True
            }
    
            ' Configure validation logic for passwords
            manager.PasswordValidator = New PasswordValidator With {
                .RequiredLength = 6,
                .RequireNonLetterOrDigit = True,
                .RequireDigit = True,
                .RequireLowercase = True,
                .RequireUppercase = True
            }
    
            ' 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(Of ApplicationUser) With {
                                              .MessageFormat = "Your security code is {0}"
                                          })
            manager.RegisterTwoFactorProvider("Email Code", New EmailTokenProvider(Of ApplicationUser) With {
                                              .Subject = "Security Code",
                                              .BodyFormat = "Your security code is {0}"
                                              })
            manager.EmailService = New EmailService()
            manager.SmsService = New SmsService()
            Dim dataProtectionProvider = options.DataProtectionProvider
            If (dataProtectionProvider IsNot Nothing) Then
                manager.UserTokenProvider = New DataProtectorTokenProvider(Of ApplicationUser)(dataProtectionProvider.Create("ASP.NET Identity"))
            End If
    
            Return manager
        End Function
    
    End Class
    
    ' Configure the application sign-in manager which is used in this application.
    Public Class ApplicationSignInManager
        Inherits SignInManager(Of ApplicationUser, String)
        Public Sub New(userManager As ApplicationUserManager, authenticationManager As IAuthenticationManager)
            MyBase.New(userManager, authenticationManager)
        End Sub
    
        Public Overrides Function CreateUserIdentityAsync(user As ApplicationUser) As Task(Of ClaimsIdentity)
            Return user.GenerateUserIdentityAsync(DirectCast(UserManager, ApplicationUserManager))
        End Function
    
        Public Shared Function Create(options As IdentityFactoryOptions(Of ApplicationSignInManager), context As IOwinContext) As ApplicationSignInManager
            Return New ApplicationSignInManager(context.GetUserManager(Of ApplicationUserManager)(), context.Authentication)
        End Function
    End Class
    

    5.Modfy the connections string in the web config as below:

      <connectionStrings>
        <add name="DefaultConnection" connectionString="Server={server};Port=3306;Database=vbidentity;Uid={user};Pwd={password};" providerName="MySql.Data.MySqlClient" />
      </connectionStrings>

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 18, 2018 2:55 AM
  • User1567609808 posted

    Hi, First of all thank you very much for your attention.

    I have tested your code and it works perfectly.

    My site is in vb.net webforms and I feel that now I can continue my work.

    Thank you very much for your generosity.

    Monday, June 18, 2018 5:07 AM