MySQL+SpringBoot+OAuth2.0 配置

本贴最后更新于 1830 天前,其中的信息可能已经时移世异

OAuth2.0 规范

是微服务以及前后分离的趋势下产生的规范,用于客户端请求服务端资源,这里的客户端可以是一个前端项目或者是另一个服务端。简单来说就是端到端的请求。
下面简单讲一下使用步骤,我这里的 SpringBoot 的版本是当前最新版:2.1.4

MySQL 配置:

client_id: client_1
resource_ids: demo
client_secret: 123456
scope: select
authorized_grant_types: client_credentials
web_server_redirect_uri: null
authorities: client
access_token_validity: null
refersh_token_validity: null
additional_infomation: null,
autoapprove: 1

application.propertites 配置:

spring.datasource.url=jdbc:mysql://你的数据库ip:你的数据库端口?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=你的数据库用户名
spring.datasource.password=你的数据密码
server.port=你的项目监听端口

maven 配置:

<!-- SpringBoot基本配置 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- devtools 开发热部署 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
	<scope>runtime</scope>
</dependency>
<!-- SpringBoot 测试支持 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
<!-- 这两个是SpringBoot+OAuth2.0的核心配置,我这里的SpringBoot版本是2.1.4所以下面的两个版本需要对应一下 -->
<dependency>
	<groupId>org.springframework.security.oauth.boot</groupId>
	<artifactId>spring-security-oauth2-autoconfigure</artifactId>
	<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework.security.oauth</groupId>
	<artifactId>spring-security-oauth2</artifactId>
	<version>2.3.5.RELEASE</version>
</dependency>

这里的 OAuth2.0 核心配置需要注意,根据 2.1.4 版本的官方文档:
https://docs.spring.io/spring-boot/docs/2.1.4.RELEASE/reference/htmlsingle/#_authorization_server

Currently, Spring Security does not provide support for implementing an OAuth 2.0 Authorization Server. However, this functionality is available from theSpring Security OAuthproject, which will eventually be superseded by Spring Security completely. Until then, you can use the spring-security-oauth2-autoconfigure module to easily set up an OAuth 2.0 authorization server; see itsdocumentationfor instructions.

意思就是 Spring Security 不再提供 OAuth2.0 认证服务器的实现,转而由 Spring Security OAuth 项目实现。

SpringBoot 注解配置

启动类:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

ResourseServer 资源服务器配置,新建一个 RSConfig 类,内容如下:

/*
 * 资源服务器
 * */
@Configuration
@EnableResourceServer
public class RSConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and()
            .requestMatchers().anyRequest()
            .and()
            .anonymous()
            .and()
            .authorizeRequests()
            .antMatchers("/demo/**").authenticated();
    }
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("demo");
    }
}

这里就是配置/demo/下的任何请求都需要认证,并且将数据库的那一条记录的 resource_ids 里的 demo 注册为资源

AuthorizationServer 认证服务器配置,新建一个 ASConfig 类,内容如下:

/*
 * 认证服务器
 * */
@Configuration
@EnableAuthorizationServer
public class ASConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .tokenStore(new JdbcTokenStore(dataSource));
    }
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        //允许表单认证
        oauthServer.allowFormAuthenticationForClients();
    }
}

这里的 DataSource 就是 application.propertities 里配置的,SpringBoot 自动注入了,不用我们关心。

SpringSecurity 配置,新建一个 SecurityConfig,写入以下内容:

/*
 * Spring Security配置
 * */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/*").permitAll();
        }
    }
}

这里其实可以理解为 SpringSecurity 的拦截发生在 OAuth 之前,所以需要允许所有的/oauth/下的请求。

Controller,就是受保护的资源,新建一个 DemoController,内容如下:

@RestController
@RequestMapping("/demo")
public class DemoController {
    @RequestMapping("/hello")
    public String hello(){
        return "hello~~~~!";
    }
}

调试结果

  • 启动项目,可以看到如下启动信息:
    image.png
    /oauth/token,/oauth/token_key,/oauth/check_token
    这三个接口是 SpringBoot 自己加上的
  • 用 http 工具测试请求
  • 先直接访问:localhost:你的端口/demo/hello,响应如下:
    15553868311.jpg
  • 下面再请求 token:http://localhost:你的端口/oauth/token
    请求过程跟参数请参考:
    https://oauth.net/2/
    请求结果:
    15553870971.jpg
  • 再携带得到的 token 请求/demo/hello,响应如下:
    image.png
    到此,整个 OAuth2.0 认证过程完成!

  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    940 引用 • 1458 回帖 • 160 关注
  • OAuth

    OAuth 协议为用户资源的授权提供了一个安全的、开放而又简易的标准。与以往的授权方式不同之处是 oAuth 的授权不会使第三方触及到用户的帐号信息(如用户名与密码),即第三方无需使用用户的用户名与密码就可以申请获得该用户资源的授权,因此 oAuth 是安全的。oAuth 是 Open Authorization 的简写。

    36 引用 • 103 回帖 • 6 关注
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3167 引用 • 8207 回帖 • 1 关注
  • MySQL

    MySQL 是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,目前属于 Oracle 公司。MySQL 是最流行的关系型数据库管理系统之一。

    675 引用 • 535 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...