Apache Shiro 快速开始指南(第2部分)

上次我們直接運行了樣本,但我認為在設定文件中直接編寫用戶信息並不適合。

[users]
# format: username = password, role1, role2, ..., roleN
root = secret,admin
guest = guest,guest
presidentskroob = 12345,president
darkhelmet = ludicrousspeed,darklord,schwartz
lonestarr = vespa,goodguy,schwartz

[roles]
# format: roleName = permission1, permission2, ..., permissionN
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5

我們將參考這個地方,從數據庫中獲取用戶信息。由於不需要使用MySQL,我們將使用Apache Derby。

MySQL & Apache Derby as jdbcRealm for Apache Shiro

启动Apache Derby服务。

$ sudo su -
# cd /usr/share/derby
# ./NetworkServerControl start

创建用户信息数据库。

$ ij
ij> connect 'jdbc:derby://localhost:1527/test;create=true';
ij> CREATE TABLE USERS (ID varchar(255) PRIMARY KEY NOT NULL, PASS varchar(255) NOT NULL);
ij> CREATE TABLE ROLES (ID varchar(255) PRIMARY KEY NOT NULL, ROLE varchar(255) NOT NULL);
ij> INSERT INTO USERS (ID,PASS) VALUES ('root','password');
ij> INSERT INTO ROLES (ID,ROLE) VALUES ('root','admin');

转到web目录。

$ cd shiro-root-1.3.2/samples/web

以下是修改shiro.ini的步骤。

jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.authenticationQuery = select pass from users where id = ?
jdbcRealm.userRolesQuery = select role from roles where id = ?

ds = com.jolbox.bonecp.BoneCPDataSource
ds.driverClass=org.apache.derby.jdbc.ClientDriver
ds.jdbcUrl=jdbc:derby://localhost:1527/test
jdbcRealm.dataSource=$ds

# We need to set the cipherKey, if you want the rememberMe cookie to work after restarting or on multiple nodes.
# YOU MUST SET THIS TO A UNIQUE STRING
#securityManager.rememberMeManager.cipherKey = kPH+bIxk5D2deZiIxcaaaA==

#[users]
# format: username = password, role1, role2, ..., roleN
#root = secret,admin
#guest = guest,guest
#presidentskroob = 12345,president
#darkhelmet = ludicrousspeed,darklord,schwartz
#lonestarr = vespa,goodguy,schwartz

#[roles]
# format: roleName = permission1, permission2, ..., permissionN
#admin = *
#schwartz = lightsaber:*
#goodguy = winnebago:drive:eagle5

在pom.xml文件中添加如下依赖关系。

<dependency>
    <groupId>com.jolbox</groupId>
    <artifactId>bonecp</artifactId>
    <version>0.7.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.apache.derby</groupId>
    <artifactId>derbyclient</artifactId>
    <version>10.4.2.0</version>
</dependency>

运行Jetty。

$ mvn jetty:run

请在您的网络浏览器中访问以下URL:
http://localhost:9080/

广告
将在 10 秒后关闭
bannerAds