Spring Cloud Zuul 集成 OAuth2.0+JWT

前言

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

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

正文

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

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

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

  1. Header头部:指定JWT使用的签名算法。
  2. Payload载荷:包含一些自定义与非自定义的认证信息。
  3. 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加入相关依赖

        <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改造

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信息。

 

@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文件

    <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文件

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
@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以后才有。

@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到控制台。

@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解码后

 

 

 

注:对本文有异议或不明白的地方微信探讨,wx:15524579896

 

 

  • 8
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 72
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 72
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值