您的位置:首页 > 编程语言 > Java开发

java web之基于表单的身份验证

2017-07-07 17:14 435 查看

1.web应用程序安全主要注意什么

①阻止未授权的用户访问敏感的数据

指定哪些用户才能访问哪些指定资源、用户的身份验证。身份验证简单方式采用post方式提交表单,用户名和密码。身份验证复杂方式采用X.509证书,用户通过客户端发送证书到服务器端。

②防止攻击者从数据传输过程中窃取网络数据

使用SSL来加密浏览器和服务器之间的数据通信。

2.什么是声明式安全

为了阻止未被授权的访问,使用web.xml的方式来声明哪些URL需要保护,哪些用户有权限访问它们。也可以指定验证方法来识别用户。为了保护网络数据,使用web.xml来规定哪些URL使用SSL才能访问。如果只是普通的http连接来访问,那么服务器就自动将它们重定向到相应的https(SSL)。

3.基于表单的身份验证

(1)设置用户名、密码以及角色

server.xml文件(默认):





配置tomcat-user.xml文件,添加角色:

<?xml version="1.0" encoding="UTF-8"?>

<role rolename="tomcat"/>
<role rolename="manager-gui"/>
<user username="sunpy" password="111111" roles="tomcat,manager-gui"/>
<!--
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
-->
</tomcat-users>
(2)指定login页面和login-failure页面

在web.xml文件中配置

<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/login_error.html</form-error-page>
</form-login-config>
</login-config>
当未验证的用户尝试访问受保护的资源时,会被重定向到login.jsp页面。如果当前用户登录成功了,那么毫无疑问就可以获取想要的资源。如果登录失败,就会重定向到login_error.html页面。

(3)编写登录页面login.jsp

<form action="j_security_check" method="post">
用户名 :<input type="text" name="j_username"/><br/>
密码 :<input type="password" name="j_password"/><br/>
<input type="submit" value="提交"/>
</form>
(4)创建登录失败页面login_error.html

<!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>
错误页面
</body>
</html>
错误页面随便写了

(5)指定需要密码保护的URL

在web.xml文件中配置:

<security-constraint>
<web-resource-collection>
<web-resource-name>Sensitive</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>sunpy</role-name>
<role-name>administrator</role-name>
</auth-constraint>
</security-constraint>
web-resource-collection元素指定了哪些URL应该受到保护。

auth-constraint元素则指定了哪些用户有权访问这些资源。

(6)列出所有可能的抽象角色

<security-role>
<role-name>administrator</role-name>
</security-role>
<security-role>
<role-name>sunpy</role-name>
</security-role>
<security-role>
<role-name>manager-gui</role-name>
</security-role>
(7)指定需要SSL访问的URL

<security-constraint>
.....
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>


至于tomcat配置SSL: http://www.oschina.net/question/12_23148
生成证书 :  http://ln-ydc.iteye.com/blog/1335213
参考博客  :  http://blog.csdn.net/zhangzuomian/article/details/50324395
http://www.jianshu.com/p/e94ff6c5dcfd
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: