请选择 进入手机版 | 继续访问电脑版

技术控

    今日:16| 主题:54650
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] 5 Practical Tips for Building Your Spring Boot API

[复制链接]
放弃治疗 发表于 2016-10-3 22:43:23
235 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Building Identity Management, including authentication and authorization? Try Stormpath! Our REST API and robust Java SDK support can eliminate your security risk and can be implemented in minutes. Sign up , and never build auth again!
   Every API developer is looking for ways to manage their application more securely, without sacrificing speed or ease of implementing new features. To that end, we recently updated the core Stormpath product – our REST API – to Spring Boot. Along the way, we utilized a number of critical efficiencies that would be of value to anyone developing an API using Spring Boot.
  Many teams find it difficult to manage authentication and access control to their APIs, so we want to share a few architectural principles and tips from our migration to make it easier to manage your Spring Boot API.
  Note: Below we use the command line tool httpie (https://github.com/jkbrzt/httpie) to exercise the examples.
  1. Use the @RestController Annotation

   Using @RestController (instead of simply @Controller ) ensures that you will return a Java Object rather than a reference to an HTML template. Like this:
  1. @RestController
  2. public class HelloController {
  3.     @RequestMapping("/")
  4.     public String home() {
  5.         return "hello";
  6.     }
  7. }
复制代码
  Execute: http -v localhost:8080
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello
复制代码
2. Take Advantage of Automatic POJO to JSON Conversion

  Spring Boot automatically converts your POJOs (plain old Java classes) to JSON for you!
  1. @RestController
  2. public class HelloController {
  3.     @RequestMapping("/")
  4.     public ApiResponse home() {
  5.         return new ApiResponse("SUCCESS", "hello");
  6.     }
  7. }
  8. public class ApiResponse {
  9.     private String status;
  10.     private String message;
  11.     public ApiResponse(String status, String message) {
  12.         this.status = status;
  13.         this.message = message;
  14.     }
  15.     public String getStatus() {
  16.         return status;
  17.     }
  18.     public String getMessage() {
  19.         return message;
  20.     }
  21. }
复制代码
  Execute: http -v localhost:8080
  1. HTTP/1.1 200 OK
  2. Content-Type: application/json;charset=UTF-8
  3. Date: Tue, 14 Jun 2016 23:54:19 GMT
  4. Server: Apache-Coyote/1.1
  5. Transfer-Encoding: chunked
  6. {
  7.     "message": "hello",
  8.     "status": "SUCCESS"
  9. }
复制代码
3. Use Dependency Injection With Autowired Services

  Autowiring services enables abstracting out business logic without having complex setup, configuration, or instantiation of Java Objects.
  1. @Service
  2. public class HelloService {
  3.     public String getGreeting(HttpServletRequest req) {
  4.         String greeting = "World";
  5.         Account account = AccountResolver.INSTANCE.getAccount(req);
  6.         if (account != null) {
  7.             greeting = account.getGivenName();
  8.         }
  9.         return greeting;
  10.     }
  11. }
  12. @RestController
  13. public class HelloController {
  14.     @Autowired
  15.     HelloService helloService;
  16.     @RequestMapping("/")
  17.     public ApiResponse home(HttpServletRequest req) {
  18.         String greeting = helloService.getGreeting(req);
  19.         return new ApiResponse("SUCCESS", "Hello " + greeting);
  20.     }
  21. }
复制代码
  This example uses Stormpath to return a personalized greeting once you are authenticated. To exercise this you’ll first need to setup a Stormpath account as outlined here . If you followed the instructions and put your Stormpath API Key file in the standard location (~/.stormpath/apiKey.properties) there’s nothing else to do!
   Fire up the app and execute this: http -v localhost:8080
  1. HTTP/1.1 200 OK
  2. Content-Type: application/json;charset=UTF-8
  3. Date: Wed, 15 Jun 2016 00:56:46 GMT
  4. Server: Apache-Coyote/1.1
  5. Transfer-Encoding: chunked
  6. {
  7.     "message": "Hello World",
  8.     "status": "SUCCESS"
  9. }
复制代码
  Next, we need to authenticate so we can move forward with our example, so we’ll exercise Stormpath’s built in OAuth 2.0 functionality to authenticate and get back a personalized message. Make sure you’ve created a user for your Stormpath application in the Admin Console. For more information on Stormpath’s OAuth support in the Java SDK and its integrations, check out our Java Product Documentation
  1. http -v -f POST localhost:8080/oauth/token \
  2. Origin:http://localhost:8080 \
  3. grant_type=password \
  4. username=<email address of the user you setup> \
  5. password=<password of the user you setup>
复制代码
Response:
  1. HTTP/1.1 200 OK
  2. Cache-Control: no-store
  3. Content-Length: 938
  4. Content-Type: application/json;charset=UTF-8
  5. Date: Wed, 15 Jun 2016 00:59:43 GMT
  6. Pragma: no-cache
  7. Server: Apache-Coyote/1.1
  8. {
  9.     "access_token": "eyJraWQiOiJSOTJTQkhKQzFVNERBSU1HUTNNSE9HVk1YIiwic3R0IjoiYWNjZXNzIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiIzVFhQZ01Ld0NiQTk1VEp6VzBXTzRWIiwiaWF0IjoxNDY1OTUyMzgzLCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy82dkZUNEFSZldDbXVIVlY4Vmt0alRvIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy8zcVlHbUl6VWh4UEtZTzI4a04wSWJSIiwiZXhwIjoxNDY1OTU1OTgzLCJydGkiOiIzVFhQZ0owckkwckFTZUU4SmtmN1NSIn0.o_pIHZVDZWogNuhJN2dmG4UKxACoWFxpRpp5OCyh6C4",
  10.     "expires_in": 3600,
  11.     "refresh_token": "eyJraWQiOiJSOTJTQkhKQzFVNERBSU1HUTNNSE9HVk1YIiwic3R0IjoicmVmcmVzaCIsImFsZyI6IkhTMjU2In0.eyJqdGkiOiIzVFhQZ0owckkwckFTZUU4SmtmN1NSIiwiaWF0IjoxNDY1OTUyMzgzLCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy82dkZUNEFSZldDbXVIVlY4Vmt0alRvIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy8zcVlHbUl6VWh4UEtZTzI4a04wSWJSIiwiZXhwIjoxNDcxMTM2MzgzfQ.mJBfCgv4Sdnw7Ubzup7CZ1xdAIC9iO31AJE3NMmp05E",
  12.     "token_type": "Bearer"
  13. }
复制代码
Once that’s done, save the Access Token for use with our application:
  1. ACCESS_TOKEN=eyJraWQiOiJSOTJTQkhKQzFVNERBSU1HUTNNSE9HVk1YIiwic3R0IjoiYWNjZXNzIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiIzVFhQZ01Ld0NiQTk1VEp6VzBXTzRWIiwiaWF0IjoxNDY1OTUyMzgzLCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy82dkZUNEFSZldDbXVIVlY4Vmt0alRvIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy8zcVlHbUl6VWh4UEtZTzI4a04wSWJSIiwiZXhwIjoxNDY1OTU1OTgzLCJydGkiOiIzVFhQZ0owckkwckFTZUU4SmtmN1NSIn0.o_pIHZVDZWogNuhJN2dmG4UKxACoWFxpRpp5OCyh6C4
复制代码
Now, let’s hit our application again with authentication:
  1. http -v localhost:8080 Authorization:"Bearer $ACCESS_TOKEN"
  2. HTTP/1.1 200 OK
  3. Content-Type: application/json;charset=UTF-8
  4. Date: Wed, 15 Jun 2016 01:05:35 GMT
  5. Server: Apache-Coyote/1.1
  6. Transfer-Encoding: chunked
  7. {
  8.     "message": "Hello Micah",
  9.     "status": "SUCCESS"
  10. }
复制代码
Now, we get the personalized response from our Service that the Controller has access to thanks to dependency injection.
  4. Layer in Spring Security

  Spring Security adds an authorization layer to Spring applications that makes it really easy to determine who should have access to what. It uses a declarative configuration syntax and includes annotations to limit who can access methods based on group membership and fine-grained permissions.
   If you’re interested in learning more, I’ve also written an in-depth Stormpath + Spring Security tutorial . We also have a great tutorial that takes you from zero to full functioning Spring Security + Spring Boot WebMVC app in our open-source Java SDK project . Find the tutorial documentation here .
  By default everything is locked down in Spring Security and the Stormpath Spring Security integration is a great example that follows this convention. To try out Spring Security with Stormpath, you simply need to apply the Stormpath integration in a configuration like so:
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello0
复制代码
  http.apply(stormpath()) is all that’s needed to configure the Stormpath Spring Security integration. The next two lines allow unauthenticated access to the “/” endpoint.
  Let’s take a look at how this impacts a method in our controller:
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello1
复制代码
In this case, there’s no need to perform the null check on the account since we know that the only way to get into this method if after authentication. For example:
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello2
复制代码
We are redirected to /login since we are unauthenticated. If I use my access token as before, it looks like this:
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello3
复制代码
5. Uniform Error Handling

  Good API design dictates that your API returns a common response, even when something goes wrong. This makes parsing and marshalling JSON into Java Objects easier and more reliable.
   Let’s try out an example. Here, we require a header called: Custom-Header . If that header is not present, an exception is thrown:
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello4
复制代码
If we look at the “happy path,” all is well:
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello5
复制代码
  What if we don’t have the Custom-Header header?
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello6
复制代码
  So, what’s wrong with this? For one, it doesn’t conform to the response format we’ve already established. Also, it results in a 500 (Internal Server Error) error, which is never good.
  Fortunately, Spring Boot makes this an easy fix. All we need to do is add an exception handler. No other code changes are required.
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello7
复制代码
Let’s look at the response now:
  1. HTTP/1.1 200 OK
  2. Content-Length: 5
  3. Content-Type: text/plain;charset=UTF-8
  4. Date: Tue, 14 Jun 2016 23:55:16 GMT
  5. Server: Apache-Coyote/1.1
  6. hello8
复制代码
  Now we have the correct response, 400 (Bad Request) . We also have the response in the same format as successful responses.
  Bonus Tip: Try Stormpath

   Stormpath offers an advanced, developer-centric Identity service that includes both authentication and authorization and can be implemented in minutes. The Stormpath REST API lets developers quickly and easily build a wide variety of user management functions they would otherwise have to code themselves, including:
  
       
  • Sophisticated authorization support , with caching for maximum performance   
  • Token authentication and revocation with JSON Web Tokens and OAuth2   
  • Native support for multi-tenant applications , with pre-built partitioning of customer data   
  • Comprehensive documentation and commitment to customer care —even for free developer accounts   
  • Robust and highly idiomatic SDKs  
   Building Identity Management, including authentication and authorization? Try Stormpath! Our REST API and robust Java SDK support can eliminate your security risk and can be implemented in minutes. Sign up , and never build auth again!
   

5 Practical Tips for Building Your Spring Boot API

5 Practical Tips for Building Your Spring Boot API-1-技术控-principles,difficult,developer,including,recently



上一篇:Query DynamoDB Items with DynamoDBMapper
下一篇:Runtime Introspection of Flow Types in JS
*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )

© 2001-2017 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表