Reference document: docs.spring. IO /spring-secu…

Complete code: gitee.com/mayanze123/…

Series of articles:

SpringBoot integration with OAuth2 Series 1 (simplest configuration)

SpringBoot integrated OAuth2 series 2

SpringBoot integrated oAuth2, Series 3 (UserDetailsService)

SpringBoot integrates oAuth2, Series 4 (Cross-domain issues of using oAuth2 in Front and back End Separation web pages)

preface

This article is the foundation of springBoot integration oAuth2, easy to understand how simple configuration can use oAuth2 functionality, see the actual project use of the article series

The effect is as follows:

1. Access the API directly

Curl, the location, request GET 'http://127.0.0.1:8080/whoami? name=mayanze'Copy the code

2. Obtain the token(a little abstract, official document example)

curl --location --request POST 'http://first-client:noonewilleverguess@localhost:8080/oauth/token? scope=any&grant_type=client_credentials'Copy the code

3. Use the token to access the API

Curl, the location, request GET 'http://127.0.0.1:8080/whoami? name=mayanze' \ --header 'Authorization: Bearer dfVidwI31Nyzy-3dOXH8M82Xr6k'Copy the code

Code implementation

Code implementation is very simple, also can refer to the complete code: gitee.com/mayanze123/… 1. Introducing OAuth dependencies (note version)

<dependency> <groupId>org.springframework.security.oauth.boot</groupId> < artifactId > spring ws-security - oauth2 - autoconfigure < / artifactId > < version > 2.5.2 < / version > < / dependency >Copy the code

2. Add two annotations to the startup class

package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @EnableAuthorizationServer @EnableResourceServer @SpringBootApplication public class Oauth2BootApplication { public static void main(String[] args) { SpringApplication.run(Oauth2BootApplication.class, args); }}Copy the code

3. Configure the file application.yml

security:
  oauth2:
    client:
      client-id: first-client
      client-secret: noonewilleverguess
Copy the code

4. Write an interface class

package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SimpleController { @GetMapping("/whoami") public String whoami(String name) { return name; }}Copy the code