日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

5个构建Spring Boot API的实用技巧

發布時間:2023/12/3 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 5个构建Spring Boot API的实用技巧 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

建筑物身份管理,包括身份驗證和授權? 嘗試Stormpath! 我們的REST API和強大的Java SDK支持可以消除您的安全風險,并且可以在幾分鐘內實現。 注冊 ,再也不會建立auth了!

每個API開發人員都在尋找一種更安全地管理其應用程序,而又不犧牲速度或易于實現新功能的方法。 為此,我們最近將核心Stormstorm產品(我們的REST API)更新為Spring Boot。 在此過程中,我們利用了許多關鍵效率,這對于任何使用Spring Boot開發API的人來說都是有價值的。

許多團隊發現很難管理對其API的身份驗證和訪問控制,因此我們希望分享遷移中的一些體系結構原理和技巧,以簡化管理Spring Boot API的過程。

注意:下面我們使用命令行工具httpie(https://github.com/jkbrzt/httpie)來練習示例。

1.使用@RestController注釋

使用@RestController (而不是簡單地@Controller )可確保您將返回Java對象,而不是對HTML模板的引用。 像這樣:

@RestController public class HelloController {@RequestMapping("/")public String home() {return "hello";} }

執行: http -v localhost:8080

HTTP/1.1 200 OK Content-Length: 5 Content-Type: text/plain;charset=UTF-8 Date: Tue, 14 Jun 2016 23:55:16 GMT Server: Apache-Coyote/1.1hello

2.利用自動POJO到JSON轉換的優勢

Spring Boot會自動為您將POJO(普通的舊Java類)轉換為JSON!

@RestController public class HelloController {@RequestMapping("/")public ApiResponse home() {return new ApiResponse("SUCCESS", "hello");} }public class ApiResponse {private String status;private String message;public ApiResponse(String status, String message) {this.status = status;this.message = message;}public String getStatus() {return status;}public String getMessage() {return message;} }

執行: http -v localhost:8080

HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Date: Tue, 14 Jun 2016 23:54:19 GMT Server: Apache-Coyote/1.1 Transfer-Encoding: chunked{"message": "hello","status": "SUCCESS" }

3.對自動有線服務使用依賴注入

自動裝配服務可以抽象出業務邏輯,而無需進行復雜的Java對象設置,配置或實例化。

@Service public class HelloService {public String getGreeting(HttpServletRequest req) {String greeting = "World";Account account = AccountResolver.INSTANCE.getAccount(req);if (account != null) {greeting = account.getGivenName();}return greeting;} }@RestController public class HelloController {@AutowiredHelloService helloService;@RequestMapping("/")public ApiResponse home(HttpServletRequest req) {String greeting = helloService.getGreeting(req);return new ApiResponse("SUCCESS", "Hello " + greeting);} }

一旦您通過身份驗證,此示例將使用Stormpath返回個性化問候。 為此,您首先需要按照此處概述的方法設置一個Stormpath帳戶。 如果您按照說明進行操作,并將Stormpath API密鑰文件放在標準位置(~/.stormpath/apiKey.properties)則無需執行其他任何操作!

啟動應用程序并執行以下命令: http -v localhost:8080

HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Date: Wed, 15 Jun 2016 00:56:46 GMT Server: Apache-Coyote/1.1 Transfer-Encoding: chunked{"message": "Hello World","status": "SUCCESS" }

接下來,我們需要進行身份驗證,以便繼續進行示例,因此,我們將使用Stormpath內置的OAuth 2.0功能來進行身份驗證并獲取個性化消息。 確保已在管理控制臺中為Stormpath應用程序創建了一個用戶。 有關Java SDK及其集成中Stormpath的OAuth支持的更多信息,請查看我們的Java產品文檔

http -v -f POST localhost:8080/oauth/token \ Origin:http://localhost:8080 \ grant_type=password \ username=<email address of the user you setup> \ password=<password of the user you setup>

響應:

HTTP/1.1 200 OK Cache-Control: no-store Content-Length: 938 Content-Type: application/json;charset=UTF-8 Date: Wed, 15 Jun 2016 00:59:43 GMT Pragma: no-cache Server: Apache-Coyote/1.1{"access_token": "eyJraWQiOiJSOTJTQkhKQzFVNERBSU1HUTNNSE9HVk1YIiwic3R0IjoiYWNjZXNzIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiIzVFhQZ01Ld0NiQTk1VEp6VzBXTzRWIiwiaWF0IjoxNDY1OTUyMzgzLCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy82dkZUNEFSZldDbXVIVlY4Vmt0alRvIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy8zcVlHbUl6VWh4UEtZTzI4a04wSWJSIiwiZXhwIjoxNDY1OTU1OTgzLCJydGkiOiIzVFhQZ0owckkwckFTZUU4SmtmN1NSIn0.o_pIHZVDZWogNuhJN2dmG4UKxACoWFxpRpp5OCyh6C4","expires_in": 3600,"refresh_token": "eyJraWQiOiJSOTJTQkhKQzFVNERBSU1HUTNNSE9HVk1YIiwic3R0IjoicmVmcmVzaCIsImFsZyI6IkhTMjU2In0.eyJqdGkiOiIzVFhQZ0owckkwckFTZUU4SmtmN1NSIiwiaWF0IjoxNDY1OTUyMzgzLCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy82dkZUNEFSZldDbXVIVlY4Vmt0alRvIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy8zcVlHbUl6VWh4UEtZTzI4a04wSWJSIiwiZXhwIjoxNDcxMTM2MzgzfQ.mJBfCgv4Sdnw7Ubzup7CZ1xdAIC9iO31AJE3NMmp05E","token_type": "Bearer" }

完成后,保存訪問令牌以用于我們的應用程序:

ACCESS_TOKEN=eyJraWQiOiJSOTJTQkhKQzFVNERBSU1HUTNNSE9HVk1YIiwic3R0IjoiYWNjZXNzIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiIzVFhQZ01Ld0NiQTk1VEp6VzBXTzRWIiwiaWF0IjoxNDY1OTUyMzgzLCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy82dkZUNEFSZldDbXVIVlY4Vmt0alRvIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy8zcVlHbUl6VWh4UEtZTzI4a04wSWJSIiwiZXhwIjoxNDY1OTU1OTgzLCJydGkiOiIzVFhQZ0owckkwckFTZUU4SmtmN1NSIn0.o_pIHZVDZWogNuhJN2dmG4UKxACoWFxpRpp5OCyh6C4

現在,讓我們再次通過身份驗證訪問我們的應用程序:

http -v localhost:8080 Authorization:"Bearer $ACCESS_TOKEN"HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Date: Wed, 15 Jun 2016 01:05:35 GMT Server: Apache-Coyote/1.1 Transfer-Encoding: chunked{"message": "Hello Micah","status": "SUCCESS" }

現在,由于依賴注入,我們從服務中獲得了控制器可以訪問的個性化響應。

4. Spring Security中的層

Spring Security在Spring應用程序中添加了一個授權層,這使得確定誰應該有權訪問什么變得非常容易。 它使用聲明性配置語法,并包含注釋以限制誰可以訪問基于組成員身份和細粒度權限的方法。

如果您想了解更多信息,我還編寫了深入的Stormpath + Spring Security教程 。 我們還有一個很棒的教程,可以在開源Java SDK項目中將您從零帶到功能完整的Spring Security + Spring Boot WebMVC應用程序 。 在此處找到教程文檔。

默認情況下,所有內容都在Spring Security中被鎖定,并且Stormpath Spring Security集成是遵循此約定的一個很好的例子。 要嘗試使用帶有Stormpath的Spring Security,您只需要在如下配置中應用Stormpath集成:

@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.apply(stormpath()).and().authorizeRequests().antMatchers("/").permitAll();} }

