Spring Security ,从表中获取方法和url,并友好地验证授权请求

tcbh2hod  于 2021-10-10  发布在  Java
关注(0)|答案(2)|浏览(272)

我有这个来验证方法和资源以及角色,但我不能相信这部分需要在代码中设置,存在一个查询表的方法吗?
例如

table: user_access <br>
campos: url , path <br>
method="HttpMethod.GET" <br>
path="/api/clientes/page/**"

我有这个密码:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    //implementar reglas de seguridad para los end points
    //por el lado de oauth
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //reglas especificate al mas generico

**//I Dont like this part and i try to creat it dinamicly**

        http.authorizeRequests().antMatchers(HttpMethod.GET,"/api/clientes","/api/clientes/page/*","/api/clientes/img/*","/images/**").permitAll()
        .antMatchers(HttpMethod.GET,"/api/clientes/form/").hasAnyRole("ADMIN","SUPER_ADMIN")
        .antMatchers(HttpMethod.POST,"/api/clientes/uploads").hasAnyRole("ADMIN","SUPER_ADMIN")
        .antMatchers(HttpMethod.POST,"/api/clientes").hasAnyRole("ADMIN","SUPER_ADMIN")
        .antMatchers(HttpMethod.DELETE,"/api/clientes/{id}").hasRole("SUPER_ADMIN")
        .antMatchers(HttpMethod.GET,"/api/clientes/{id}").hasRole("SUPER_ADMIN")
        .anyRequest().authenticated()
        .and().cors().configurationSource(cousConfigurationSource()); //error en el cors con esto se arregla para la pagina de angular

    }

    //importante no tomar cors.reactive 
    @Bean
    public CorsConfigurationSource cousConfigurationSource() {

        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        config.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS")); //se podria poner * para todo
        config.setAllowCredentials(true);
        config.setAllowedHeaders(Arrays.asList("Content-Type","Autorization"));

        UrlBasedCorsConfigurationSource source= new UrlBasedCorsConfigurationSource();

        source.registerCorsConfiguration("/**", config);
        return source;
    }

    //filtro //seleccionar spring Framework
    @Bean
    public FilterRegistrationBean<CorsFilter>  corsFilter(){
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(cousConfigurationSource()));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }

有没有办法让它更有活力?

krugob8w

krugob8w1#

希望下面能有所帮助,
您可以这样做,但在应用程序启动时它会工作,您可以创建一个表来保存所有必需的配置,并且在应用程序开始运行时,您可以编写代码来读取所有配置的值并使用它们来配置 HttpSecurity .

例如:

@Entity
public class UserAccessEntity{

@Id
private String url;
private String methodName;
private List<String> userRoles;
private boolean isPattern;

// setter and getter

}

public interface UserAccessRepository extends CrudRepository<UserAccessEntity,String> {}

然后,只需在从数据库中获取记录后进行配置,如下所示:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private final UserAccessRepository repository;
    public ResourceServerConfig(UserAccessRepository repository){
      this.repository = repository;
    }

    // Configure this as you need.
    @Override
    public void configure(HttpSecurity http) throws Exception {
      repository.findAll().foreach(userAccess -> {
        http.authorizeRequests()
        .antMatchers(userAccess.getMethodName(),userAccess.getUrl())
        .hasAnyRole(userAccess.getRoles())
      });
    }
}

唯一的限制是,您可以在应用程序启动之前预先配置所有访问,如果需要反映用户访问记录的任何更改,则必须重新启动服务器。

lpwwtiir

lpwwtiir2#

我认为@preauthorize可以使您的验证更加动态:您可以为您的控制器进行验证,并使用spel(spring表达式语言)来组合更多的案例。要启用@preauthorize,您需要在websecurityconfig中进行配置

@Configuration
@EnableWebSecurity
//enable for @PreAuthorize
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSercurityConfig extends WebSecurityConfigurerAdapter {
    //configs
}

在我的示例中,“超级管理员”或拥有资源的用户可以从请求中访问数据(获取用户详细信息)。希望这能对你有所帮助。

@RestController
public class UserDetailsController {
    @Autowired
    private UsersService usersService;

    @CrossOrigin(origins = "http://localhost:4200")
    @PreAuthorize("hasAuthority('SUPER_ADMIN')" + "or hasAuthority('USER') and authentication.getName().equals(#username)")
    @GetMapping(path = "/user/{username}")
    public ResponseEntity<?> getUserDetailByUsername(@PathVariable("username") String username, Authentication authentication) {
        return ResponseEntity.ok(usersService.getUserByUsername(username));
    }
}

spel引用文档:spring表达式语言,enable@preauthorize引用:spring方法安全简介

相关问题