2013年10月24日木曜日

JDBC認証作り直してみた。

【DB構築】

drop database auth;
create database auth;
use auth;
##---------------------------------auth.sql---------------------------------
drop table if exists auth_users;
create table auth_users (
user_name varchar(64),
user_pass varchar(16),
PRIMARY KEY (user_name)
);
insert into auth_users values ('casio', '$$casio');

drop table if exists user_roles;
create table user_roles (
user_name varchar(64),
role_name varchar(16),
PRIMARY KEY (user_name)
);
INSERT INTO user_roles VALUES ('casio', 'member');

##---------------------------------auth.sql---------------------------------
show databases;
use auth;
show tables;
select * from auth_users;
select * from user_roles;


SOURCE auth.sql;




プロジェクト作成
ファイル→新規→動的Webプロジェクト
プロジェクト名: xxxxxxxxx
ターゲット・ランタイム: apache-tomcat-7.0.42
動的Webモジュールバージョン: 3.0

web.xmlデプロイメント記述子の生成(G)にチェック

以下をWebContent下に配置。


【index.html】

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index.html</title>
<meta http-equiv="refresh" content="3; URL=http://localhost:8080/JDBCAuth/security-webapps/menu.jsp">
</head>
<body>
<p>このページは、3秒後にログインページに移動します。</p>
<br>
<p><a href="security-webapps/menu.jsp">業務メニューにジャンプします。</a></p>
</body>
</html>

【login/index.html】


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index.html</title>
<meta http-equiv="refresh" content="3; URL=http://localhost:8080/JDBCAuth/security-webapps/menu.jsp">
</head>
<body>
<p>このページは、3秒後にログインページに移動します。</p>
<br>
<p><a href="../security-webapps/menu.jsp">業務メニューにジャンプします。</a></p>
</body>
</html>

【login/login.jsp】


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login page</title>
</head>
<body>
<h1 align="center">端末管理支援システム</h1>
<h1 align="center">ログイン</h1>
<br>
<div align="center">
<form method="post" action='<%= response.encodeURL("j_security_check")%>'>
<table>
<tr>
<td>メールアドレス</td>
<td> <input type="text" name="j_username"></td>
</tr>
<tr>
<td>パスワード</td>
<td><input type="password" name="j_password"></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Login" name="submit">
<input type="reset" value="Reset" name="reset">
</td>
</tr>
</table>
</form>
<br> <br> <br>
<%
String str_status = request.getParameter("status");
if( str_status != null && str_status.equals("error")){
out.println("ID/Passswordが誤っています。");
}
%>
<br> <br> <br>
<p><a href="../regist/regist.html">新規登録はこちら。</a></p>
</div>
</body>
</html>

【login/logout.jsp】

<%@ page session="true" language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
[<%=request.getRemoteUser()%>] さんはログアウトしました。
<% session.invalidate(); %>
<br><br>
<a href="../security-webapps/menu.jsp">ログイン画面に戻る</a>

【regist/regist.html】

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登録項目入力フォーム</title>
<script type="text/javascript">

function check(){
var flag = 0;
// alert("フィールドのチェックをはじめます。");
if( !document.regist_form.auth_mailaddress.value.match(/^([A-Za-z0-9_\.\-]){2,32}@([A-Za-z0-9_\.\-]){3,31}$/)){
flag = 1;
alert("メールアドレスのフォーマットが間違っています。");
} else if( !document.regist_form.auth_password.value.match(/^[a-z0-9]{6,16}$/)){
flag = 1;
alert("パスワードのフォーマットが間違っています。");
}
// alert("フィールドチェックが終わりました。ー2");
if(flag){
// window.alert('必須項目に未入力がありました'); // 入力漏れがあれば警告ダイアログを表示
return false; // 送信を中止
}
else{
return true; // 送信を実行
}
}

</script>
</head>
<body>
<br>
<h1 align="center">端末管理支援システム</h1>
<h1 align="center">ユーザ登録</h1>
<br>
<div align="center">
<form name="regist_form" method="POST" action="regist.jsp" onSubmit="return check()">
<table>
<tr>
<td>メールアドレス:</td>
<td><input type="text" name="auth_mailaddress" value="" tabindex="0" accesskey="a" placeholder="xxxxx@xxxxx.xxx.xx"></td>
</tr>
<tr>
<td>パスワード:</td>
<td><input type="password" name="auth_password" value="" tabindex="1" accesskey="b" placeholder="山田 太郎"></td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="登録" tabindex="10" accesskey="s">
<input type="reset" value="取消" tabindex="11" accesskey="r">
</td>
</tr>
</table>
</form>
</div>
<p><a href="../security-webapps/menu.jsp">loginに戻る</a></p>
</body>
</html>


