什么是JWT?为什么选择JWT?如何在Spring Cloud Security集成使用?

什么是JWT?

Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准,详情可以参考什么是 JWT -- JSON WEB TOKEN。其特点如下:

  1. 具体时效性,包含失效时间。
  2. 具有安全性,基于密钥机制的签发和验证机制。

为什么选择JWT?

基于oauth2协议认证过程中,以密码类型认证方式为例,包括认证和授权两个步骤。分别如下:

  1. 客户端通过客户端用户名和密码,密码授权方式,以及用户名和密码,向授权服务器认证,如果有效则返回token(访问令牌)。
  2. 客户端携带token(访问令牌)访问资源服务器,资源服务器验证token,如果有效则返回受保护的资源。 

一般在资源服务验证token时,需要通过token向授权服务器调用认证服务,并且,需要通过token向授权服务器获取用户信息。在服务的相互调用过程中,会频繁地调用授权服务器,如果使用JWT有如下几个优势:

  1. 由于JWT具有时效性,如果token失效则直接校验失败
  2. 在资源服务可以基于密钥对token进行校验,而无需调用授权服务器的认证服务,避免频繁调用认证服务器
  3. 在JWT中携带非敏感的认证信息,同样避免了频繁调用授权服务器获取用户相关信息,方便了在服务之间传递

如何在Spring Cloud Security集成使用?

授权服务器生成JWT

  • 授权服务器生成token的流程分析如下:

通过向授权服务TokenEndpoint的/oauth/token POST 请求生成访问令牌。TokenEndpoint部分源码如下:

@RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
	public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
	Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {

		if (!(principal instanceof Authentication)) {
			throw new InsufficientAuthenticationException(
					"There is no client authentication. Try adding an appropriate authentication filter.");
		}
        // 通过客户端id获取客户端信息
		String clientId = getClientId(principal);
		ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);

		TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
        
        // 省略授权模式校验
        ... ...
        // 生成token访问授权码

		OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
		if (token == null) {
			throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
		}

		return getResponse(token);

	}

根据源码可知,security通过TokenGranter生成OAuth2AccessToken,在一般的实现中会使用CompositeTokenGranter组合生成token。分析TokenGranter的公共类AbstractTokenGranter可知,TokenGranter通过调用AuthorizationServerTokenServices的createAccessToken方法生成token,AbstractTokenGranter源码如下:

// TokenGranter 公共实现类
public abstract class AbstractTokenGranter implements TokenGranter {

    // 生成OAuth2AccessToken 
    public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {

		if (!this.grantType.equals(grantType)) {
			return null;
		}
		
		String clientId = tokenRequest.getClientId();
		ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
		validateGrantType(grantType, client);

		if (logger.isDebugEnabled()) {
			logger.debug("Getting access token for: " + clientId);
		}

		return getAccessToken(client, tokenRequest);

	}

    // 通过AuthorizationServerTokenServices 生成token
	protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
		return tokenServices.createAccessToken(getOAuth2Authentication(client, tokenRequest));
	}

}

在security中默认的AuthorizationServerTokenServices实现类为DefaultTokenServices,在调用createAccessToken生成token时,会调用TokenEnhancer的enhance对OAuth2AccessToken进行包装。在实现JWT的TokenEnhancer实现类JwtAccessTokenConverter时,会按照JWT的规范生成OAuth2AccessToken,并且可以自定义TokenEnhancer在OAuth2AccessToken的additionalInformation扩展字段中追加自定义属性。

  • 基于jwt的授权服务器搭建的相关配置如下:

定义jwt的配置,源码如下:

@Configuration
public class JwtTokenConfig {

    // 定义密钥的key
    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("mm.jks"),
                "AJKcNwxDry".toCharArray());
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tttttt");
        return keyPair;
    }
   // 使用JwtAccessTokenConverter 
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair());
        return converter;
    }
    // 使用JwtTokenStore
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

}

授权服务器配置源码如下,AuthorizationServerConfig 在配置生效需要在JwtTokenConfig之后,配置时JWT的相关配置已经生效。其中自定义的认证方式方式实现可以参考玩转Spring Cloud Security OAuth2身份认证扩展——电话号码+验证码认证。在tokenEnhancer的配置中,使用TokenEnhancerChain,利用TokenEnhancer列表组合多种token增强方式,其中自定义JwtTokenUserEnhancer,在在OAuth2AccessToken的additionalInformation扩展字段中追加用户属性。AuthorizationServerConfig部分源码如下:

