技术控

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

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

[复制链接]
放弃治疗 发表于 2016-10-3 22:43:23
172 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:
  [code]@RestController
public class HelloController {

    @RequestMapping("/")
    public String home() {
        return "hello";
    }
}[/code]   Execute: http -v localhost:8080
  [code]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.1

hello[/code]  2. Take Advantage of Automatic POJO to JSON Conversion

  Spring Boot automatically converts your POJOs (plain old Java classes) to JSON for you!
  [code]@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;
    }
}[/code]   Execute: http -v localhost:8080
  [code]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"
}[/code]  3. Use Dependency Injection With Autowired Services

  Autowiring services enables abstracting out business logic without having complex setup, configuration, or instantiation of Java Objects.
  [code]@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 {

    @Autowired
    HelloService helloService;

    @RequestMapping("/")
    public ApiResponse home(HttpServletRequest req) {
        String greeting = helloService.getGreeting(req);
        return new ApiResponse("SUCCESS", "Hello " + greeting);
    }
}[/code]   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
  [code]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"
}[/code]   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
  [code]http -v -f POST localhost:8080/oauth/token \
Origin:http://localhost:8080 \
grant_type=password \
username= \
password=[/code]  Response:
  [code]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"
}[/code]  Once that’s done, save the Access Token for use with our application:
  [code]ACCESS_TOKEN=eyJraWQiOiJSOTJTQkhKQzFVNERBSU1HUTNNSE9HVk1YIiwic3R0IjoiYWNjZXNzIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiIzVFhQZ01Ld0NiQTk1VEp6VzBXTzRWIiwiaWF0IjoxNDY1OTUyMzgzLCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy82dkZUNEFSZldDbXVIVlY4Vmt0alRvIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy8zcVlHbUl6VWh4UEtZTzI4a04wSWJSIiwiZXhwIjoxNDY1OTU1OTgzLCJydGkiOiIzVFhQZ0owckkwckFTZUU4SmtmN1NSIn0.o_pIHZVDZWogNuhJN2dmG4UKxACoWFxpRpp5OCyh6C4[/code]  Now, let’s hit our application again with authentication:
  [code]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"
}[/code]  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:
  [code]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.1

hello0[/code]   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:
  [code]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.1

hello1[/code]  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:
  [code]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.1

hello2[/code]  We are redirected to /login since we are unauthenticated. If I use my access token as before, it looks like this:
  [code]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.1

hello3[/code]  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:
  [code]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.1

hello4[/code]  If we look at the “happy path,” all is well:
  [code]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.1

hello5[/code]   What if we don’t have the Custom-Header header?
  [code]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.1

hello6[/code]   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.
  [code]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.1

hello7[/code]  Let’s look at the response now:
  [code]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.1

hello8[/code]   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-1 (principles,difficult,developer,including,recently)

友荐云推荐




上一篇:Query DynamoDB Items with DynamoDBMapper
下一篇:Runtime Introspection of Flow Types in JS
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

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

返回顶部 返回列表