为了账号安全,请及时绑定邮箱和手机立即绑定
2.1 API 接口规范

Restful 提倡将接口的行为状态放到了 Http 的头部 method 里。对同一个资源的不同操作,接口 URL 可能是一样的。行为规约主要有下面几项:GET查询资源,不会对资源产生变化的都用 GET。例:查询慕课网 http Wiki 教程的所有小节列表:GET http://www.imooc.com/http如果资源查询的过程需要带过滤参数,建议使用 URL 参数的形式:例:查询慕课网 http 小节中作者是 rj 的文章GET http://www.imooc.com/http?author=rj例:查询慕课网 http 里面 id = 1 的文章GET http://www.imooc.com/http/1POST新增某个资源:POST http://www.imooc.com/http具体的参数放请求体中{"title":"restful","author":"rj","content":"xxxxxx"}PUT资源的修改:PUT http://www.imooc.com/http/{articleId}具体的参数放请求体中{"title":"restful","author":"rj","content":"xxxxxx"}PATCHPATCH http://www.imooc.com/http/{articleId}patch 跟 put 都是修改的意思,put 类型的修改请求体中需要包含全量的对象信息,而 patch 只需要带上要修改的某几个对象即可,没有带上的参数就代表不更新,采用原来的值。具体的参数放请求体中{"title":"aaa"}DELETE删除资源:DELETE http://www.imooc.com/http/{articleId}

4. 编辑 spring-mvc.xml

spring-mvc.xml 用来配置与 Spring MVC 相关的组件信息,用来提供给 web 上下文对象进行组件维护。这些组件包括 Spring MVC 核心组件和用户控制器组件。<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 启动注解支持 --> <mvc:annotation-driven/> <!--静态资源交给 tomcat default servelt 处理--> <mvc:default-servlet-handler /> <!--扫描组件位置--> <context:component-scan base-package="com.mk.web.action"></context:component-scan> <!-- 视图解析器 --> <mvc:view-resolvers> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp"></property> <property name="suffix" value=".jsp"></property> </bean> </mvc:view-resolvers></beans>元素解释说明:mvc:annotation-driven: 启动注解支持,完全使用 XML 进行 Spring MVC 项目维护,并不是很方便。即使在使用 XML 时,建议还是结合注解一起使用,这也是 Spring MVC 官方建议的;context:component-scan: 指定哪些组件由 Spring MVC 的上下文对象负责。除了 Spring MVC 内部组件外,再就是用户控制器;mvc:view-resolvers: 配置具体的视图解析器。Tips: 映射器、适配器等组件可以不用显示配置,采用 Spring MVC 默认配置即可。

2.2 负载均衡的hash算法

我们打开 ip_hash 指令的注释,这个时候默认是使用客户端的 ip 地址作为 hash 的 key,然后重启 Nginx 服务并进行如下的命令行操作:# 使用本机的ip地址,无论请求多少出,通过hash转发到的上游服务器地址都是一致的[shen@shen ~]$ curl http://180.76.152.1138002, server[shen@shen ~]$ curl http://180.76.152.1138002, server[shen@shen ~]$ curl http://180.76.152.1138002, server# 只有换了ip之后,请求转发的上游地址才可能有变化[shen@shen ~]$ curl -H 'X-Forwarded-For: 111.10.1.3' http://180.76.152.1138000, server[shen@shen ~]$ curl -H 'X-Forwarded-For: 111.10.2.3' http://180.76.152.1138001, server

2. 获取 URL 相关参数

本节编写一个 Flask 程序 request-url.py,打印 request 中和 URL 相关的属性:from flask import Flaskfrom flask import requestapp = Flask(__name__)def echo(key, value): print('%-10s = %s' % (key, value))@app.route('/query')def query(): echo('url', request.url) echo('base_url', request.base_url) echo('host', request.host) echo('host_url', request.host_url) echo('path', request.path) echo('full_path', request.full_path) return 'hello'if __name__ == '__main__': app.run(port = 80)在浏览器中输入 http://localhost/query?userId=123,程序在终端输出如下:url = http://localhost/query?userId=123base_url = http://localhost/queryhost = localhosthost_url = http://localhost/path = /queryfull_path = /query?userId=123

2. HTTPS

