Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

Security với JAAS sử dụng DatabaseServerLoginModule

Trong bài này tôi sẽ hướng dẫn cho bạn cách secure EJB với DatabaseServerLoginModule.

1. Cấu hình database

Đầu tiên bạn thiết kế database với MDBRS là Ms SQL Server. Tạo cơ sở dữ liệu có tên EJB_SecureModule và có các bảng cùng mối quan hệ như hình

clip_image002

Dữ liệu cho 2 bảng

clip_image004 clip_image006

2. Cấu hình JBoss

Trước hết bạn cần cấu hình đăng nhập theo keiu63 DatabaseServerLoginModule trong file %JBOSS_HOME%\server\default\conf\logon-config.xml như sau:

<application-policy name="dbsecuritymodule">
		<authentication>
			<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule"
                             flag="required">
				<module-option name="dsJndiName">java:/SecureDS</module-option>
				<module-option name="principalsQuery">select Password from Users where UserName=?</module-option>
				<module-option name="rolesQuery">Select Role, RoleGroup from Roles where UserName = ?
				</module-option>
			</login-module>

			<!-- Module for doing authentication from within the application -->
		<login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule" flag = "optional">
			<module-option name = "dsJndiName">java:/SecureDS</module-option>
			<module-option name = "principalsQuery"> select Password from Users where UserName=?</module-option>
			<module-option name = "rolesQuery">elect Role, RoleGroup from Roles where UserName = ?</module-option>
		</login-module>

		<!-- Client Login module so that the security context can be set for invoking EJBs -->
		<login-module code = "org.jboss.security.ClientLoginModule" flag = "required">
			<module-option name="restore-login-identity">true</module-option>
		</login-module>

	</authentication>
</application-policy>

Cấu hình phân đoạn datasource – tập tin secure-ds.xml trong thư mục %JBOSS_HOME%\server\default\deploy\ như sau:

<?xml version="1.0" encoding="UTF-8"?>
<datasources>
	<local-tx-datasource>
		<jndi-name>SecureDS</jndi-name>
		<use-java-context>true</use-java-context>
		<connection-url>
			jdbc:sqlserver://localhost:1433;databaseName=EJB_SecureModule
		</connection-url>
		<driver-class>
			com.microsoft.sqlserver.jdbc.SQLServerDriver
		</driver-class>
		<user-name>sa</user-name>
		<password></password>
		<metadata>
			<type-mapping>MS SQLSERVER2000</type-mapping>
		</metadata>
  </local-tx-datasource>
</datasources>

3. Tạo EJB

Trong ví dụ này đơn giản là 1 Session Bean xử lý cho các công việc của ngân hàng đơn giản bao gồm các chức năng: nộp tiền, rút tiền, chuyển tiền.

clip_image008

clip_image010

clip_image012

clip_image014

clip_image016

clip_image018

Thêm vào các business methods như sau:

public boolean Deposit(Account acc, double amount) {

if (amount &lt;= 0) {

return false;

}

acc.setBalance(acc.getBalance() + amount);

return true;

}

public boolean Withdral(Account acc, double amount) {

if (acc.getBalance() &lt;= amount) {

return false;

}

acc.setBalance(acc.getBalance() - amount);

return true;

}

public boolean Transfer(Account from, Account to, double amount) {

if (from.getBalance() &lt;= amount || amount &lt;= 0) {

return false;

}

to.setBalance(to.getBalance() + amount);

from.setBalance(from.getBalance() - amount);

return true;

}