【regist/regist.jsp】

<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>データベース登録</title>
</head>
<body>
<%
String str_mailaddress = request.getParameter("auth_mailaddress");
String str_password = request.getParameter("auth_password");
out.println("メールアドレスは" + str_mailaddress + "ですね" + "<br>");
out.println("パスワードは" + str_password + "ですね" + "<br>");
%>
<%
Connection cn = null;
Statement st = null;
ResultSet rs = null;
String sql =null;
int num =0;

try {
Class.forName("com.mysql.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost/auth?" +
"user=takahab&password=no3177&useUnicode=true&characterEncoding=UTF-8");

st=cn.createStatement();

sql = "select user_name from auth_users where user_name = \'" + str_mailaddress + "\'";

out.println( sql );

rs = st.executeQuery(sql);

} catch (Exception e ) {
out.print("<p>JDBC executeQuery エラー<br>" + e.toString() + "</p>");
}

if( rs.next() ) {
out.println( "<p>メールアドレスは、既に登録されています。 </p>");
} else {
try {
sql = "insert into auth_users (user_name, user_pass) values (?, ?)";
PreparedStatement pstmt = cn.prepareStatement(sql);

pstmt.setString(1, str_mailaddress );
pstmt.setString(2, str_password );
num = pstmt.executeUpdate();

out.println(sql);

sql = "insert into user_roles (user_name, role_name) values (?, ?)";
pstmt = cn.prepareStatement(sql);

pstmt.setString(1, str_mailaddress );
pstmt.setString(2, "member" );
num = pstmt.executeUpdate();

out.println(sql);

st.close();
cn.close();

} catch (Exception e ) {
out.print("<p>JDBC executeUpdate エラー<br>" + e.toString() + "</p>");
}
}
%>
<br>
<p><a href="../security-webapps/menu.jsp">login</a></p>
</body>
</html>

【security-webapps/AuthDump.jsp】

<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>認証テーブルDBの表示</title>
</head>
<body>
<h1 align="center">認証DBテーブルの表示</h1>

<table border="5" cellpadding="2" cellspacing="2" align="center">

<tr><th>メールアドレス</th><th>パスワード</th></tr>

<%
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost/auth?" +
"user=takahab&password=no3177&useUnicode=true&characterEncoding=UTF-8");
Statement st=cn.createStatement();

String sql = "select * from auth_users";
ResultSet rs = st.executeQuery(sql);

while(rs.next()){
out.println("<tr>");
out.println("<td>" + rs.getString("user_name") + "</td>");
out.println("<td>" + rs.getString("user_pass") + "</td>");
out.println("</tr>");
}

sql = "select * from user_roles";
rs = st.executeQuery(sql);

while(rs.next()){
out.println("<tr>");
out.println("<td>" + rs.getString("user_name") + "</td>");
out.println("<td>" + rs.getString("role_name") + "</td>");
out.println("</tr>");
}
    try { st.close(); } catch (Exception e ) {}
    try { cn.close(); } catch (Exception e ) {}
%>
</table>
<br><br>
<p><a href="menu.jsp">JSPメニューシステムにジャンプします。</a></p>
</body>
</html>

【security-webapps/menu.jsp】

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>メニューシステム(jspタイプ)</title>
</head>
<body>
ようこそ [<%=request.getRemoteUser()%>] さんログイン成功です。
<br> <br>
ユーザ名: [<%=request.getRemoteUser()%>]
<br>
Authタイプ: [<%=request.getAuthType()%>]
<br>
メソッド: [<%=request.getMethod()%>]
<br>
パス: [<%=request.getPathInfo()%>]
<br>
トランス: [<%=request.getPathTranslated()%>]
<br>
クエリ: [<%=request.getQueryString()%>]
<br>
リクエストSID: [<%=request.getRequestedSessionId()%>]
<br>
URI: [<%=request.getRequestURI()%>]
<br>
URL: [<%=request.getRequestURL()%>]
<br>
PATH: [<%=request.getServletPath()%>]
<br><br>
<p><a href="AuthDump.jsp">認証DB情報の表示</a></p>
<br>
<p><a href="../login/logout.jsp">logout</a></p>
</body>
</html>


【error/403.html】

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" http-equiv="refresh" content="3; URL=http://localhost:8080/JDBCAuth/login/logout.jsp">
<title>Insert title here</title>
</head>
<body>
<p>
お客さまのIDは、ログインする権限がありません。( エラー403)
3秒後にログアウトページに移動しますので。再度ログインしてください。
</p>
<br>
<p><a href="../login/logout.jsp">再度ログインしてください。</a></p>
</body>
</html>