Https 是一种通过计算机网络进行安全通信的传输协议,经由 Http 进行通信,利用 SSL/TLS 建立安全信道,加密数据包。Https 使用的主要目的是提供对网站服务器的身份认证,同时保护交换数据的隐私与完整性。Http 服务的默认端口是 80,Https 服务的默认端口是 443。HTTP + SSL = HTTPS = HTTP + 身份认证 + 数据私密 + 数据完整性

4. 小结

本节中介绍了 Nginx 的四层反向代理和七层反向代理,并用案例进行了演示。刚开始使用时只是用了 http 指令块,因为是针对 http 请求进行处理。这进行的是四层反向代理。nginx 七层方向代理处理的是 http 请求,对应的是 http 协议。如果只是转发 http 请求,可以简单使用 proxy_pass 指令即可。这和我们之前简单的反向代理示例一致。

3. 使用场景及应用实例

超链接是文章的资源向导,包括锚点连接和外部连接,可以帮助读者快速定位到文章内的某个位置,或者打开外部的某个资源和网页。常见的页内锚点超链接如文档目录等。实例 5:一个属于自己的门户页。#### 一个简单的个人门户- 常用网站 [百度](http://www.baidu.com), [慕课](http://www.imooc.com), [Github](http://www.github.com)- 新闻 [人民网](http://www.people.com.cn/), [央视网](http://www.cctv.com/), [光明网](http://www.gmw.cn/),- 购物网站 [淘宝](http://www.taobao.com), [京东](http://www.jd.com)- 程序文档 [小程序开发文档](https://developers.weixin.qq.com/miniprogram/dev/framework/)渲染结果如下:

3.1 下载合适的 USB 驱动程序

由于不同品牌的手机,USB 驱动程序也是不同的,所以推荐大家从品牌厂商的官网下载 USB 驱动程序。设备制造商驱动程序网址宏碁http://www.acer.com/worldwide/support/华硕https://www.asus.com/support/Download-Center/BlackBerryhttps://swdownloads.blackberry.com/Downloads/entry.do?code=4EE0932F46276313B51570F46266A608Dellhttp://support.dell.com/support/downloads/index.aspx?c=us&cs=19&l=en&s=dhs&~ck=anavmlFujitsuhttp://www.fmworld.net/product/phone/sp/android/develop/HTChttp://www.htc.com/support华为http://consumer.huawei.com/en/support/index.htmIntelhttp://www.intel.com/software/androidKyocerahttp://www.kyocera-wireless.com/support/phone_drivers.htm联想http://support.lenovo.com/us/en/GlobalProductSelectorLGEhttp://www.lg.com/us/support/software-firmwareMotorolahttps://motorola-global-portal.custhelp.com/app/answers/detail/a_id/88481/MTKhttp://online.mediatek.com/Public Documents/MTK_Android_USB_Driver.zipSamsunghttp://developer.samsung.com/galaxy/others/android-usb-driver-for-windows夏普http://k-tai.sharp.co.jp/support/Sonyhttp://developer.sonymobile.com/downloads/drivers/小米http://www.xiaomi.com/c/driver/index.html中兴http://support.zte.com.cn/support/news/NewsDetail.aspx?newsId=1000442

2.1 简单的七层负载均衡