@Configuration
@EnableAuthorizationServer
@AutoConfigureAfter(JwtTokenConfig.class)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

   /**
     * 自定义用户信息增强
     */
    @Autowired
    private TokenEnhancer jwtTokenEnhancer;
    /**
     * jwt token 转换器
     */
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Autowired
    private TokenStore jwtTokenStore;

    /**
     * 配置授权服务
     * @param endpoints 授权服务端点配置
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

        AuthenticationManager authenticationManager = authenticationProviderManager();
        // tokenStore
        endpoints.tokenStore(jwtTokenStore)
                .userDetailsService(userManager)
                .authenticationManager(authenticationManager)
                 // jwtAccessTokenConverter
                .accessTokenConverter(jwtAccessTokenConverter)
                // token增强
                .tokenEnhancer(tokenEnhancerChain(jwtAccessTokenConverter))
                // 自定义认证方式
                .tokenGranter(compositeTokenGranter(endpoints, authenticationManager));
    }

  /**
     * token增加链表
     */
    private TokenEnhancerChain tokenEnhancerChain(JwtAccessTokenConverter jwtAccessTokenConverter) {

        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = Lists.newArrayList(jwtTokenEnhancer, jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(enhancerList);
        return enhancerChain;
    }

}

JwtTokenUserEnhancer,用于在OAuth2AccessToken的additionalInformation扩展字段中追加用户属性,部分源码如下:

@Component
public class JwtTokenUserEnhancer implements TokenEnhancer {

