我正在使用Spring Boot构建REST API,并且使用Spring Security。我开始here,但发现了其他一些与此问题有关的教程和博客文章,并在实现自定义内容后设法使其正常工作。 This和this这样的帖子回答了我的一些问题,但我还有一个问题:
是否存在实现某些功能的扩展,例如返回401而不是重定向的REST AuthenticationEntryPoint或JWT生成和验证,或者我应该为每个REST服务实现相同的功能?
谢谢您的回答。
答案 0 :(得分:0)
我也使用Springboot,但是出于安全性考虑,我依靠Apache Shiro project,它从根本上取决于您存储用户帐户的方式(地雷在MongoDb实例中)
简而言之,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。