在 nginx.conf 中添加如下的 http 指令块:http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log logs/access.log main; sendfile on; keepalive_timeout 65; gzip on; server { listen 8000; return 200 '8000, server\n'; } server { listen 8001; return 200 '8001, server\n'; } server { listen 8002; return 200 '8002, server\n'; } upstream backends { # ip_hash # hash user_$arg_username; server 127.0.0.1:8000; server 127.0.0.1:8001; server 127.0.0.1:8002; } server { listen 80; location / { proxy_pass http://backends; proxy_http_version 1.1; proxy_set_header Connection ""; } }}上述配置中,我们用8000,8001和8002三个端口模拟了3个上游服务器,默认使用轮询负载均衡算法,而且三个的权重均为1。进行如下的 http 请求操作,可以看到 Nginx 转发 http 请求会均匀地分配到3个服务器上。[shen@shen ~]$ curl http://180.76.152.1138000, server[shen@shen ~]$ curl http://180.76.152.1138001, server[shen@shen ~]$ curl http://180.76.152.1138002, server[shen@shen ~]$ curl http://180.76.152.1138000, server

3.2 七层反向代理示例

在 nginx.conf 中加入如下的测配置:...http { server { listen 8000; return 200 '$uri\n'; } server { listen 9001; location /test { proxy_pass http://127.0.0.1; } } server { listen 9002; location /test { proxy_pass http://127.0.0.1/xyz; } }}...启动 nginx 后,通过请求服务器的8000端口,我们可以知道请求的 uri 值,然后测试经过两种类型的 proxy_pass 配置后最后的 uri 的值。具体操作以及结果如下:# 测试8000端口显示的uri值[shen@shen ~]$ curl http://180.76.152.113:8000/test/abc/test/abc# 9001端口配置中proxy_pass后面的URL不带URI[shen@shen ~]$ curl http://180.76.152.113:9001/test/abc/test/abc# 9002端口配置中proxy_pass后面的URL带URI,会替换到匹配的/test[shen@shen ~]$ curl http://180.76.152.113:9002/test/abc/xyz/abc

4. 小结

本节讲解了 HTTP 协议中的不同方法,通过一个具体的例子,讲解在 Flask 应用中,如何处理指定 HTTP 方法的请求。对常用的 HTTP 方法,使用思维导图概括如下:

2. 实现-TCP/IP 协议

Http 和 TCP/IP 都是协议,它们的不同之处在于:HTTP 是浏览器和后台服务之间的语言,而 TCP/IP是电脑之间的语言(相同的语言才能互相理解双方要表达的意思)。Http 本身只是约定了传输的时候文字要是什么格式,具体文字如何转成物理的高低电平穿越电脑实现传输的过程它是不知道的。所以它需要借助专业的人士 TCP/IP 来处理。TCP/IP 是专门解决主机之间信息传输的,它不局限于为 Http 服务,像发送邮件也有自己的邮件协议(SMTP),它的底层也需要借助 TCP/IP 来实现。(TCP/IP是整套完整的网络传输框架模型,HTTP 也是属于它里面的应用层)。

3.2 使用自定义方法作为表达式

如果我们需要扩展现有的表达式,我们可以使用 Spring Bean 里的方法。例如,使用自定义 Bean WebSecurity 中的 check 方法:public class WebSecurity { public boolean check(Authentication authentication, HttpServletRequest request) { ... }}我们可以在配置文件中这样写:<http> <intercept-url pattern="/user/**" access="@webSecurity.check(authentication,request)"/> ...</http>或者在 Java 中直接加入配置:http .authorizeRequests(authorize -> authorize .antMatchers("/user/**").access("@webSecurity.check(authentication,request)") ... )

1.1 概述

HTTP 协议是 Hyper Text Transfer Protocol(超文本传输协议)的缩写, 用于从万维网(World Wide Web)服务器传输超文本到本地浏览器的传送协议。HTTP 协议工作于客户端-服务端架构为上。浏览器作为 HTTP 客户端通过 URL 向 服务端发送请求,服务端根据接收到的请求 URL,向客户端发送响应信息。HTTP 请求-响应模型如下所示:

3.1 默认的安全头配置

Spring Security 提供了一系列默认 Http 安全响应头,我们可以便捷的配置它们。例如,为 X-Frame-Options 指定值 SAMEORIGIN:@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) { http.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin())); }}如果不希望默认头被自动添加,可以通过如下方式配置,例如仅添加 Cache Control 头:@EnableWebSecuritypublic class WebSecurityConfig extendsWebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // ... .headers(headers -> headers // 取消自动添加默认头 .defaultsDisabled() // 添加 CacheControl 头 .cacheControl(withDefaults()) ); }}或者通过以下方式禁用所有 HTTP 安全响应头:@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.headers(headers -> headers.disable()); }}

2.1 SSL

Https 并不是新的一种协议,它是 Http 协议的基础上面封装了一层 SSL(Secure Socket Layer),Https 底层跟 Http 一样是经由 TCP 通信的。SSL 并不是 Http 特有的,所有应用层协议都可以使用 SSL 进行安全通信。

4.2 access_log 指令用法示例