    /**
     * 增强 AccessToken
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {

        // 扩展属性集合
        Map<String, Object> additionalInformation = new LinkedHashMap<>(oAuth2AccessToken.getAdditionalInformation());
        Authentication authentication;
        // 认证对象
        Object principal;
        if (Objects.nonNull(authentication = oAuth2Authentication.getUserAuthentication())
                && Objects.nonNull(principal = authentication.getPrincipal())
                && (principal instanceof UserWrapper)) {

            UserWrapper userWrapper = (UserWrapper) principal;
            // 设置附加信息
            Map<String, Object> info;
            if (MapUtils.isNotEmpty(info = this.getAdditionalInformationByUser(userWrapper))) {
                additionalInformation.putAll(info);
            }
        }
    }

    private Map<String, Object> getAdditionalInformationByUser(UserWrapper userWrapper) {

        ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        // 用户权限列表
        Collection<? extends GrantedAuthority> grantedAuthorities;
        // 省略用户信息的转换逻辑
        ......
        return builder.build();
    }
}

 

在资源服务验证JWT

  • 资源服务器认证token流程如下

资源服务器通过OAuth2AuthenticationProcessingFilter,对资源服务器的url进行拦截授权。大致过程步骤如下:

  1. 从参数中获取token
  2. 对token进行认证
  3. 认证通过把认证对象保存在安全上下文SecurityContextHolder中

OAuth2AuthenticationProcessingFilter源码如下:

// 实现Filter 对资源服务器的url访问请求进行拦截
public class OAuth2AuthenticationProcessingFilter implements Filter, InitializingBean {


public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
			ServletException {

		final boolean debug = logger.isDebugEnabled();
		final HttpServletRequest request = (HttpServletRequest) req;
		final HttpServletResponse response = (HttpServletResponse) res;

		try {
            // 获取token
			Authentication authentication = tokenExtractor.extract(request);
			
			if (authentication == null) {
				if (stateless && isAuthenticated()) {
					if (debug) {
						logger.debug("Clearing security context.");
					}
					SecurityContextHolder.clearContext();
				}
				if (debug) {
					logger.debug("No token in request, will continue chain.");
				}
			}
			else {
				request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
				if (authentication instanceof AbstractAuthenticationToken) {
					AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
					needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
				}

                // 认证token
				Authentication authResult = authenticationManager.authenticate(authentication);

				if (debug) {
					logger.debug("Authentication success: " + authResult);
				}

				eventPublisher.publishAuthenticationSuccess(authResult);
                // 在安全上下文设置认证对象
				SecurityContextHolder.getContext().setAuthentication(authResult);

			}
		}
		catch (OAuth2Exception failed) {
			SecurityContextHolder.clearContext();

			if (debug) {
				logger.debug("Authentication request failed: " + failed);
			}
			eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
					new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

			authenticationEntryPoint.commence(request, response,
					new InsufficientAuthenticationException(failed.getMessage(), failed));

			return;
		}

		chain.doFilter(request, response);
	}

}

security通过AuthenticationManager的实现类Auth2AuthenticationManager对token进行认证授权。在认证过程中,通过ResourceServerTokenServices的loadAuthentication验证token,并且验证客户端信息。Auth2AuthenticationManager部分源码如下:

public class OAuth2AuthenticationManager implements AuthenticationManager, InitializingBean {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		if (authentication == null) {
			throw new InvalidTokenException("Invalid token (token not found)");
		}
		String token = (String) authentication.getPrincipal();
        // 获取OAuth2Authentication认证对象
		OAuth2Authentication auth = tokenServices.loadAuthentication(token);
		if (auth == null) {
			throw new InvalidTokenException("Invalid token: " + token);
		}

		Collection<String> resourceIds = auth.getOAuth2Request().getResourceIds();
		if (resourceId != null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(resourceId)) {
			throw new OAuth2AccessDeniedException("Invalid token does not contain resource id (" + resourceId + ")");
		}
        // 验证客户端
		checkClientDetails(auth);

		if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
			OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
			// Guard against a cached copy of the same details
			if (!details.equals(auth.getDetails())) {
				// Preserve the authentication details from the one loaded by token services
				details.setDecodedDetails(auth.getDetails());
			}
		}
		auth.setDetails(authentication.getDetails());
        // 认证通过返回认证对象
		auth.setAuthenticated(true);
		return auth;

	}
}

ResourceServerTokenServices的默认实现类DefaultTokenServices调用loadAuthentication获取认证对象。在loadAuthentication中,通过TokenStore通过readAccessToken获取token;通过readAuthentication获取认证信息。DefaultTokenServices的部分源码如下:

public class DefaultTokenServices implements AuthorizationServerTokenServices, ResourceServerTokenServices,
		ConsumerTokenServices, InitializingBean {
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException,
			InvalidTokenException {
        // 获取token
		OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
		if (accessToken == null) {
			throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
		}
		else if (accessToken.isExpired()) {
			tokenStore.removeAccessToken(accessToken);
			throw new InvalidTokenException("Access token expired: " + accessTokenValue);
		}
        // 根据token获取认证对象
		OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
		if (result == null) {
			// in case of race condition
			throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
		}
		if (clientDetailsService != null) {
			String clientId = result.getOAuth2Request().getClientId();
			try {
				clientDetailsService.loadClientByClientId(clientId);
			}
			catch (ClientRegistrationException e) {
				throw new InvalidTokenException("Client not valid: " + clientId, e);
			}
		}
		return result;
	}

}

调用JwtTokenStore的readAuthentication方法获取认证对象时,会调用JwtAccessTokenConverter的extractAuthentication方法获取认证对象。最终,JwtAccessTokenConverter通过AccessTokenConverter的extractAuthentication获取认证信息;认证通过后通过SecurityContextHolder上下文获取认证对象。

  • 资源服务器的配置如下:

在业务开发中,自定义了JwtAccessTokenConverter的AccessTokenConverter实现类UserAuthenticationConverter,用于从OAuth2AccessToken的additionalInformation扩展字段中获取用户的部分信息。ResourceServerConfiguration的配置生效在JwtTokenConfig之后,所以,JWT的相关配置已经注入,ResourceServerConfiguration的部分配置如下:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@AutoConfigureAfter(JwtTokenConfig.class)
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    /**
     * 资源属性配置
     */
    @Autowired
    private ResourceServerProperties resource;
    /**
     * jwtTokenStore
     */
    @Autowired(required = false)
    private TokenStore jwtTokenStore;
    /**
     * jwt AccessToken转换器
     */
    @Autowired(required = false)
    private JwtAccessTokenConverter jwtAccessTokenConverter;