【error/404.html】

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" http-equiv="refresh" content="3; URL=http://localhost:8080/JDBCAuth/security-webapps/menu.jsp">
<title>error</title>
</head>
<body>
<p>
エラーページです(404)3秒後にログアウトページに移動します。再度ログインしてください。
</p>
<br>
<p><a href="../security-webapps/menu.jsp">再度ログインしてください。</a></p>
</body>
</html>

【error/408.html】

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" http-equiv="refresh" content="3; URL=http://localhost:8080/JDBCAuth/security-webapps/menu.jsp">
<title>error</title>
</head>
<body>
<p>エラーページです(408)3秒後にログインページに移動します。</p>
<br> <br>
<p>
HTTPステータス 408 - ログインプロセスに認められていた時間が過ぎました。
継続したいならば,バックボタンを2度押してから再度リンクを押すか,
ブラウザを立ち上げ直してください
</p>
<br>
<p><a href="../security-webapps/menu.jsp">業務メニューにジャンプします。</a></p>
</body>
</html>




【WEBーINF/web.xml】

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>JDBCAuth</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<security-constraint>
<web-resource-collection>
<web-resource-name>Authentication of FormAuth</web-resource-name>
<url-pattern>/security-webapps/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
<role-name>manager</role-name>
<role-name>member</role-name>
<role-name>entry</role-name>
<role-name>stop</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login/login.jsp</form-login-page>
<form-error-page>/login/login.jsp?status=error</form-error-page>
</form-login-config>
</login-config>

<security-role>
<role-name>admin</role-name>
</security-role>

<security-role>
<role-name>manager</role-name>
</security-role>

<security-role>
<role-name>member</role-name>
</security-role>

<security-role>
<role-name>entry</role-name>
</security-role>

<security-role>
<role-name>stop</role-name>
</security-role>

<session-config>
<session-timeout>1</session-timeout>
</session-config>

<error-page>
<error-code>403</error-code>
<location>/error/403.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error/404.html</location>
</error-page>
<error-page>
<error-code>408</error-code>
<location>/error/408.html</location>
</error-page>

</web-app>



Tomcatのserver.xmlにJDBC認証のDBを設定。
/usr/local/tomcat/conf/server.xml


【servers/-/server.xml】

<!-- by takahab
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
by takahab -->

<!-- by takahab -->
<Realm className="org.apache.catalina.realm.JDBCRealm"
connectionName="takahab"
connectionPassword="no3177"
connectionURL="jdbc:mysql://localhost/auth"
driverName="com.mysql.jdbc.Driver"
roleNameCol="role_name"
userCredCol="user_pass"
userNameCol="user_name"
userRoleTable="user_roles"
userTable="auth_users"/>
</Realm>
<!-- by takahab -->





【regist/regist.html】 old版

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登録項目入力フォーム</title>
</head>
<body>
<form method="POST" action="regist.jsp">
<p><label>メールアドレス:
<input type="text" name="auth_mailaddress" value="" tabindex="0" accesskey="a">
</label> </p>

<p><label>   お名前:
<input type="text" name="auth_name" value="" tabindex="1" accesskey="b">
</label></p>

<p>性別:
<input type="radio" name="auth_sex" value="man" tabindex="2" accesskey="c">男性
<input type="radio" name="auth_sex" value="woman" tabindex="3" accesskey="d">女性<br>

職業:
<input type="checkbox" name="auth_job" value="Student" tabindex="4" accesskey="e">学生
<input type="checkbox" name="auth_job" value="worker" tabindex="5" accesskey="f">会社員
<input type="checkbox" name="auth_job" value="official" tabindex="6" accesskey="g">公務員
<input type="checkbox" name="auth_job" value="etc" tabindex="7" accesskey="h">その他
</p>

<p>年代:<select name="auth_age" tabindex="8">
<option value="10ages">10代</option><option value="20ages">20代</option>
<option value="30ages">30代</option><option value="40ages">40代</option>
<option value="50ages">50代</option><option value="60ages">60代</option>
<option value="age" selected>お選びください</option>
</select></p>

<p><label>お問合せ<br>
<textarea name="auth_title" rows="5" cols="60" tabindex="9" accesskey="i">
</textarea>
</label></p>

<p>
<input type="submit" value="登録" tabindex="10" accesskey="s">
<input type="reset" value="取消" tabindex="11" accesskey="r">
</p>
</form>
</body>
</html>
















0 件のコメント:

コメントを投稿

シャットダウン時の後処理 (shutdown)

# vi /etc/systemd/system/drop.service [Unit] Description= stop httpgwd DefaultDependencies=no Before=shutdown.target RefuseManualStart=true ...