REST安全实践·1.HTTP BASIC认证
http://tomcat.apache.org/tomcat-7.0-doc/config/realm.html
Eclipse内置Tomcat配置?
拷贝Mysql的JDBC驱动到$CATALINA_HOME/lib目录。使用Maven的项目可以从本地仓库取得,否则从网上搜吧。
M2_REPO/mysql/mysql-connector-java/5.1.25/mysql-connector-java-5.1.25.jar (仓库地址举例:M2_REPO=C:\Users\hanl\.m2\repository)
/security-rest/src/main/webapp/WEB-INF/web.xml
<security-constraint> <web-resource-collection> <url-pattern>/webapi/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> <http-method>UPDATE</http-method> <http-method>DELETE</http-method> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint></security-constraint><security-constraint> <web-resource-collection> <url-pattern>/webapi/*</url-pattern> <http-method>GET</http-method> </web-resource-collection> <auth-constraint> <role-name>user</role-name> </auth-constraint></security-constraint><login-config> <auth-method>BASIC</auth-method></login-config>
Tomcat将调用Realm.authenticate()对首次访问的用户进行认证。认证通过后被缓存在Tomcat(对于FORM-based authentication, 直到session失效,对于 BASIC authentication,直到关闭浏览器)
C:\Users\hanl.m2\repository\org\apache\tomcat\tomcat-catalina\7.0.42\tomcat-catalina-7.0.42-sources.jar
Realm.authenticate()?
base64(username:password)?
测试工具?Chrome插件POSTMAN
测试用例1
测试地址=http://localhost:8080/security-rest/webapi/books
测试方法=GET
测试用户=无
测试结果=**401 Unauthorized**
测试用例2
测试地址=http://localhost:8080/security-rest/webapi/books
测试方法=GET
测试用户=caroline role=user
测试结果=**200 OK**
测试用例3
测试地址=http://localhost:8080/security-rest/webapi/books
测试方法=POST
测试用户=caroline role=user
测试结果=**403 Forbidden**
测试用例4
测试地址=http://localhost:8080/security-rest/webapi/books
测试方法=POST
测试用户=eric role=admin
测试结果=**200 OK**