【问题标题】:Is there any Spring Security extension for REST services?REST 服务是否有任何 Spring Security 扩展?
【发布时间】:2019-01-26 00:55:34
【问题描述】:

我正在使用 Spring Boot 构建 REST API,并使用 Spring Security。我开始here,但发现了一些其他教程和博客文章与这个问题并在实现自定义内容后设法让它工作。 Thisthis SO 帖子回答了我的一些问题,但我还有一个问题:

是否有任何扩展实现了某些功能,例如返回 401 而不是重定向的 REST AuthenticationEntryPoint,或者 JWT 生成和验证,或者我应该为每个 REST 服务实现相同的功能?

感谢您的回答。

【问题讨论】:

    标签: java spring rest spring-boot spring-security


    【解决方案1】:

    @布朗尼..... 试试这个....

    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.security.web.AuthenticationEntryPoint;
    import org.springframework.stereotype.Component;
    
    @Component
    public class RESTAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        }
    }
    

    @Autowired
        private RESTAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Override
        protected void configure(final HttpSecurity http) throws Exception {
            http.cors().and().exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint).and().authorizeRequests()......
    

    在您的安全配置类中添加 RESTAuthenticationEntryPoint 和配置,然后如果身份验证失败,它将返回 401。

    【讨论】:

      【解决方案2】:

      我也使用 Springboot,但为了安全起见,我依赖 Apache Shiro project,这基本上取决于您存储用户帐户的方式(我的帐户位于 MongoDb 实例中),

      • 负责登录 - currentUser.login(token);
      • 如果失败则抛出异常,以便您处理响应
      • 如果成功在响应中注入身份验证 cookie
      • 对于任何其他请求,解码 cookie 并向用户注入适当的授权

      简而言之,Shiro 不会重定向 HTTPRequest,因为它只关心安全性,留下进一步的决定,在您的情况下重定向到您的控制器逻辑。 您可以使用简单的 Maven 依赖项将其添加到您的项目中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 2015-08-27
        • 2020-02-07
        • 2017-04-21
        • 1970-01-01
        相关资源
        最近更新 更多