http.apply(stormpath())是配置Stormpath Spring Security集成所需的全部。 接下來的兩行允許未經授權的訪問“/”端點。

讓我們看一下這如何影響控制器中的方法:

@RequestMapping("/restricted") public ApiResponse restricted(HttpServletRequest req) {// guaranteed to have account because of Spring Securityreturn new ApiResponse("SUCCESS", "Hello " + AccountResolver.INSTANCE.getAccount(req).getGivenName()); }

在這種情況下,無需對帳戶執行null檢查,因為我們知道,經過身份驗證后,進入該方法的唯一方法。 例如:

http localhost:8080/restrictedHTTP/1.1 302 Found Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Length: 0 Date: Wed, 15 Jun 2016 17:32:31 GMT Expires: 0 Location: http://localhost:8080/login

由于我們未經身份驗證,因此我們被重定向到/ login。 如果我像以前一樣使用訪問令牌,則如下所示:

http localhost:8080/restricted Authorization:"Bearer $ACCESS_TOKEN"HTTP/1.1 200 OK Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Type: application/json;charset=UTF-8 Date: Wed, 15 Jun 2016 17:34:34 GMT Expires: 0 Pragma: no-cache{"message": "Hello Micah","status": "SUCCESS" }

5.統一錯誤處理

良好的API設計表明,即使出現問題,您的API也會返回通用響應。 這使得將JSON解析和編組為Java對象變得更加容易和可靠。

讓我們嘗試一個例子。 在這里,我們需要一個標題: Custom-Header 。 如果該標頭不存在,則會引發異常:

@RequestMapping("/custom-header") public ApiResponse customHeader(HttpServletRequest req) throws MissingCustomHeaderException {String customHeader = req.getHeader("Custom-Header");if (customHeader == null) {throw new MissingCustomHeaderException("'Custom-Header' on the request is required.");}return new ApiResponse("SUCCESS", "Found Custom-Header: " + customHeader); }

如果我們看“幸福的道路”,一切都很好:

http localhost:8080/custom-header \Custom-Header:MyCustomValue \Authorization:"Bearer $ACCESS_TOKEN"HTTP/1.1 200 OK Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Type: application/json;charset=UTF-8 Date: Wed, 15 Jun 2016 22:28:47 GMT{"message": "Found Custom-Header: MyCustomValue","status": "SUCCESS" }

如果沒有Custom-Header標頭怎么辦?

http localhost:8080/custom-header Authorization:"Bearer $ACCESS_TOKEN"HTTP/1.1 500 Internal Server Error Cache-Control: no-cache, no-store, max-age=0, must-revalidate Connection: close Content-Type: application/json;charset=UTF-8 Date: Wed, 15 Jun 2016 22:34:13 GMT{"error": "Internal Server Error","exception": "com.stormpath.spring.boot.examples.controller.HelloController$MissingCustomHeaderException","message": "'Custom-Header' on the request is required.","path": "/custom-header","status": 500,"timestamp": 1466030053360 }

那么,這怎么了? 首先,它不符合我們已經建立的響應格式。 另外,它還會導致500 (Internal Server Error)錯誤,這永遠是不好的。

幸運的是,Spring Boot使此修復很容易。 我們需要做的就是添加一個異常處理程序。 無需其他代碼更改。

@ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MissingCustomHeaderException.class) public ApiResponse exception(MissingCustomHeaderException e) {return new ApiResponse("ERROR", e.getMessage()); }

