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

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

在我的微服务中,我将尝试实现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的安全性来说很常见),并且在该类中,您需要定义如下所示的配置方法:

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

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

  1. @Override
  2. protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
  3. logger.info("do filter...");
  4. String token = jwtProvider.getTokenFromRequest((HttpServletRequest) httpServletRequest);
  5. try{
  6. if (token != null && jwtProvider.validateToken(token)) {
  7. String username = jwtProvider.getUsernameFromToken(token);
  8. UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, jwtProvider.getAuthorities(token));
  9. SecurityContextHolder.getContext().setAuthentication(auth);
  10. }
  11. filterChain.doFilter(httpServletRequest, httpServletResponse);
  12. }
  13. catch (RuntimeException e)
  14. {
  15. // Some general Exception handling that will wrap and send as HTTP Response
  16. }
  17. }

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

  1. @PreAuthorize("hasRole('ROLE_YOURROLE')")
  2. @GetMapping(path = "/your_secured_endpoint", consumes = "application/json",
  3. produces = "application/json")
  4. public ResponseEntity<List<SomePOJOObject>> getAllAppointmentsForPatient()
  5. {
  6. return new ResponseEntity<>(thatSomePOJOObjectListYouWant, HttpStatus.OK);
  7. }
展开查看全部

相关问题