我使用SpringSecurity、JWT和OAuth2实现了身份验证。
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.POST,"/v1/register").permitAll()
.antMatchers(HttpMethod.GET,"/v1/public").permitAll();
List<String> permisos = roleService.findPermisos();
for(String name: permisos) {
String[] data = name.split(",");
http.authorizeRequests().antMatchers(data[0], data[1]).hasRole(data[2]);
}
http.authorizeRequests()
.anyRequest().authenticated()
.and().cors().configurationSource(corsConfigurationSource());
}
目前,configure(HttpSecurity http)
方法在OAuth2端工作。在我的数据库中,每个角色都被允许或拒绝访问它们的所有@RestController
,问题是,只有在编译了应用程序之后才应用它,而我需要的是在修改允许或拒绝访问时应用它,而不需要重新编译List<String> permisos = roleService.findPermisos()
中显示的动态acl。
搜索我读到,我可以使用过滤器与HttpSecurity,我一直未能找到例子,请您的帮助。
发布于 2022-03-21 03:01:56
通过一些研究,我修改了我的解决方案如下:
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.PUT,"/v1/menu").permitAll()
.anyRequest().authenticated().and()
.addFilterAfter(new CustomFilter(), AbstractPreAuthenticatedProcessingFilter.class)
.cors().configurationSource(corsConfigurationSource());
}
我添加了一个过滤器addFilterAfter(new CustomFilter(), AbstractPreAuthenticatedProcessingFilter.class)
,在CustomFilter()
中是:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
ServletContext servletContext = request.getServletContext();
if(usuarioService == null){
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
usuarioService = webApplicationContext.getBean(IUsuarioService.class);
}
String[] path = request.getRequestURI().split("/");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Usuario usuario = usuarioService.findByEmail(authentication.getName());
if(usuarioService.existsPermission(request.getMethod(), path[2], authentication.getName())) {
filterChain.doFilter(request, response);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
所以我把我的解决方案从循环改为通过过滤器查询,问题是所有其他的都必须注册和验证,这将是允许访问我不希望被验证的资源的问题。
如果你有更好的解决方案,我会非常感谢你的帮助。
https://stackoverflow.com/questions/71490064
复制相似问题