background

Recently, we are working on the security and authentication of platform API. Interface security and authentication are very important in production activities. The most popular authentication method is Oauth2. Let’s take a quick look at the Oauth2 process with SpringBoot’s security dependencies.

A simple understanding of Oauth2

What is?

Is an authorization mechanism used to authorize third-party applications to obtain user data

There are four ways to delegate

  • Authorization-code

    In this mode, the authorization code is transmitted through the front end and the token is stored in the back end. This mode is mainly applicable to Web applications with backends.

  • Implicit

    This way without authorization code intermediate step, very insecure. Mainly suitable for pure front-end applications.

  • Password type

    This method requires users to highly trust third-party applications, which is risky.

  • The client credentials

    This mode applies to the application between servers. It is about interface security authentication.

Client credentials

This method is the certification method that we mainly practice today. If you are in the usual open, often with the external third party docking, you should be familiar with this certification method. During the development of wechat, we usually go to the official server of wechat official account for authentication to obtain access token. Then we request the relevant wechat interface, and we need to bring the access token to have access.

SpringBoot Oatuh2 simple practice

Now that we have a brief introduction to Oauth2, let’s do a quick implementation.

General idea steps:

  1. The introduction of dependent dependencies
  2. configuration
    • Authentication Service Information
    • Resource Service Information
  3. validation
    • Obtain an access token
    • Access to the resource

Pom

To enable Oauth2 authentication, we must introduce SpringBoot security dependencies and Spring’s Oauth2 dependencies

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.security.oauth</groupId>
      <artifactId>spring-security-oauth2</artifactId>
    </dependency>
Copy the code

After security authentication dependencies are introduced, SpringBoot protects all resources on the resource server by default.

Authorization Service Config – Authorization Service configuration

The authentication service configuration includes the following three aspects:

  1. Define security constraints for the Token endpoint

    Main configuration: whether to allow the client to log in in the Form of Form, define the encryption mode of password, etc

  2. Define client details

    Client information includes client information storage mode (memory or database) and authentication information, including client_id, client_secret, grant_type, and scope

  3. Define authorization and token endpoint and token service.

    You can configure the endpoint of authorization and the token storage mode

Authentication service configuration is as follows :(in this practice, in line with the configuration principle of saving what can be saved)

@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {

    /** * Configures configurations related to security constraints *@paramSecurity defines security constraints * on token endpoints@throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        Client_id and client_secret can be used for login in form form. For details, see wechat access Token
        security.allowFormAuthenticationForClients();
    }

    /** * Configure client details *@paramClients Defines the configurator for the client details service. You can initialize client details or just reference existing storage. *@throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            // client_id
            .withClient("gold")
            // Authorization mode
            .authorizedGrantTypes("client_credentials")
            // Scope of authorization
            .scopes("write")
            // client_secret
            .secret("{noop}123456");

    }

    / * * * *@paramEndpoints define authorization and token endpoints and token services. *@throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints); }}Copy the code

Note that the password configuration, need to configure encryption, this practice is not any encryption.

Relevant information, see: DelegatingPasswordEncoder or PasswordEncoderFactories

Resource Service Config – Resource Service configuration

Resource service configuration includes the following two aspects:

  1. Security configuration for resource services

    You can configure the resource ID, stateless – whether the resource only allows token-based authentication, and token storage

  2. Http Security Configuration

    This is where our protected API is configured

Resource configuration:

API:

@RestController
@AllArgsConstructor
public class ResController {

    @GetMapping("/res/{id}")
    public String testOauth(@PathVariable String id) {
        return "Get the resource "+ id; }}Copy the code

Resource Service configuration:

@Configuration
@EnableResourceServer
public class MyResourceServerConfigurer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        super.configure(resources);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/res/**").authenticated(); }}Copy the code

The configuration is complete

We have completed the basic configuration of Oauth2 for SpringBoot.

Client information:

  • client_id : gold
  • client_secret : 123456
  • scopes : write
  • grant_type : client_credentials

Next, let’s verify that our configuration works.

The following request is made in Postman. Base_url is the set global variable, which is actually http://127.0.0.1:8080

Direct request

When we request it directly, the application returns unauthorized and inaccessible:

Get the access token

Springboot oauth The default endpoint for obtaining the token is /oauth/token

As you can see from the request results, we obtained the access_token and the refresh time was 43,199 seconds, or 12 hours.

Request a protected resource

As a result, we successfully accessed the protected resource using the Access token.

summary

This article briefly introduces what Oauth2 is and authorization, want to know more about Oauth2 students, you can go to Ruan Yifeng teacher blog to learn about it. After by SpringBoot simple implementation of a client certificate authentication, the configuration of the main key point is to understand the resource server configuration (ResourceServerConfigurer) and authentication server configuration (AuthorizationServerConfigurer). Let’s do it, boys and girls!

Personal level is limited, welcome to correct, exchange oh ~~~

The demo:Github.com/goldpumpkin…

Reference:

  1. spring-security-oauth
  2. Understand the 2.0