Cấu hình ejb-jar.xml như sau:

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">
    <enterprise-beans>
        <session>
            <display-name>BankingBeanSB</display-name>
            <ejb-name>BankingBeanBean</ejb-name>
            <home>vovanhai.wordpress.com.BankingBeanRemoteHome</home>
            <remote>vovanhai.wordpress.com.BankingBeanRemote</remote>
            <ejb-class>vovanhai.wordpress.com.BankingBeanBean</ejb-class>
            <session-type>Stateless</session-type>
            <transaction-type>Container</transaction-type>
        </session>
    </enterprise-beans>
    <assembly-descriptor>
        <security-role>
            <role-name>Echo</role-name>
        </security-role>
        <method-permission>
            <role-name>Echo</role-name>
            <method>
                <ejb-name>BankingBeanBean</ejb-name>
                <method-name>*</method-name>
            </method>
        </method-permission>

        <method-permission>
            <role-name>Coder</role-name>
            <method>
                <ejb-name>BankingBeanBean</ejb-name>
                <method-name>create</method-name>
            </method>
            <method>
                <ejb-name>BankingBeanBean</ejb-name>
                <method-name>Deposit</method-name>
            </method>
        </method-permission>

        <container-transaction>
            <method>
                <ejb-name>BankingBeanBean</ejb-name>
                <method-name>*</method-name>
            </method>
            <trans-attribute>Required</trans-attribute>
        </container-transaction>
    </assembly-descriptor>
</ejb-jar>

Cấu hình file jboss.xml như sau:

<?xml version="1.0" encoding="UTF-8"?>
<jboss>
    <!-- All bean containers use this security manager by default -->     
    <security-domain>java:/jaas/dbsecuritymodule</security-domain>    
    <enterprise-beans>
        <session>
            <ejb-name>BankingBeanBean</ejb-name>
            <jndi-name>ty/BankingBeanBean</jndi-name>
        </session>
    </enterprise-beans>
</jboss>

Triển khai ứng dụng lên JBoss.

Client

clip_image020

clip_image022

clip_image024

clip_image026

clip_image028

package securityejb_client;

import javax.jms.Session;

import javax.naming.InitialContext;

import javax.security.auth.callback.Callback;

import javax.security.auth.callback.CallbackHandler;

import javax.security.auth.callback.NameCallback;

import javax.security.auth.callback.PasswordCallback;

import javax.security.auth.callback.UnsupportedCallbackException;

import javax.security.auth.login.LoginContext;

import javax.security.auth.login.LoginException;

import vovanhai.wordpress.com.Account;

import vovanhai.wordpress.com.BankingBeanRemote;

import vovanhai.wordpress.com.BankingBeanRemoteHome;

/**

*

* @author VoVanHai

*/

public class DatabaseLogonModule_client {

static class AppCallbackHandler implements CallbackHandler {

private String username;

private char[] password;

public AppCallbackHandler(String username, char[] password) {

this.username = username;

this.password = password;

}

public void handle(Callback[] callbacks) throws

java.io.IOException, UnsupportedCallbackException {

for (int i = 0; i &lt; callbacks.length; i++) {

if (callbacks[i] instanceof NameCallback) {

NameCallback nc = (NameCallback) callbacks[i];

nc.setName(username);

} else if (callbacks[i] instanceof PasswordCallback) {

PasswordCallback pc = (PasswordCallback) callbacks[i];

pc.setPassword(password);

} else {

throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");

}

}

}

}

public static void main(String args[]) throws Exception {

System.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");

System.setProperty("java.naming.provider.url", "localhost:1099");

System.setProperty("java.security.policy", "mypol.policy");

System.setSecurityManager(new SecurityManager());

System.setProperty("java.security.auth.login.config", "au.conf");

String name = "teo";

char[] password = "123".toCharArray();

String example = " sqllogonmodule ";

System.out.println("+++ Running SessionClient with username=" + name + ", password=" + new String(password) + ", example=" + example);

try {

AppCallbackHandler handler = new AppCallbackHandler(name, password);

//chay others{}trong au.conf

LoginContext lc = new LoginContext("other ", handler);

System.out.println("Created LoginContext");

lc.login();

System.out.println("Login success");

} catch (LoginException le) {

System.out.println("Login failed");

le.printStackTrace();

}

System.out.println("___Starting call business methods");

try {

InitialContext ctx = new InitialContext();

Object obj = ctx.lookup("ty/BankingBeanBean");

BankingBeanRemoteHome home = (BankingBeanRemoteHome) obj;

BankingBeanRemote rem = home.create();

Account acc = new Account(1900l, "Nguyen Van Teo", 1000);

rem.Deposit(acc, 500);

System.out.println("Deposit OK");

System.out.println("Try to withdrawal...");

rem.Withdral(acc, 300);

} catch (Exception e) {

e.printStackTrace();

}

}

}

