如何在miceoservices中添加基于jwt令牌的安全性

6ljaweal  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(367)

在我的微服务中,我将尝试实现jwt Spring Security ,但我不知道如何应用它。
在我的微服务中,我使用了2020.0.3 spring云版本。在用户服务中,我使用rest模板连接了department服务。我需要关于如何在这些微服务中添加jwt安全性的帮助。
这是4个微服务
服务器=Eureka 服务器
服务api网关=spring云api网关
服务部门和服务用户=这两个微服务与rest模板连接
微服务项目结构:https://i.stack.imgur.com/ajtix.png

w1jd8yoj

w1jd8yoj1#

因此,在更高的级别上,当使用jwt作为身份验证时,Spring Security 应用于控制器级别。首先,您需要添加一个安全配置来扩展WebSecurityConfigureAdapter(这对于基于http的安全性来说很常见),并且在该类中,您需要定义如下所示的配置方法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .httpBasic().disable()
            .csrf().disable()  // IF your clients connect without a cookie based, this will be fine
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/register", "/login","/your_open_endpoints_etc").permitAll()
            .and()
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}

然后在扩展onceperrequestfilter的filter类中,您可以这样定义do筛选器,您必须在spring身份验证上下文中设置usernamepasswordauthenticationfilter示例:

@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    logger.info("do filter...");
    String token = jwtProvider.getTokenFromRequest((HttpServletRequest) httpServletRequest);
    try{
        if (token != null && jwtProvider.validateToken(token)) {
            String username = jwtProvider.getUsernameFromToken(token);
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, jwtProvider.getAuthorities(token));
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
    catch (RuntimeException e)
    {
        // Some general Exception handling that will wrap and send as HTTP Response
    }

}

进一步检查扩展过滤器,它们可能会根据您的要求进行更改
最后,在rest端点中,您可以进行如下安全防护:

@PreAuthorize("hasRole('ROLE_YOURROLE')")
@GetMapping(path = "/your_secured_endpoint", consumes = "application/json", 
  produces = "application/json")
public ResponseEntity<List<SomePOJOObject>> getAllAppointmentsForPatient()
{

    return new ResponseEntity<>(thatSomePOJOObjectListYouWant, HttpStatus.OK);
}

相关问题