【最简OAuth 2.0 教程】开发认证中心及资源服务器接入

简介: 背景: 网上很多讲配置 oauth2 ,配置方法 复杂纷繁对于初学者很不友好,让人望而却步 欢迎关注本系列博客 基于 spring cloud 最新版本 hoxton 完成oauth2 的实践基于 Spring Cloud OAuth ,用简洁的方式搭建oauth的认证中心,关于oauth2 的授权模式 请直接参考 [阮一峰 OAuth 2.

背景: 网上很多讲配置 oauth2 ,配置方法 复杂纷繁对于初学者很不友好,让人望而却步

欢迎关注本系列博客 基于 spring cloud 最新版本 hoxton 完成oauth2 的实践


名称 版本
Spring Boot 2.2.0.M5
Spring Cloud Hoxton.M2
Spring Cloud OAuth2 2.2.0.M2

开始配置认证服务器

maven 依赖引入

  • 这里只需要引入web、 cloud-oauth 即可,暂不引入spring cloud 其他组件
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
</dependencies>

配置web安全,拦截全部的请求

  • 获取web 上下文AuthenticationManager 注入到spring中,方便后边oauth server注入
  • 创建UserDetailsService的内存实现,注入一个测试用户
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    /**
     * 必须注入 AuthenticationManager,不然oauth  无法处理四种授权方式
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 必须注入UserDetailsService ,不然oauth  密码模式等死循环问题
     *
     * @return
     */
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        userDetailsManager.createUser(User.withUsername("lengleng").password("{noop}lengleng").authorities("USER").build());
        return userDetailsManager;
    }
}

配置oauth2 认证服务器

  • 配置clientId 信息,及其支持的授权模式,特别注意这里是五种包含一个刷新操作
@Configuration
@EnableAuthorizationServer
public class BigAuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("appid")
                .secret("{noop}secret")
                .authorizedGrantTypes("password", "authorization_code", "client_credentials", "implicit", "refresh_token")
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }

}

以上完成了认证服务器的功能

测试密码模式

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'grant_type=password&username=lengleng&password=lengleng&scope=all' "http://appid:secret@localhost:8764/oauth/token"

开始配置资源服务器

maven 依赖引入

  • 这里只需要引入web、 cloud-oauth 即可,暂不引入spring cloud 其他组件
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
</dependencies>

配置客户端信息

security:
  oauth2:
    client:
      client-id: appid
      client-secret: secret
      scope: all
    resource: # 认证中心的check_token 接口地址
      token-info-uri: http://127.0.0.1:8764/oauth/check_token

应用声明资源服务器

  • @EnableResourceServer 即可完成接入
// 接入oauth2 ,声明为资源服务器
@EnableResourceServer  
@EnableDiscoveryClient
@SpringBootApplication
public class BigUpmsServerApplication {

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

}

上文配置的认证服务器暴露check_token

  • 若不处理接口check_token 403
