【问题标题】:How to achieve secure REST api along with springboot session and spring security without authentication如何在没有身份验证的情况下实现安全的 REST api 以及 springboot session 和 spring security
【发布时间】:2021-07-21 13:15:50
【问题描述】:

问题: 我的 java springboot 应用程序从外部系统接收 JWT 令牌,以使用其外部身份管理提供程序对用户进行身份验证,成功后返回用户详细信息。 一旦收到 userdetails,后端应用程序必须为外部系统最终用户创建一个重定向 url。重定向 url 将使用户登陆我的 Angular 应用程序以显示登陆页面。 在这里,所有其余的 api 都应该通过 http 会话被允许。 如果用户试图直接访问其余的 api,他应该得到一个身份验证错误。

在这种情况下我们如何获得授权,因为我的 Spring Boot 应用程序没有完成身份验证。我们可以使用 spring security 创建自定义 Spring session 并手动将 userDetails 放入 SecurityContext 吗?

【问题讨论】:

    标签: spring-session spring-security-rest


    【解决方案1】:

    我目前正在处理从 Google 获得的 JWT 令牌。包括谷歌在内,几乎所有的授权服务器都提供了诸如GET /userInfo之类的REST API,你可以在请求头或URL中携带JWT令牌作为GET参数,然后验证JWT令牌是否有效、未过期等。

    由于验证 JWT 令牌通常是无状态的,因此这些 API 通常具有很大的限制,您可以根据需要多次调用它们。

    我假设您已经集成了 Spring 安全性,然后您可以添加一个过滤器。这样,每个请求都必须在标头中验证其令牌。

    
    @Service
    public class TokenAuthenticationFilter extends OncePerRequestFilter {
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            try {
           String header = request.getHeader("Authorization");
                RestTemplate restTemplate = new RestTemplate(); // If you use Google SDK, xxx SDK, you do not have to use restTemplate 
                String userInfoUrl = "https://example.com/api/userInfo";
    
                HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", header);
    
                HttpEntity entity = new HttpEntity(headers);
    
                ResponseEntity<String> response = restTemplate.exchange(
                        userInfoUrl, HttpMethod.GET, entity, String.class, param);
    
                User user = response.getBody(); // Get your response and figure out if the Token is valid.
    
                 // If the token is valid? Check it here....
    
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
    
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                
            } catch (Exception ex) {
                logger.error("Could not set user authentication in security context", ex);
            }
    
            filterChain.doFilter(request, response);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 2013-12-05
      • 2013-09-29
      相关资源
      最近更新 更多