我们只需要在 http 指令块中配置 log_format 指令和 access_log 指令即可。测试的配置如下:...http { ... log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log logs/access.log main; # 和上面的日志格式无关 server { listen 8000; return 200 '8000, server\n'; } ...}...log_format 指令是指定打印日志的格式,access_log 指令指定日志输出的路径以及指定使用前面定义的日志格式。在配置好日志相关的指令后,重启 Nginx,并发送一个 Http 请求,就可以在对应的路径上看到相关的日志信息了。# 模拟发送http请求[shen@shen Desktop]$ curl http://180.76.152.113:80008000, server[shen@shen Desktop]$ curl -H "X-Forwarded-For: 1.1.1.1" http://180.76.152.113:8000# 查看打印的日志,和前面配置的日志格式进行对比[root@server nginx]# tail -2 logs/access.log 103.46.244.226 - - [02/Feb/2020:20:52:05 +0800] "GET / HTTP/1.1" 200 13 "-" "curl/7.29.0" "-"103.46.244.226 - - [02/Feb/2020:20:57:03 +0800] "GET / HTTP/1.1" 200 13 "-" "curl/7.29.0" "1.1.1.1"

2.2 访问资源的 URI

客户端可以新增、修改、删除联系人,相应的 URI 如下:HTTP 方法行为URIPOST新增联系人http://localhost/usersPUT修改 id 为 123 的联系人http://localhost/users/123DELETE删除 id 为 123 的联系人http://localhost/users/123

4. 小结

Http 直接跟 TCP 传输层交互,而 Https 多了一层 SSL 协议,正式这个协议让 Https 有了数据加密、身份认证的证书和数据完整性保护这些功能。SSL 是独立于 HTTP 的协议,所以不光是 HTTP 协议,其他运行在应用层的 SMTP 和 Telnet 等协议均可配合 SSL 协议使用。可以说 SSL 是当今世界上应用最为广泛的网络安全术。

4.2. 补充 Spring 的配置文件

配置文件的目的是将我们自定义的实现类交给 Spring 的容器管理。因为 Spring 框架核心功能之一就是 IoC 控制反转,目的是将对象实例化的动作交给容器。还记得第一节介绍的吗?不记得了?走你,剩下的我们继续。最终 Spring 的配置文件如下:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd"> <!-- 此标签的作用 是实例化UserServiceImpl类的实例 交给 Spring 容器 --> <bean id="userService" class="com.wyan.service.impl.UserServiceImpl"></bean></beans>

2. 几种常用的客户端-服务器消息传递方式

http 最常用的协议,用于客户端主动向服务器发送请求,单向传递;ajax HTTP 的扩展版,底层还是 HTTP 协议,只不过客户端是无刷新的;comet 也是基于 HTTP 封装的,使用 HTTP 长连接的方式,原理大致是将 HTTP 的timeout 设置较长,服务器有数据变化时返回数据给客户端,同时断开连接,客户端处理完数据之后重新创建一个 HTTP 长连接,循环上述操作(这只是其中一种实现方式);websocket 这是 HTML5 中的新标准,基于 socket 的方式实现客户端与服务端双向通信,需要浏览器支持 HTML5;Adobe Flash Socket 这个也是使用 socket 的方式,需要浏览器支持 flash 才行,为了兼容老版本的浏览器;ActiveX object 只适用于 IE 浏览器;目前尚没有一种方式能兼容所有的浏览器,只能针对软件的目标客户人群做一定的兼容。sse 服务端单向推送。

2. HttpUrlConnection 接口

Android 系统为我们提供了 HttpUrlConnection 接口用于实现 Http 请求。自从 Android API9 开始,HttpUrlConnection 就成为了 Android App 推荐使用的内置 Http 库。使用它无需添加任何依赖,打开网络权限:<uses-permission android:name="android.permission.INTERNET" />就可以访问 Http 资源了,可以说相比第三方框架

4.1 refer 模块防盗链测试

在 nginx.conf 中加入如下防盗配置:...http { ... server { listen 9008; location / { valid_referers none blocked *.domain.pub www.domain.com/nginx server_names ~\.baidu\.; if ($invalid_referer) { return 403; } return 200 "valid\n"; } } ...}...重新加载或者启动 Nginx 后,我们进行如下操作:[shen@shen Desktop]$ curl -H 'referer: http://www.domain.com/test' http://180.76.152.113:9008 <html><head><title>403 Forbidden</title></head><body><center><h1>403 Forbidden</h1></center><hr><center>nginx/1.17.6</center></body></html>[shen@shen Desktop]$ curl -H 'referer: http://www.domain.com/nginx' http://180.76.152.113:9008 valid[shen@shen Desktop]$ curl -H 'referer: ' http://180.76.152.113:9008 valid[shen@shen Desktop]$ curl http://180.76.152.113:9008 valid[shen@shen Desktop]$ curl -H 'referer: http://www.domain.pub/test' http://180.76.152.113:9008 valid第一个 http 请求 referer 的值存在,但是没有匹配后面的域名,所以返回403。其余的请求中 referer 值要么不存在,要么没有这个头部,要么匹配了后面的域名正则表达,都通过了 referer 校验,所以都返回 “valid” 字符串。我们通过构造不同的 referer 头部字段成功的绕过了 Nginx 的referer 模块校验,也说明了这种防盗的方式极不靠谱。

5. 编辑 application.xml

application.xml 是 Spring 上下文容器所关联的配置文件,可称其为全局上下文对象的关联配置文件。<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config></context:annotation-config> <context:component-scan base-package="com.mk.web"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan></beans>元素解释说明:context:annotation-config: 启动注解支持,建议需要全局上下文对象创建、维护的对象使用注解的方式;context:component-scan: 扫描位置,需要排除开 Spring MVC 容器对象扫描的位置。Tips: application.xml 文件中一般用来配置业务层逻辑组件、数据层逻辑组件、通用组件、第三方组件相关的信息。

3. 小结

HTTP 协议应该是前端、后端、测试开发人员最常接触的网络协议了,因为这是网站和用户之间传输信息的直接渠道。面试官考察 HTTP 相关的问题,也是为了了解候选人的开发基本功,为了熟悉本小结的知识,大家也可以了解下发送 HTTP 的 Postman 开发工具,以及 HTTP 网络抓包的 Wireshark 工具。

4. 小结

本节讨论了通过 HTTP + SSL 的方式,规避 HTTP 协议在安全上的不足。HTTP 协议存在安全隐患,容易遭到恶意攻击,例如中间人攻击;HTTP 安全时传输层安全的范畴,可以通过重定向 HTTP 连接和强制安全传输的方式增加其安全性;Spring Security 支持通过配置将 HTTP 请求转换为 HTTPS 请求;Spring Security 支持为 B/S 应用强制使用安全传输。下节我们讨论如果通过 Spring Security 统一不同 Web 容器间的访问控制差异。

3. log 阶段

log 阶段是 http 请求 11 个阶段中的最后一个阶段,这个阶段主要的任务就是记录请求的访问日志。这个阶段主要涉及的是 ngx_http_log_module 这个模块。该模块提供了几个常用指令,如 access_log 和 log_format 指令,分别定义了请求日志的记录文件以及记录的日志格式。# 官方例子log_format compression '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" "$gzip_ratio"';access_log /spool/logs/nginx-access.log compression buffer=32k;# access_log指令用法Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];access_log off;Default: access_log logs/access.log combined;Context: http, server, location, if in location, limit_except# log_format指令用法Syntax: log_format name [escape=default|json|none] string ...;Default: log_format combined "...";Context: http# 是否打开日志缓存Syntax: open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];open_log_file_cache off;Default: open_log_file_cache off;Context: http, server, location

3.4 HSTS 头

HTTP Strict Transport Security(HSTS)头,在 Spring Security 中是被默认开启的,我们可以修改它的默认状态,如下:@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .headers(headers -> headers .httpStrictTransportSecurity(hsts -> hsts .includeSubDomains(true) .preload(true) .maxAgeInSeconds(31536000) ) ); }}

1. 前言

上节我们讨论了 HTTP 请求中,如何通过配置其头部参数达到安全性提升的效果,本节将讨论 HTTP 协议层面的安全性提升方法。HTTP 通讯协议是一种明文传输协议,存在安全隐患,所以通常我们会使用 TLS 方式保障其安全。本节我们主要讨论 Spring Security 中的 HTTP 安全。

直播
查看课程详情
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号