File au.conf đặt cùng thư mục gốc của project

srp-client{

//Login Module Needed – I use Database (Note it correlates to what I had in login-config.xml

org.jboss.security.auth.spi.DatabaseServerLoginModule required

dsJndiName=”java:/SecureDS”

principalsQuery=”select Password from Users where UserName=?”

rolesQuery=”Select Role, RoleGroup from Roles where UserName = ?”;

};

other{

//DEFAULT CLIENT-LOGIN MODULE

org.jboss.security.ClientLoginModule required;

//org.jboss.security.auth.spi.DatabaseServerLoginModule required;

};

Phần srp-client cho ví dụ khác

File mypol.policy như sau

grant

{

permission java.security.AllPermission;

};

Chạy ứng dụng, bạn sẽ có kết quả:

clip_image030

Thay username= java, password=echoman và chạy thử cho phép truy xuất phương thức withdrawal. Kết quả:

clip_image032

Chúc thành công!

25 Responses to “Security với JAAS sử dụng DatabaseServerLoginModule”

  1. hp said

    a ơi a có database cho blog ko a , cho e xin duoc ko a

  2. Drusilla said

    Hello to every one, it’s actually a good for me to visit this website, it contains useful Information.

  3. Minerva said

    Unquestionably consider that which you stated. Your favorite justification seemed to be on the web the simplest thing to remember of. I say to you, I certainly get irked at the same time as people consider concerns that they just don’t understand about. You managed to hit the nail upon the highest as smartly as outlined out the entire thing with no need side-effects , other folks can take a signal. Will probably be again to get more. Thanks

  4. Horace said

    Hello! I simply would like to offer you a huge thumbs up for your great information you’ve got here on this post. I’ll be returning to your website for more soon.

  5. Victoria said

    卸売シャネルのハンドバッグドルの数千〜数百からコストと店で販売されていますだけでなく、世界全体のオンラインウェブサイト同様に、我々は所定の位置に常に非常に良い番号を持つことができませんでした、これは、ユーザがエリアに追加された拡張機能のスマートなこ​​とはありませんでした意味 |それは丈夫、実用的でトレンディなバッグを選ぶことになると、細部に注意を払う女性専用.金の輝きは、ホログラムステッカーの上部透明層上に配置されている、となりますランダムトップステッカー層を横切っ振りかけ 我々は、それが非常に簡単に、今落ちるとそれを適用して、あなたにこの情報を提供することにより、オンラインでシャネルのハンドバッグを買い物かもしれないので、作った

  6. Doreen said

    Good post. I learn something totally new and challenging on blogs I stumbleupon everyday. It will always be interesting to read through content from other writers and use a little something from other web sites.

  7. Blanche said

    Howdy! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My blog looks weird when browsing from my iphone. I’m trying to find a theme or plugin that might be able to resolve this problem. If you have any recommendations, please share. Thanks!

  8. Lynda said

    Additionally, it is used to help strengthen the kidneys and liver. A reduction in serotonin causes an increase in the neurotransmitter, substance P. The worst of the ailment often occurs within the initial few hours.

  9. Ivory said

    Have you ever considered publishing an e-book or guest authoring on other blogs? I have a blog based on the same information you discuss and would really like to have you share some stories/information. I know my audience would value your work. If you are even remotely interested, feel free to send me an email.

  10. Octavia said

    This page certainly has all the information I needed concerning this subject and didn’t know who to ask.

  11. Yasmin said

    Most of the research into chronic fatigue suggests that main cause is a malfunction in the immune system or the metabolism. Also, the pain migrates between areas so one day the neck may ache while the next day the legs may ache for hours causing continuous and prolonged muscle and tendon pain. It is a very basic test, but so many sufferers will recognize this feature, in fact many people suffering everyday fatigue will also notice it.

  12. Craig said

    It’s a pity you don’t have a donate button! I’d most certainly donate to this excellent blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this website with my Facebook group. Chat soon!

  13. Elliot said

    I like it when people come together and share opinions. Great website, stick with it!

  14. Iola said

    s metabolic rate as well as regulate the growth and functioning of other body systems. The two most important antibodies to check are Thyroid Peroxidase Antibodies (TPO Ab) and Thyroglobulin Antibodies (TBG Ab). The TSH level is increased because the pituitary gland creates excess TSH to make the gland provide more of the hormone.

  15. Maryellen said

    Je suis une fille de quarante et un années .
    Je porte le joli nom de Françoise.
    Je voudrais devenir chef de projet . Si je suis parfois revêche, ce n’est pas un défaut ?

  16. Brooke said

    1 MP are two of the most interesting point-and-shoot cameras on the market not only because they take advantage of advanced technology but also because they offer one features that just a few short years ago were very high-end cameras. Spot metering- Measures a small amount of area in the center of the image. Total Control: You get to tell the camera what You Want.

  17. Paula said

    The camera’s comes equipped with some of the most obvious features, common to count is the extremely large zoom range ranging from 25mm to 450mm equivalent in 35mm film terms. When getting a digital waterproof digital camera, your to begin with consideration should be the superior of the digital camera. Focus – Maine promotes Maine’s fine arts photographers.

  18. Cora said

    An optional cable you should consider buying is a mini plug that will connect your digital camcorder directly to a TV or VCR. This means it will interface directly with a high-definition display in your home or you can use the built-in USB cable to upload up to six hours of videography to your PC. Everything about this camera will give you the ultimate filming experience.

  19. Larhonda said

    When you purchase digital cameras you want to buy best cheap and banded digital cameras like wespro, Polaroid, Sony cybershot, Nikon, fujifilm and many more they must have the quality, good looking, features, guaranty, warranty, price and many more. One of these hi tech gadgets they’re so mad about is spy cameras. Takes Video Clips with Audio, Pict – Bridge compatible 16MB Built-in Storage.

  20. Barbara said

    And then you can import converted AVCHD MTS or M2TS files to Mac applications, like MTS to i – Movie , FCP, FCE, i – DVD and more for editing as you like. I already thought the idea was silly but once my husband explained to me what it was for, I wanted to actually try it out. I have also tried to import straight into Pinnacle 14 (which is the editing software that I am using), but it cannot read the formats either.

  21. Boris said

    Panasonic Lumix Digital Cameras – 3 Tips So You Don’t Buy Camera Regrets. With all these features, design and the build quality, and price makes this a perfect flash for on camera use for everyone, and for experienced flash photographers the manual modes. A bit of advice, never attempt to repair the camera yourself.

  22. Florencia said

    Think about how important photography is in your life. Shop around and find the camera that is right for you. Usually you will see the F-Stop range of the lens on the front near where you found the focal length.

  23. Heriberto said

    Camera manufacturers have pretty much agreed that the current mega pixel rate is not worth improving on, and instead are going to work towards improving resolution for high contrast images. Check out the Vista – Quest VQ510 5MP Digital Camera Bundle and see for yourself. A fast shutter speed is necessary for moving subjects.

  24. Maynard said

    All the information can be seen in the rear panel as well, but the top panel gives the critical data in a very easy to use format and place. Spot metering- Measures a small amount of area in the center of the image. For example; on the Canon 7D it has the view of 112-320mm zoom, making getting a shot in crowded or cramped situations more difficult.

  25. Gayle said

    If the sixth digit of your serial number is between one and seven for the EOS-1D X, or is one for the EOS-1D C, then your camera body may be affected. One very meaningful feature that Canon thought to stick into the 6D was the ability to change focus screens, of which Canon makes one model that is precisely designed for accurate manual focus with fast lenses. Total Control: You get to tell the camera what You Want.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: