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

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

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

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


  • 基于 Spring Cloud OAuth,用简洁的方式搭建oauth的认证中心,

  • 项目版本核心说明

名称 版本
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 请求测试接口获取当前用户信息

总结

目录
相关文章
|
3月前
|
弹性计算 运维 安全
阿里云轻量应用服务器与云服务器ECS啥区别?新手帮助教程
阿里云轻量应用服务器适合个人开发者搭建博客、测试环境等低流量场景,操作简单、成本低;ECS适用于企业级高负载业务,功能强大、灵活可扩展。二者在性能、网络、镜像及运维管理上差异显著,用户应根据实际需求选择。
340 10
|
3月前
|
弹性计算 网络协议 Linux
阿里云服务器简介及使用教程,附送云服务器ECS自定义创建流程
阿里云ECS是安全可靠、弹性灵活的云计算服务,支持多种实例规格与操作系统,可快速创建和管理云服务器。本文详解ECS介绍、购买流程及使用教程,涵盖配置选择、网络设置、安全组规则等,助您轻松上手。
482 16
|
3月前
|
存储 弹性计算 网络协议
超详细的阿里云服务器购买流程,ECS自定义购买配置教程
本文详细图解阿里云ECS服务器自定义购买全流程,涵盖付费模式、地域选择、网络配置、实例规格、镜像、存储、安全组及登录设置等核心步骤,助您轻松掌握专业级云服务器搭建方法。
|
3月前
|
存储 弹性计算 网络协议
阿里云服务器ECS是什么?ECS介绍、云服务器创建及使用教程
阿里云ECS是安全可靠、弹性灵活的云计算服务,支持多种实例规格与操作系统,可快速创建和管理云服务器。本文详解ECS介绍、购买流程(含付费模式、地域、网络、存储等设置)及使用教程,助您轻松上手云服务器。
584 4
|
3月前
|
存储 弹性计算 Linux
阿里云账号注册、领取优惠券、试用云服务器和购买云服务器教程参考
对于还未使用阿里云任何云产品的用户来说,完整的上云流程包括账号注册并完成实名认证,然后才是试用或者购买云服务器,有的新手用户对这一流程还不是很清楚。本文为大家介绍新手用户从注册阿里云账号,完成实名认证,然后领取阿里云优惠券,并试用云服务器和购买云服务器的全部流程,适合初次购买和试用阿里云服务器的新手用户参考。
|
3月前
|
弹性计算 网络协议 Linux
阿里云服务器ECS创建流程(新手详细图文教程)
本文图解阿里云ECS自定义购买全流程,涵盖付费模式、地域选择、实例规格、镜像、存储、网络、安全组及登录设置等关键步骤,助您快速掌握云服务器配置要点,适合专业用户参考操作。
239 7
|
3月前
|
运维 安全 Ubuntu
阿里云渠道商:服务器操作系统怎么选?
阿里云提供丰富操作系统镜像,涵盖Windows与主流Linux发行版。选型需综合技术兼容性、运维成本、安全稳定等因素。推荐Alibaba Cloud Linux、Ubuntu等用于Web与容器场景,Windows Server支撑.NET应用。建议优先选用LTS版本并进行测试验证,通过标准化镜像管理提升部署效率与一致性。
|
3月前
|
弹性计算 ice
阿里云4核8g服务器多少钱一年?1个月和1小时价格,省钱购买方法分享
阿里云4核8G服务器价格因实例类型而异,经济型e实例约159元/月,计算型c9i约371元/月,按小时计费最低0.45元。实际购买享折扣,1年最高可省至1578元,附主流ECS实例及CPU型号参考。
489 8
|
3月前
|
存储 监控 安全
阿里云渠道商:云服务器价格有什么变动?
阿里云带宽与存储费用呈基础资源降价、增值服务差异化趋势。企业应结合业务特点,通过阶梯计价、智能分层、弹性带宽等策略优化成本,借助云监控与预算预警机制,实现高效、可控的云资源管理。