前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Cloud Zuul 集成 OAuth2.0+JWT

Spring Cloud Zuul 集成 OAuth2.0+JWT

作者头像
胖虎
发布2019-06-26 15:52:49
1.7K0
发布2019-06-26 15:52:49
举报
文章被收录于专栏:晏霖晏霖

前言 声明:此文Demo摘自《重新定义》已得作者许可。

有资源的地方就会有权限的约束,单体应用时代比较流行的就是Apache shiro,但是使用Spring Cloud开发的微服务中,所有服务之间访问都是无状态的,也就是说,访问一个接口我不知道你登陆了没有,我也不知道你是谁……所以Spring Cloud没有选择集成shiro的原因就在于此。所以想在微服务中做权限我们有一个好的办法,利用zuul在微服务体系流量前门的特性加入一些权限的认证和,返回相应的资源。

正文 下图是OAuth2原理图,下面文字简述一下:这三个来回的请求相当于手动键入密码或者第三方登录,然后客户端向授权服务器申请Token,客户端拿到Token到资源所在的服务器拉取相应的资源,整个鉴权就结束了。

其次我还要给大家解释什么是JWT

JWT(JSON Web Token)是一种JSON格式来规约Token或者Session的协议。再通俗的解释就是JWT是一个加密的协议。用来给Token加密的。 他包括三部分:

Header头部:指定JWT使用的签名算法。 Payload载荷:包含一些自定义与非自定义的认证信息。 Signature签名:将头部与载荷使用“.”连接之后,使用头部的签名算法生成签名信息并拼接带尾部。 OAuth2.0+JWT的意义在于,使用OAuth2.0协议的思想拉取认证生成的Token,使用JWT瞬时保存这个Token,在客户端与资源端进行对称与非对称加密,使得这个规约具有定时定量的授权认证功能,也解决来Token存储带来的不安全隐患。

上文我们知道来zuul的用法和特性,刚刚也解释了OAuth2.0、JWT

下面的案例流程是:使用zuul判断是否登陆鉴权,如果没登陆就跳转到auth-server配置的登陆页面,登陆成功后auth-server颁发jwt token,zuul服务在访问下游服务时将jwt token放到header中即可。

第一步 大家可以使用上文的zuul-server,但需要改造,

在zuul-server加入相关依赖

代码语言:javascript
复制
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>

zuul-server yml改造

代码语言:javascript
复制
spring:
  application:
    name: zuul-server
server:
  port: 5555
eureka:
  client:
    serviceUrl:
      defaultZone: http://${eureka.host:127.0.0.1}:${eureka.port:8888}/eureka/
  instance:
    prefer-ip-address: true