public class BigAuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
    /**
     * checkTokenAccess 权限设置为isAuthenticated,不然资源服务器 来请求403
     * @param oauthServer
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                .allowFormAuthenticationForClients()
                .checkTokenAccess("isAuthenticated()");
    }
}

资源服务器demo 接口

@RestController
public class DemoController {

    @GetMapping("/info")
    public Authentication authentication(Authentication authentication) {
        return authentication;
    }
}

通过上文获取的token 访问测试接口

  • 获取token

  • 通过token 请求测试接口获取当前用户信息

总结

目录
相关文章
|
14天前
|
弹性计算 前端开发 持续交付
云效产品使用常见问题之导入ECS主机到资源池找不到导入的入口如何解决
云效作为一款全面覆盖研发全生命周期管理的云端效能平台,致力于帮助企业实现高效协同、敏捷研发和持续交付。本合集收集整理了用户在使用云效过程中遇到的常见问题,问题涉及项目创建与管理、需求规划与迭代、代码托管与版本控制、自动化测试、持续集成与发布等方面。
|
14天前
Servlet 教程 之 Servlet 服务器 HTTP 响应 2
Servlet教程讲解了如何通过HttpServletResponse设置HTTP响应,包括编码URL、添加cookie、设置报头、控制缓冲区、发送错误或重定向响应。方法如encodeURL、addCookie、sendError、sendRedirect等,涉及状态码、报头、字符编码和内容长度的管理。
19 2
|
14天前
|
XML Java 数据格式
Servlet 教程 之 Servlet 服务器 HTTP 响应 3
`Servlet`教程示例展示了如何创建一个HTTP响应,使用`@WebServlet(&quot;/Refresh&quot;)`的`Refresh`类继承`HttpServlet`。在`doGet`方法中,设置了`Refresh`头以每5秒自动刷新,并用`setContentType(&quot;text/html;charset=UTF-8&quot;)`设定内容类型。还使用`Calendar`和`SimpleDateFormat`获取并格式化当前时间显示。相应的`web.xml`配置指定了Servlet路径。当访问此Servlet时,页面将每5秒更新一次显示的系统时间。
19 4
|
10天前
|
前端开发 数据处理 API
后端开发:构建稳健与高效的服务器逻辑
后端开发:构建稳健与高效的服务器逻辑
|
6天前
|
域名解析 弹性计算 Linux
阿里云购买云服务器、注册域名、备案及绑定图文教程参考
本文为大家介绍了2024年购买阿里云服务器和注册域名,绑定以及备案的教程,适合需要在阿里云购买云服务器、注册域名并备案的用户参考,新手用户可通过此文您了解在从购买云服务器到完成备案的流程。
阿里云购买云服务器、注册域名、备案及绑定图文教程参考
|
15天前
|
Unix Linux 数据安全/隐私保护
Linux服务器如何远程连接?服务器远程连接图文教程
服务器操作系统可以实现对计算机硬件与软件的直接控制和管理协调,任何计算机的运行离不开操作系统,服务器也一样,服务器操作系统主要分为四大流派:Windows Server、Netware、Unix和Linux。 今天驰网飞飞就给你们分享下Linux、Unix系统远程连接图文操作方法
21 4
Linux服务器如何远程连接?服务器远程连接图文教程
|
15天前
|
安全 Unix Linux
Windows如何远程连接服务器?服务器远程连接图文教程
服务器操作系统可以实现对计算机硬件与软件的直接控制和管理协调,任何计算机的运行离不开操作系统,服务器也一样,服务器操作系统主要分为四大流派:Windows Server、Netware、Unix和Linux。今天驰网飞飞将和你分享Windows server远程连接图文教程,希望可以帮助到你
26 4
Windows如何远程连接服务器?服务器远程连接图文教程
|
5天前
|
存储 弹性计算 固态存储
阿里云服务器配置怎么选择合适?收藏级教程大家参考下
阿里云服务器配置选择涉及CPU、内存、带宽和磁盘。个人开发者或中小企业推荐使用轻量应用服务器或ECS经济型实例,如2核2G3M配置,适合低流量网站。企业用户应选择企业级独享型ECS,如通用算力型u1、计算型c7或通用型g7,至少2核4G配置,公网带宽建议5M,系统盘可选SSD或ESSD云盘。具体配置需根据实际应用需求来定。
|
存储 弹性计算 自然语言处理
使用阿里云ECS的开发心得
关于本人使用阿里云ECS的开发心得与使用经验。分享开发提高效率的方法、使用心得。
使用阿里云ECS的开发心得
|
4天前
|
存储 弹性计算 固态存储
阿里云服务器CPU内存配置详细指南,如何选择合适云服务器配置?
阿里云服务器配置选择涉及CPU、内存、公网带宽和磁盘。个人开发者或中小企业推荐使用轻量应用服务器或ECS经济型e实例,如2核2G3M配置,适合低流量网站。企业用户则应选择企业级独享型ECS,如通用算力型u1、计算型c7或通用型g7,至少2核4G配置,公网带宽建议5M,系统盘可选SSD或ESSD云盘。选择时考虑实际应用需求和性能稳定性。