参考文档:docs.spring.io/spring-secu…
系列文章:
SpringBoot 集成 OAuth2 系列一(最简单配置篇)
SpringBoot 集成 OAuth2 系列二(password篇)
springBoot集成oAuth2,系列三(UserDetailsService篇)
springBoot集成oAuth2,系列四(前后端分离web页面中使用oauth2跨域问题篇)
springBoot集成oAuth2,系列五(下载等location.href 如何使用token)
springBoot集成oAuth2,系列六(如何获取refresh_token)
springBoot集成oAuth2,系列七(根据refresh_token获取access_token)
前言
此篇文章是springboot 集成oauth2 基础篇,方便理解怎么简单配置就能使用oauth2的功能,有关实际项目使用可以看后续系列文章
效果如下:
1.直接访问api接口
curl --location --request GET 'http://127.0.0.1:8080/whoami?name=mayanze'
2.获取token(有点小抽象,官方文档例子)
curl --location --request POST 'http://first-client:noonewilleverguess@localhost:8080/oauth/token?scope=any&grant_type=client_credentials'
3.拿token访问api接口
curl --location --request GET 'http://127.0.0.1:8080/whoami?name=mayanze' \
--header 'Authorization: Bearer dfVidwI31Nyzy-3dOXH8M82Xr6k'
代码实现
代码实现很简单,也可以参考完整代码:gitee.com/mayanze123/… 1.引入OAuth依赖(注意版本)
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.5.2</version>
</dependency>
2.启动类加两注解
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);
}
}
3.配置文件application.yml
security:
oauth2:
client:
client-id: first-client
client-secret: noonewilleverguess
4.写个接口类
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;
}
}