美文网首页
Spring Cloud与OAuth2整合

Spring Cloud与OAuth2整合

作者: 自负的鱼 | 来源:发表于2018-09-12 18:02 被阅读44次

    Spring Cloud与OAuth2整合

    OAuth2中的角色

    • client 调用资源服务器API的应用
    • Authorization Server 认证授权服务器
    • Resource Server 受保护的资源服务器
    • user 资源拥有者用户

    Authorization Server

    开启@EnableAuthorizationServer注解,该注解会自动添加OAuth2的多个endpoint。

    • /oauth/authorize:验证接口, AuthorizationEndpoint
    • /oauth/token:获取token
    • /oauth/confirm_access:用户授权
    • /oauth/error:认证失败
    • /oauth/check_token:资源服务器用来校验token
    • /oauth/token_key:jwt模式下获取公钥;位于:TokenKeyEndpoint ,通过 JwtAccessTokenConverter 访问key

    继承AuthorizationServerConfigurerAdapter,配置OAuth2认证服务器,需要配置授权和Token相关的三个配置。

    • AuthorizationServerSecurityConfigurer:声明安全约束,允许那些请求可以访问和禁止访问。
    • ClientDetailsServiceConfigurer:配置独立的client客户端信息,包括授权范围、授权方式、客户端权限等。授权方式包括password、implicit、client_redentials、authorization_code四种方式,其中密码授权方式必须结合 AuthenticationManager 进行配置。
    • AuthorizationServerEndpointsConfigurer:配置授权服务器的Token存储方式、Token配置、授权模式

    Token存储配置,默认使用DefaultTokenServices管理生命周期。Token存储通过配置 TokenStore,默认使用内存存储,包括一下存储方式。

    • InMemoryTokenStore 默认方式,保存在本地内存
    • JdbcTokenStore 存储数据库
    • RedisTokenStore 存储Redis,这应该是微服务下比较常用方式
    • JwtTokenStore 分布式跨域JWT存储方式

    Resource Server

    开启@EnableResourceServer注解,在服务中声明资源服务器。
    继承实现ResourceServerConfigurerAdapter 类配置资源服务器安全属性,如Token的配置。

    如何访问资源服务器中的API

    要实现访问资源服务器中API,常用的方法有以下三种情况:

    • 在校验request中的token时,使用RemoteTokenServices去调用AuthServer中的/auth/check_token。
    • 共享数据库,使用Jdbc存储和校验token,避免再去访问AuthServer。
    • 使用JWT签名的方式,资源服务器自己直接进行校验,不借助任何中间媒介。

    相关文章

      网友评论

          本文标题:Spring Cloud与OAuth2整合

          本文链接:https://www.haomeiwen.com/subject/iirbgftx.html