Information, ideas, tips, architectures, and all that is possible on software development
Two years ago I was studying about RIA and in order to test new technologies that were emerging as dwr ajax,dojo and prototype to construction of interfaces I decided to build a prototype of an application. I built a prototype of application of Remote Desktop and File Transfer service. And to make the communication between the web application and local application, I have developed a communication protocol that is transported into the communication protocol from the MSN. I found a api called Java MSN Messenger. This api allows to connect easily from the MSN network. I made a video of the application and i presented this video in my university when I studied, I thought it was cool to the application interface.
Developing this prototype I learned how to work the msn protocol.
MSN Protocol Operation
The MSN protocol is a protocol that implements the IM technology and was developed by Microsoft to serve as a communication protocol for its IM tool called MSN Messenger. The MSN protocol was based on RFC 2778. RFC 2778 defines an abstract model of an IM system, the various entities involved, defines terminology and outline what services will be offered by the system.
A MSN Messenger session involves a connection to a Notification Server (NS), which is a notification to the server to connect to the "switchboard servers (SBS) that provides the IM service.
Notification Server (NS)
Notification Server notifications are made to the server via MSN Messenger session. The main purpose of NS is to notify the information present in the meeting and their contacts and request a session to the switchboard. The Notification Server also has other services such as notification of new e-mail received from a Hotmail account (www.hotmail.com).
To request a session to the switchboard, the customer must send an XFR command with two parameters, the first with TrID (Transaction IDs) and the second command is a command SB.XFR the MSN Messenger protocol that makes some kind of notification to the server requesting a switchboard session. With this command sent, the server will respond to the command with another command XFR with the instructions to authenticate to the switchboard.
The first parameter of the response "SB" means you are starting a session on the switchboard. The second parameter of the response indicates the IP address and port of the server, 1863 is the default port Switchboard Server. The third parameter specifies the response type of authentication, which will always be CKI. The fourth parameter of the response "17262740.1050826919.32308" is an id of authentication which the client will need to submit when he sent his ID to the switchboard.
Switchboard (SB)
The switchboard is a manager of the sessions, that is, each person in chat corresponds to a shared connection in a switchboard session. That is, when two people are in conversation directly, the switchboard that manages the state of that conversation acts as a proxy.
Once connected to the switchboard, the customer must send a USR command with three parameters: the first is the TrID, the second the e-mail that is connected, and the third session Id. The USR command is used to connect to the switchboard. If he succeeds in sending the command, the server will send back an USR command with the same TrID, the OK command in the first parameter and your e-mail in the second parameter and the name of User in the third parameter.
One example of authentication messages
Onde eu trabalho, eu precisei configurar um sistema antigo que sua struts para usar autenticação via JAAS com o JBOSS. Eu procurei na Internet alguns tutorias que monstra-se detalhademente o processo de configuração do JAAS com JBOSS, infelizmente eu não encontrei nada bem explicado e acabei procurando algum tutorial em inglês, e ai sim, eu encontrei mais coisas. Vou descrever passo a passo como eu fiz para fazer essa configuração, espero que ajude algum pessoa.
1. Passo – Configurar login, password, roles e group.
No JBOSS existe várias formas de autenticação. JBOSS permite autenticação via arquivo de propriedades, via banco de dados, via web service, via LDAP. Na configuração que eu fiz no meu trabalho eu utilizei uma autenticação via arquivo de propriedades, mas nesse exemplo que eu vou mostrar a autenticação feita via banco de dados, que eu acho que é mais interessante para ser implementado.
Primeiramente crie duas tabelas no seu banco de dados, a primeira tabela define o login e a senha, e a segunda tabela define login, rules e group. Isso corresponde aos arquivos users.properties e roles.properties que ficam na pasta jboss-x.x.x\server\default\conf.
A primeira tabela vaiter o nome USERS e teria a seguinte estrutura:
CREATE TABLE USERS (UserID VARCHAR (30) PRIMARY KEY, Password VARCHAR (10));
A segunda tabela vai ter o nome ROLES e teria a seguinte estrutura:
CREATE TABLE ROLES ( UserID VARCHAR (30), Role VARCHAR (30), RoleGroup VARCHAR (30));
Depois crie alguns registos para as tabelas USERS e ROLES
INSERT INTO USERS VALUES ('MARIA', '123')
INSERT INTO USERS VALUES ('JOAO', '123456')
INSERT INTO Roles VALUES ('MARIA', 'ENFERMEIRA', 'USER')
INSERT INTO Roles VALUES ('MARIA', 'FUNCIONARIO', 'USER')
INSERT INTO Roles VALUES ('JOAO', 'ADMINISTRADOR', 'ADM')
INSERT INTO Roles VALUES ('JOAO', 'MEDICO', 'ADM')
INSERT INTO Roles VALUES ('JOAO', 'FUNCIONARIO', 'USER')
2. Passo – Configurar o arquivo login-config.xml
Esse arquivo se encontra na pasta jboss-x.x.x\server\default\conf. O login-config.xml é usado pelo JBOSS para definir modelos de autenticação. É lá que vai ser inserido uma nova “application policy”. Application policy é o nome que o JBOSS dá para as novas configurações de autenticação. Nesse arquivo eu criei um Application policy, definir um nome que nos vamos chamar de exemploJAAS, informar qual banco de dados vai ser usado.
Esse arquivo se encontra na pasta jboss-x.x.x\server\default\conf. O login-config.xml é usado pelo JBOSS para definir modelos de autenticação. É lá que vai ser inserido uma nova “application policy”. Application policy é o nome que o JBOSS dá para as novas configurações de autenticação. Nesse arquivo eu criei um Application policy, definir um nome que nos vamos chamar de exemploJAAS, informar qual banco de dados vai ser usado.
<application-policy name="examploJAAS">
<authentication>
<login-module code="org.jboss.security.ClientLoginModule"
flag="required">
</login-module>
<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule"
flag="required">
<module-option name ="managedConnectionFactoryName">
jboss.jca:service=LocalTxCM,name=OracleDS
</module-option>
<module-option name="dsJndiName">
java:/nomejndibancoDB
</module-option>
<module-option name="principalsQuery">
Select Password from USERS where UserID =?
</module-option>
<module-option name="rolesQuery">
Select Role 'Roles', RoleGroup 'RoleGroups' from ROLES where UserID =?
</module-option>
</login-module>
</authentication>
</application-policy>
Os module option, principalsQuery e rolesQury são padrões para esse tipo de autenticação. Essas query são usadas pela API do JBOSS para realizar a autenticação via banco de dados.
3. Passo – No arquivo jboss-web que fica na sua aplicação adicione o security domain que nos criamos com o nome exemploJAAS
<security-domain>java:/jaas/exemploJAASsecurity-domain>
4. Passo – altere o aqui auth.conf na pasta jboss-x.x.x\client e adicione o seguinte conteúdo
exemploJAAS {
org.jboss.security.ClientLoginModule required;
org.jboss.security.auth.spi.DatabaseServerLoginModule required;
};
6. Passo – Altere o arquivo web.xml do seu projeto e adicione as seguintes linhas
<security-constraint>
<web-resource-collection>
<web-resource-name>action</web-resource-name>
<description>Teste de seguraça</description>
<url-pattern>*.do</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>ENFERMEIRA</role-name>
<role-name>FUNCIONARIO</role-name>
<role-name>ADMINISTRADOR</role-name>
<role-name>MEDICO</role-name>
</auth-constraint>
<user-data-constraint>
<description>no description</description>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/logon.do</form-login-page>
<form-error-page>/logoff.do</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description>role 1</description>
<role-name>ENFERMEIRA</role-name>
</security-role>
<security-role>
<description>role 2</description>
<role-name>FUNCIONARIO</role-name>
</security-role>
<security-role>
<description>role 3</description>
<role-name>ADMINISTRADOR</role-name>
</security-role>
<security-role>
<description>role 4</description>
<role-name>MEDICO</role-name>
</security-role>
Nesse exemplo do web.xml, o arquivo está configurado para que todas as chamadas no navegador para *.do, só posam ser concluídas, caso os usuários tenham alguma das roles definidas(ENFERMEIRA,MEDICO,ADMINISTRADOR,FUNCIONARIO). Se você estiver usando algum patterns de front controller e caso você precise fazer bloqueios por páginas(ex: médico só pode ver pagania xx.jsp e a enfermeira só pode ver a pagina yyy.jsp) eu aconselho fazer essa validação ou pelo código.
Caso você não esteja usado um patterns front controller fica mais fácil fazer esse tipo de bloqueio pelo web.xml.
7. Passo - Criar um jsp de login
<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″pageEncoding=”ISO-8859-1″%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>LOGIN</title>
</head>
<body>
<form action=”j_security_check” method=”POST”>
username: <input type=”text” name=”j_username” /><br />
password: <input type=”password” name=”j_password” /><br />
<input type=”submit” value=”login” />
</form>
</body>
</html>
Pronto, quando o jsp login chamar o j_security_check. O JBOSS vai verficar o login e senha e adicionar as roles ao usando. O seguinte código mostra um exemplo de como verificar as roles de um determinado usuário tem.
HttpServletRequest.getUserPrincipal(); // retorna o User
HttpServletRequest.isUserInRole("ADM"); // retorna se o usuario possue a role informada
User user = (User)HttpServletRequest.getUserPrincipal();
user.getRoles(); // roles do usuario
© 2009 dev-doska | Blogger Templates created by Deluxe Templates
Powered by Blogger | Wordpress Theme by danielfajardo web