zuul:
  routes:
    client-a:
      path: /client/**
      serviceId: client-a
security:
  basic:
    enabled: false
  oauth2:
    client:
      access-token-uri: http://localhost:7777/uaa/oauth/token #令牌端点
      user-authorization-uri: http://localhost:7777/uaa/oauth/authorize #授权端点
      client-id: zuul_server #OAuth2客户端ID
      client-secret: secret #OAuth2客户端密钥
    resource:
      jwt:
        key-value: springcloud123 #使用对称加密方式,默认算法为HS256

zuul-server 核心启动类,重写WebSecurityConfigurerAdapter但configure方法,声明需要授权但url信息。

代码语言:javascript
复制
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
@EnableOAuth2Sso
public class ZuulServerApplication extends WebSecurityConfigurerAdapter{

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
        .antMatchers("/login", "/client/**")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .csrf()
        .disable();
    }
}

第二步 编写auth-server服务,整个示例的核心,作为认证授权中心,用来颁发jwt token凭证。

auth-server的pom文件

代码语言:javascript
复制
    <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
    </dependencies>

auth-server的yml文件

代码语言:javascript
复制
spring:
  application:
    name: auth-server
server:
  port: 7777
  servlet: 
    contextPath: /uaa #web基路径
eureka:
  client:
    serviceUrl:
      defaultZone: http://${eureka.host:127.0.0.1}:${eureka.port:8888}/eureka/
  instance:
    prefer-ip-address: true

auth-server的配置类,编写认证授权服务器适配器OAuthConfiguration类,这里主要指定类客户端ID、密钥,以及权限定义与作用范围的声明,指定类TokenStore为JWT

代码语言:javascript
复制
@Configuration
@EnableAuthorizationServer
public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
        .inMemory()
        .withClient("zuul_server")
        .secret("secret")
        .scopes("WRIGTH", "read").autoApprove(true)
        .authorities("WRIGTH_READ", "WRIGTH_WRITE")
        .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
        .tokenStore(jwtTokenStore())
        .tokenEnhancer(jwtTokenConverter())
        .authenticationManager(authenticationManager);
    }

    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtTokenConverter());
    }

    @Bean
    protected JwtAccessTokenConverter jwtTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("springcloud123");
        return converter;
    }
}

auth-server的启动类,这里声明类admin有读写权限,guest只有读的权限;passwordEncoder()方法用于声明用户名和密码的加密方式,注:只有Spring Security5.0以后才有。

代码语言:javascript
复制
@SpringBootApplication
@EnableDiscoveryClient
public class AuthServerApplication extends WebSecurityConfigurerAdapter {

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

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
        .inMemoryAuthentication()
        .withUser("guest").password("guest").authorities("WRIGTH_READ")
        .and()
        .withUser("admin").password("admin").authorities("WRIGTH_READ", "WRIGTH_WRITE");
    }

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
      return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

第三步 client-a服务编写,左右一个服务,被注册中心发现,以及可以按照规则解析jwt token。

编写client-a服务的启动类,和auth-server的配置很像,不同是,写类一个/test接口用于返回内容与打印header到控制台。

代码语言:javascript
复制
@SpringBootApplication
@EnableDiscoveryClient
@EnableResourceServer
@RestController
public class ClientAApplication extends ResourceServerConfigurerAdapter {

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

    @RequestMapping("/test")
    public String test(HttpServletRequest request) {
        System.out.println("----------------header----------------");
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            System.out.println(key + ": " + request.getHeader(key));
        }
        System.out.println("----------------header----------------");
        return "hellooooooooooooooo!";
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()
        .authorizeRequests()
        .antMatchers("/**").authenticated()
        .antMatchers(HttpMethod.GET, "/test")
        .hasAuthority("WRIGTH_READ");
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
        .resourceId("WRIGTH")
        .tokenStore(jwtTokenStore());
    }

    @Bean
    protected JwtAccessTokenConverter jwtTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("springcloud123");
        return converter;
    }

    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtTokenConverter());
    }
}

第四步 把上文的eureka服务copy过来

测试 工程启动顺序依次是eureka服务、zuul服务、client-a、auth服务。

浏览器访问http://localhost:5555/client/test,直接访问接口肯定是访问不通的。

让我们来直接访问网关http://localhost:5555,浏览器自动跳转至授权服务的登陆页面 http://localhost:7777/uaa/login

用户名:admin 密码:admin

登陆成功,在开启一个浏览器标签输入刚刚访问的地址 http://localhost:5555/client/test

回到客户端的控制台观察,header已经打印出来,截图里有个长长的字符串 authorization 就是你的使用jwt加密后的token,大概100来个字节,以后这个用户访问任何资源都会带着个加密后的token的。

使用BASE64解码后

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-01-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 晏霖 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
访问管理
访问管理(Cloud Access Management,CAM)可以帮助您安全、便捷地管理对腾讯云服务和资源的访问。您可以使用CAM创建子用户、用户组和角色,并通过策略控制其访问范围。CAM支持用户和角色SSO能力,您可以根据具体管理场景针对性设置企业内用户和腾讯云的互通能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档