Primeiramente vamos criar a tabela de permissão de grupos.
create
table tbGrupos (id int primary key identity(1,1), dsGrupo varchar(100) not null)
Inserindo alguns registros
insert
tbGrupos values(Admin)insert tbGrupos values(Usuario)
Crinado uma tabela de login
create
table tbLogin (login varchar(100) not null, senha varchar(10) not null, id int foreign key references tbGrupos(id))Populando a tabela, coloquei um login como admin e o outro como usuario
insert
tbLogin values(ze, 123,1)insert
tbLogin values(joao, 123,2)Criando uma procedure para consultar
create
procedure LOGIN_SELECT@login
varchar(100),@senha
varchar(10)as
select
* from tbLogin l inner join tbGrupos g on l.id = g.idwhere
login = @loginand
senha = @senha
Abra o Visual Studio e crie uma classe de dados
Imports
Microsoft.VisualBasicImports
System.Data.SqlClient
Public
Class clsDadosAtributo para a string de conexao
Private con As SqlConnection
Metodo para abrir a conexao
Private Function ConectionOpen() As Boolean
Dim string_Conection As String = "sua string de conexao"con =
New SqlConnection(string_Conection) Trycon.Open()
Return True Catch ex As Exception Throw New Exception( ex.Message) End Try End Function Private Sub ConectionClose() If con.State = Data.ConnectionState.Open Thencon.Close()
End If End Sub Public Sub Dispose()ConectionClose()
End Sub
Um metedo para executar a procedure
Public Function Executar(ByVal nmProcedure As String, ByRef objCmd As SqlCommand) As SqlDataReader If Not ConectionOpen() Then Throw New Exception("Error ao abrir a conexao") End IfobjCmd.Connection = con
objCmd.CommandText = nmProcedure
objCmd.CommandType = Data.CommandType.StoredProcedure
Return objCmd.ExecuteReader End FunctionEnd
Class
Agora uma classe que chamei de clsPermissao
Imports
Microsoft.VisualBasicImports
System.Data.SqlClientPublic
Class clsPermissao
#
Region "Atributos" Private _Login As Integer Private _Senha As String Private _Grupo As String#
End Region#
Region "Propriedades" Public Property Login() As string Get Return _Login End Get Set(ByVal value As string)_Login = value
End Set End Property Public Property Senha() As String Get Return _Senha End Get Set(ByVal value As String)_Senha = value
End Set End Property Public Property Grupo() As String Get Return _Grupo End Get Set(ByVal value As String)_Grupo = value
End Set End Property
#
End RegionPublic Function VerificarLogin() As Boolean Dim objCmd As New SqlCommand Dim objDados As New clsDados Dim objread As SqlDataReader Try
objCmd.Parameters.Add(
"@login", Data.SqlDbType.VarChar,100)objCmd.Parameters("@login
").Direction = Data.ParameterDirection.InputobjCmd.Parameters("@login
").Value = _LoginobjCmd.Parameters.Add("@senha", Data.SqlDbType.VarChar,10)
objCmd.Parameters("@senha").Direction = Data.ParameterDirection.Input
objCmd.Parameters("@senha").Value = _Senha
objread = objDados.Executar("LOGIN_SELECT", objCmd)
If objread.Read Then
_Login = objread(
"login").ToString_Grupo = objread(
"dsGrupo").ToString Return True Else Return False End IfCatch ex As Exception
Throw New Exception( ex.Message)
Finally
objCmd.Dispose()
objDados.Dispose()
End Try End FunctionEnd
Class
Crie um pagina aspx adicione 2 textbox 2 label e um botão, no evento do botão adicione ó seguite
Estanciando o objeto clspermissao
Dim objPermissao As New clsPermissao
Passando os valores para a propriedade
objPermissao.Login = Me.txtLogin.Text
objPermissao.Senha = Me.txtSenha.Text
Verifica se o usuario existe
If objPermissao.VerificarLogin Then
Criando um tik de autenticação
Dim tik As FormsAuthenticationTicketCriando um tik para cryptografar o tik de autenticação
Dim encTik As String
Dim cookie As HttpCookieNos parametros FormsAuthenticationTicket informe a versão que o patrão é 1 , o nome do login, a data atual, a data para expirar, se é persistente , e o grupo
tik =
New FormsAuthenticationTicket(1, objPermissao.Login, Now, Now.AddMinutes(5), False, objPermissao.dsGrupo)Joga todo o conteudo do tik para enctik ja cryptografado
encTik = FormsAuthentication.Encrypt(tik)
Joga as informações no cookie dando a ele um nome que depois o asp exija que tenha
cookie =
New HttpCookie(FormsAuthentication.FormsCookieName, encTik)Joga o cookie para a maquina do cliente
Response.Cookies.Add(cookie)
Redireciona a pagiana que foi solicitada
Response.Redirect(FormsAuthentication.GetRedirectUrl(objPermissao.Login,
False)) End If
Agora um pequeno truquinho no arquivo global.asax existe varios eventos, no evento
Application_AuthenticateRequest adicione o seguinte codigo
rotected
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As System.EventArgs)Criando um cookie
Dim cookie As HttpCookie
Pegando o cookie que criamos na pagina aspx
cookie = Request.Cookies(FormsAuthentication.FormsCookieName)
Verifica se é valido
If Not IsNothing(cookie) Then
Criando um tik para descryptografar
Dim enTik As String
Criando um tik de atenticação
Dim tik As FormsAuthenticationTicket
Criando uma Identificação generic
Dim G_I As System.Security.Principal.GenericIdentity
Criando uma principal generic
Dim G_P As System.Security.Principal.GenericPrincipal
Passando o valor do cookie para enTik
enTik = cookie.Value
Descryptogrando o tik de autenticação
tik = FormsAuthentication.Decrypt(enTik)
Passando como identificação o nome do tik
G_I = New System.Security.Principal.GenericIdentity(tik.Name)
Passando para o grupo G_P, o parametro do G_P é GenericIdentity que é o nosso G_I e um array de grupos
G_P = New System.Security.Principal.GenericPrincipal(GI, New String() {tik.UserData})
Guardando os grupo no context do usario
Context.User = G_P
End If
End Sub Pronto acabou nossa autenticação, agora em qualquer arquivo Web.configé só colocar os grupo que vc deseja que acesse aquela pasta ou arquivo, por exemplo
Criei um pasta admin onde que só quero que os que pertence ao grupo de Admin acesse aquela pasta
<
authorization><
allow roles="Admin"/><
deny users="*"/></
authorization>
Espero que tenha gostado até a proxima.