如何在没有身份验证的情况下实现安全的 REST api 以及 springboot 会话和 spring 安全

时间:2021-04-28 07:42:15

标签: spring-session spring-security-rest

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

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

1 个答案:

答案 0 :(得分:0)

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

因为验证 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);
    }
}
相关问题