RESTful API

发布于 2017-09-29 · 本文总共 4072 字 · 阅读大约需要 12 分钟

REST(REpresentational State Transfer)

RESTful架构,是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制,所以正得到越来越多网站的采用。如果一个架构符合REST原则,就称它为RESTful架构。

设计原则

1.域名ROOT URL

2.版本Versioning

3.URL(Endpoints)

4.过滤信息Filtering

5.HTTP动词

6.状态码Status Codes

7.错误Error handling、Response

8.认证Authentication

OpenAPI and Swagger

OpenAPI = Specification

Swagger = Tools for implementing the specification

Go实战

// ProjectCreateRequest ...
// swagger:route POST /v1/projects project ProjectResponseWrapper
//
// Create Project
//
// This will create a project
//
//		Responses:
//		    201:ProjectResponseWrapper
//
// swagger:parameters ProjectResponseWrapper
type ProjectCreateRequest struct {
	// in:body
	ProjectPost
	// in:body
	Body ProjectPost
}

// ProjectResponseWrapper ...
// Create Project
//
// swagger:response ProjectResponseWrapper
type ProjectResponseWrapper struct {
	// in:body
	Body ProjectResponse
}

// ProjectPost ...
type ProjectPost struct {
	// 创建资源指定名称,必选
	//
	// Required: true
	// in: body
	Name string `json:"name" required:"true" length:"64"`

	// 创建资源添加描述,非必选
	//
	// Required: false
	// in: body
	Description string `json:"description" length:"255"`
}

// ProjectResponse ...
type ProjectResponse struct {
	ID           int64     `json:"id"`
	Name         string    `json:"name"`
	Alias        string    `json:"alias"`
	Description  string    `json:"description"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at,omitempty"`
	Creater      string    `json:"creater"`
}

install swagger

download_url=$(curl -s https://api.github.com/repos/go-swagger/go-swagger/releases/latest | \
  jq -r '.assets[] | select(.name | contains("'"$(uname | tr '[:upper:]' '[:lower:]')"'_amd64")) | .browser_download_url')
curl -o /usr/local/bin/swagger -L'#' "$download_url"
chmod +x /usr/local/bin/swagger

generate a swagger json doc

swagger generate spec -o ./docs/api_reference/api.json

Guiding Principles of REST

1.Client–server – By separating the user interface concerns from the data storage concerns, we improve the portability of the user interface across multiple platforms and improve scalability by simplifying the server components.

2.Stateless – Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.

3.Cacheable – Cache constraints require that the data within a response to a request be implicitly or explicitly labeled as cacheable or non-cacheable. If a response is cacheable, then a client cache is given the right to reuse that response data for later, equivalent requests.

4.Uniform interface – By applying the software engineering principle of generality to the component interface, the overall system architecture is simplified and the visibility of interactions is improved. In order to obtain a uniform interface, multiple architectural constraints are needed to guide the behavior of components. REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.

5.Layered system – The layered system style allows an architecture to be composed of hierarchical layers by constraining component behavior such that each component cannot “see” beyond the immediate layer with which they are interacting.

6.Code on demand (optional) – REST allows client functionality to be extended by downloading and executing code in the form of applets or scripts. This simplifies clients by reducing the number of features required to be pre-implemented.

OAuth 2.0

OAuth2解决问题域和场景:

1.开放系统间授权

社交联合登录 开放API平台

2.现代微服务安全

单页浏览器App(HTML5/JS/无状态) 无线原生App 服务器端WebApp 微服务和API间调用

3.企业内部应用认证授权(IAM/SSO)

什么是OAuth 2.0

1.用于REST/APIs的代理授权框架(delegated authorization framework);

2.基于令牌Token的授权,在无需暴露用户密码的情况下,使应用能获取对用户数据的有限访问权限;

3.解耦认证和授权;

4.事实上的标准安全框架,支持多种用例场景;

• 服务器端WebApp

• 浏览器单页SPA

• 无线/原生App

• 服务器对服务器之间

OAuth令牌类型

  • 授权码(Authorization Code Token)
    仅用于授权码授权类型,用于交换获取访问令牌和刷新令牌

  • 刷新令牌(Refresh Token)
    用于去授权服务器获取一个新的访问令牌

  • Bearer Token:
    不管谁拿到Token都可以访问资源,像现钞

  • 访问令牌(Access Token)
    用于代表一个用户或服务直接去访问受保护的资源

  • Proof of Possession(PoP) Token
    可以校验client是否对Token有明确的拥有权

Cookbook

  • OAuth2 in Action
    https://www.manning.com/books/ oauth-2-in-action

  • OAuth 2.0 Cookbook
    https://www.packtpub.com/virtualization-and-cloud/oauth-20-cookbook
    https://tools.ietf.org/html/rfc6749

  • 阮一峰:理解OAuth 2.0: http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

  • 传统Web应用中的身份验证技术: http://insights.thoughtworkers.org/traditional-web-app-authentication/




本博客所有文章采用的授权方式为 自由转载-非商用-非衍生-保持署名 ,转载请务必注明出处,谢谢。
声明:
本博客欢迎转发,但请保留原作者信息!
博客地址:邱文奇(qiuwenqi)的博客;
内容系本人学习、研究和总结,如有雷同,实属荣幸!
阅读次数:

文章评论

comments powered by Disqus


章节列表