現在讓我們看一下響應:

http localhost:8080/custom-header Authorization:"Bearer $ACCESS_TOKEN"HTTP/1.1 400 Bad Request Cache-Control: no-cache, no-store, max-age=0, must-revalidate Connection: close Content-Type: application/json;charset=UTF-8 Date: Wed, 15 Jun 2016 22:59:32 GMT{"message": "'Custom-Header' on the request is required.","status": "ERROR" }

現在我們有了正確的響應400 (Bad Request) 。 我們也有與成功回復相同格式的回復。

額外提示:嘗試Stormpath

Stormpath提供了以開發人員為中心的高級身份服務,其中包括身份驗證和授權,并且可以在幾分鐘內實現。 Stormpath REST API使開發人員可以快速輕松地構建他們自己必須編寫的各種用戶管理功能,包括:

  • 完善的授權支持 ,具有緩存功能,可實現最佳性能
  • 使用JSON Web令牌和OAuth2進行令牌身份驗證和吊銷
  • 對多租戶應用程序的本機支持,以及對客戶數據的預先構建的分區
  • 全面的文檔和對客戶服務的承諾-即使是免費的開發人員帳戶
  • 健壯且慣用的SDK

建筑物身份管理,包括身份驗證和授權? 嘗試Stormpath! 我們的REST API和強大的Java SDK支持可以消除您的安全風險,并且可以在幾分鐘內實現。 注冊 ,再也不會建立auth了!

翻譯自: https://www.javacodegeeks.com/2016/10/5-practical-tips-building-spring-boot-api.html

總結

以上是生活随笔為你收集整理的5个构建Spring Boot API的实用技巧的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。