 /**
     * 资源服务器自定义配置
     *
     * @param resources
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {

        // 设置资源id,
        // 客户端配置表oauth_client_details的 resource_ids 值包含该resourceId,授权才会通过
        resources.resourceId(resource.getResourceId());
        // 设置自定义tokenStore
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        // 设置自定义的UserAuthenticationConverter
        accessTokenConverter.setUserTokenConverter(new UserAuthenticationConverter());
        jwtAccessTokenConverter.setAccessTokenConverter(accessTokenConverter);

        resources.tokenStore(jwtTokenStore);
    }

}

UserAuthenticationConverter用于从OAuth2AccessToken的additionalInformation扩展字段中获取用户的部分信息,其源码如下:

public class UserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {

        User user = new User();
        // 设置扩展属性传递的值
        user.extractAuthentication(map);
        // 设置权限值
        Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
        // 设置定义认证对象
        return new ExtUsernamePasswordAuthenticationToken(user, user.getUsername(), org.apache.commons.lang3.StringUtils.EMPTY, authorities);
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {

        Object authorities = map.get(AUTHORITIES);
        if (Objects.isNull(authorities)) {
            authorities = Collections.EMPTY_LIST;
        }
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                    .collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }
}


public class ExtUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken {

    private User userExt;

    public ExtUsernamePasswordAuthenticationToken(User user, Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(principal, credentials, authorities);
        this.userExt = user;
    }

    public User  getUserExt() {
        return userExt;
    }
}

资源服务器认证通过后,就可以从安全上下文SecurityContextHolder获取认证对象ExtUsernamePasswordAuthenticationToken 。

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Cloud是一个基于Spring Boot的开发工具,用于快速构建分布式系统的微服务框架。它提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡、断路器、网关等,使得开发者可以更加方便地构建和管理微服务。 Spring SecuritySpring框架中的一个安全框架,用于提供身份认证和授权功能。它可以与Spring Cloud集成,为微服务提供安全保障。 JWT(JSON Web Token)是一种轻量级的身份认证和授权机制,它使用JSON格式来传递信息。在Spring Cloud中,可以使用JWT来实现微服务之间的安全通信,保证数据的安全性和完整性。 ### 回答2: Spring Cloud是一个开源的分布式系统开发框架,它基于Spring Boot,能够帮助开发者快速构建云原生应用程序。Spring Cloud提供了一系列的组件,例如服务注册与发现(Eureka)、服务网关(Zuul)、配置中心(Config)等,可以协助开发者实现微服务架构。 Spring SecuritySpring框架提供的一种安全框架,它能够为应用程序提供认证和授权的功能。Spring Security基于过滤器链的机制,可以对请求进行安全验证。开发者可以通过配置来定义访问控制规则,保护应用程序的资源。 JWT(JSON Web Token)是一种用于身份验证和访问控制的标准方法,它通过在身份验证完成后生成一个令牌,并将该令牌发送给客户端,客户端在后续的请求中通过该令牌进行身份验证。JWT由三部分组成,分别是头部、载荷和签名。头部和载荷使用Base64进行编码,然后使用一个密钥进行签名,确保JWT的安全性。 在使用Spring CloudSpring Security构建分布式系统时,可以使用JWT作为认证和授权的方式。具体做法是,当用户进行身份验证成功后,生成一个JWT令牌,并将该令牌返回给客户端。客户端在后续的请求中,将令牌作为Authorization头部的内容发送给服务端。服务端接收到请求后,解析JWT令牌,验证其合法性,并根据令牌中的信息来判断用户的身份和权限。通过这种方式,可以实现无状态的分布式身份验证和访问控制。 总结来说,Spring Cloud可以帮助开发者构建分布式系统,Spring Security可以提供身份验证和授权的功能,而JWT可以作为一种安全的认证和授权方式在分布式系统中使用。这三者相互结合,可以帮助开发者构建安全、可靠的分布式应用程序。 ### 回答3: Spring Cloud是一个基于Spring Boot的开发工具集,它提供了一系列的分布式系统开发工具,其中包括了分布式配置中心、服务注册与发现、消息总线、负载均衡、熔断器、数据流处理等。Spring Cloud的目标是帮助开发者快速构建适应于云环境的分布式系统。 Spring SecuritySpring官方提供的安全框架,它可以用于保护Spring应用程序免受各种攻击,例如身份验证、授权、防止跨站点请求伪造等。Spring Security使用一种基于过滤器链的方式来处理HTTP请求,通过配置一系列的过滤器,可以实现对请求的鉴权和授权处理。 JWT(JSON Web Token)是一种用于跨域身份验证的开放标准。它可以在用户和服务器之间传输信息,并且能够对信息进行校验和解析。JWT一般由三部分组成:头部、载荷和签名。头部包含了令牌的类型和加密算法,载荷包含了需要传输的信息,签名用于验证令牌的合法性。 在使用Spring Cloud时,可以结合Spring SecurityJWT来进行身份验证和授权。我们可以通过配置Spring Security的过滤器链来验证JWT的有效性,并在每个请求中进行用户身份的鉴权。通过使用JWT,我们可以避免传统的基于Session的身份验证方式,实现无状态的分布式身份验证。 总结起来,Spring Cloud是一个分布式系统开发工具集,Spring Security是一个安全框架,JWT是一种用于跨域身份验证的开放标准。在使用Spring Cloud进行分布式系统开发时,可以结合Spring SecurityJWT来实现身份验证和授权的功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值