Using the ASP.Net membership provider in a Windows forms application part 4.
In my last three blog
entries I showed how to use the ASP.Net membership provider in a Windows
application. I finished with the problem of storing the current user name and
the fact that there is a second overload to the IsUserInRole() function that
only takes a role name. Well it turns out that this function checks for the
current user and uses either the HttpContext.Current.User or the
Threading.Thread.CurrentPrincipal depending on the fact if the application is
hosted. As the Threading.Thread.CurrentPrincipal is the normal way access is
provided to the current user and role information in a windows application this
seems like the natural thing to do.
The System.Web.Security.RolePrincipal class implements the required
IPrincipal interface so this is the class we need to use. To create the
required object we need an IIDentity object to provide the user identity
information. This can be provided using the System.Security.Principal.GenericIdentity
class that implements the IIdentity interface.
Add the following code to the top of the Module1.vb:
Imports System.Security.Principal
Now we can set the principal and check for specific roles using the
following code:
Dim user As MembershipUser =
Membership.GetUser("Maurice")
Dim identity As New GenericIdentity(user.UserName)
Dim principal As New RolePrincipal(identity)
Threading.Thread.CurrentPrincipal = principal
If Roles.IsUserInRole("Developer") Then
Console.WriteLine("Is a
developer.")
Else
Console.WriteLine("Doesn't
write code.")
End If
An alternative way of checking the user and role is:
Console.Write(Threading.Thread.CurrentPrincipal.Identity.Name)
If
Threading.Thread.CurrentPrincipal.IsInRole("Developer") Then
Console.WriteLine(" is a
developer.")
Else
Console.WriteLine(" doesn't
write code.")
End If
So the complete console application now looks like:
Imports System.Security.Principal
Imports System.Web.Security
Module Module1
Sub Main()
' Creating a new user
Dim status As MembershipCreateStatus
Membership.CreateUser( _
"Maurice",
_
"Password_1",
_
"maurice@TheProblemSolver.nl",
_
"Password question",
_
"Password answer",
_
True, _
status)
' Check the status for errors
Console.WriteLine(status.ToString())
' Validate a username/password
If
Membership.ValidateUser("Maurice",
"Password_1")
Then
Console.WriteLine("User
validated.")
Else
Console.WriteLine("User
invalid!")
End If
' Create a new Developer role.
' Add the <roleManager
enabled="true" /> to the app.config for this to work
If Not Roles.RoleExists("Developer") Then
Roles.CreateRole("Developer")
End If
' Add a new role to a known user.
If Not Roles.IsUserInRole("Maurice", "Developer") Then
Roles.AddUserToRole("Maurice",
"Developer")
End If
' Create a second user with only
username/password
' Add the
<membership><providers> element to the app.config first
Dim user As MembershipUser
user = Membership.GetUser("User2")
If user Is Nothing Then
user = Membership.CreateUser("User2",
"p")
Console.WriteLine(user.UserName)
End If
' Check is a specified user is in a
specific role
If Roles.IsUserInRole("Maurice", "Developer") Then
Console.WriteLine("Is a
developer.")
Else
Console.WriteLine("Doesn't
write code.")
End If
' Set the current application
principal information to a known user
Dim identity As GenericIdentity
Dim principal As RolePrincipal
user = Membership.GetUser("Maurice")
identity = New
GenericIdentity(user.UserName)
principal = New
RolePrincipal(identity)
Threading.Thread.CurrentPrincipal = principal
' Check if the current principal is
in a specific role
If Roles.IsUserInRole("Developer") Then
Console.WriteLine("Is a developer.")
Else
Console.WriteLine("Doesn't
write code.")
End If
' Set the current application
principal information to another known user
user = Membership.GetUser("User2")
identity
= New
GenericIdentity(user.UserName)
principal = New
RolePrincipal(identity)
Threading.Thread.CurrentPrincipal = principal
' Use the principal to check for
role information
Console.Write(Threading.Thread.CurrentPrincipal.Identity.Name)
If
Threading.Thread.CurrentPrincipal.IsInRole("Developer") Then
Console.WriteLine(" is a
developer.")
Else
Console.WriteLine(" doesn't
write code.")
End If
Console.ReadLine()
End Sub
End Module
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<roleManager enabled="true" />
<membership
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="1"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression="" />
</providers>
</membership>
</system.web>
</configuration>
Maurice de Beijer
www.TheProblemSolver.nl