The Security of interface services has always been a problem that programmers pay more attention to, and there are many mature Security frameworks, one of which is the integration of Spring Security and OAuth2. In ApiBoot, the two Security frameworks are automatically integrated through code encapsulation and automatic configuration.

Blog post: blog.yuqiyu.com/apiboot-sec…

ApiBoot Security OAuth Introduction

ApiBoot Security OAuth is a component of ApiBoot open source project, internal through the SpringBoot AutoConfiguration integration of Spring Security, OAuth2, and support a variety of storage methods, such as: Memory, database (JDBC), Redis, etc., use the configuration file to replace the code intrusive integration method, improve the development efficiency, reduce non-business cumbersome code, but also this relatively high scalability.

  • Api-boot-plugins, api-boot-autoconfigure: gitee.com/minbox-proj…

  • IO /zh-cn/docs/…

  • ApiBoot OAuth API Boot.minbot. IO /zh-cn/docs/…

Create a project

Create a SpringBoot project named apiboot-security-Oauth-zero-code-integration using the Idea development tool.

Add ApiBoot unified version dependency

Before adding the dependency we need to add the unified version of the ApiBoot dependency to our project’s POM.xml file as follows:

<! ApiBoot unified version dependency -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.minbox.framework</groupId>
            <artifactId>api-boot-dependencies</artifactId>
            <version>2.1.5. RELEASE</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>
Copy the code

Add the ApiBoot Security OAuth dependency

After adding the version dependency, we continue to add the ApiBoot Security OAuth dependency to the POM.xml file as follows:

<dependencies>
  <! --SpringBoot Web-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <! --ApiBoot Security Oauth-->
  <dependency>
    <groupId>org.minbox.framework</groupId>
    <artifactId>api-boot-starter-security-oauth-jwt</artifactId>
  </dependency>
</dependencies>
Copy the code

Configure the ApiBoot Security user list

ApiBoot Security supports the memory configuration user list by default, which is used to integrate OAuth2’s password authorization mode (grant_type=password). We need to add the relevant configuration to the application.yml configuration file, as shown below:

spring:
  application:
    name: apiboot-security-oauth-first-application
server:
  port: 9090
ApiBoot configuration
api:
  boot:
    ApiBoot Security configuration
    security:
      Configure the memory user list
      users:
        - username: hengboy
          password: 123456
        - username: yuqiyu
          password: 123123
Copy the code

You can use the api.boot.security.users parameter to configure multiple users. For each user, you can configure username, password, roles, Can view the org. Minbox. Framework. API. The boot. Autoconfigure. Security. ApiBootSecurityProperties source class for details.

  • usernameConfiguration:Spring SecurityUser name.
  • passwordConfiguration:Spring SecurityPassword of the user.
  • rolesConfiguration:Spring SecurityList of authorized roles corresponding to the user. Multiple roles can use English half corners.Separate, or use-Mode configuration.

Run the test

We started the chapter project with XxxApplication.

Test point: Get AccessToken

After the project runs successfully, let’s first test if we can get AccessToken.

Curl method:

➜ ~ curl -x POST ApiBoot: ApiBootSecret @ localhost: 9090 / request/token-d "grant_type=password&username=hengboy&password=123456"
{"access_token":"f16202f7-ab8c-41ae-86be-e314aebe82ff"."token_type":"bearer"."refresh_token":"93c74812-ec5b-4676-8378-b68e4c1751ae"."expires_in": 3297,"scope":"api"}
Copy the code

Obtained from PostMan:

If you have some experience integrating Spring Security with OAuth2, you should know that grant_type is one of the authorization methods provided in OAuth2. The parameters username and password are the corresponding Spring Security username and password after integration, which is one of the user information in the user list configured in the application. Yml configuration file api.boot.security.users.

The AccessToken can be obtained directly by testing the Curl and PostMan above.

Test point: Obtain the current user information

ApiBoot Security OAuth obtains the current user information in the same way that Spring Security does, by injecting the java.security.Principal interface.

package org.minbox.chapter.apiboot.security.oauth.first.application;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/** * Login user information **@authorHeng Yu Teenager */
@RestController
@RequestMapping(value = "/api/user")
public class UserController {

    /** * Get the current logged-in user information * annotations provided by Spring Security {@linkPreAuthorize} Verifies role * *@param principal {@link Principal}
     * @return {@link Principal#getName()}
     */
    @GetMapping
    @PreAuthorize("hasRole('api')")
    public String info(Principal principal) {
        returnprincipal.getName(); }}Copy the code

Note: ApiBoot Security OAuth default permission to intercept the path when/API /**, so we configured/API /user as a path prefix on the test controller. Please visit the ApiBoot official website documentation ApiBoot Security usage documentation

Our way through the Curl http://localhost:9090/api/user interface effect is as follows:

➜ ~ curl http://localhost:9090/api/user - H'Authorization: Bearer d73e86a8-892f-42c1-bc95-04aedfe97828'
hengboy
Copy the code

AccessToken access to the/API /user path is generated by user Hengboy, so the interface returns the hengboy user name.

Type on the blackboard and underline

ApiBoot Security OAuth is extremely simple to complete the integration of Spring Security and OAuth2, using the memory mode does not need to configure a line of code to complete the automatic integration.

Code sample

The sample source code for this article can be obtained from the directory springboot2. x/ APIboot-security-oauth-first-application:

  • Gitee:Gitee.com/hengboy/spr…

Author’s personal blog uses the open source framework ApiBoot to help you become an Api service architect