REST服务是否有任何Spring Security扩展?

时间:2018-08-19 20:20:14

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

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

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

谢谢您的回答。

2 个答案:

答案 0 :(得分:0)

我也使用Springboot,但是出于安全性考虑,我依靠Apache Shiro project,它从根本上取决于您存储用户帐户的方式(地雷在MongoDb实例中)

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

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

答案 1 :(得分:0)

@brownies ... 试试这个...。

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和config之上添加,然后如果身份验证失败,它将返回401。