You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Spring(JHipster)应用的/api/users接口无需认证访问?

我来帮你搞定这个问题!JHipster默认会给所有/api/**接口加上认证保护,要让/api/users开放给所有用户无需登录访问,需要修改两个核心地方——Spring Security配置和对应的REST接口权限注解:

步骤1:修改Spring Security配置

找到你的SecurityConfiguration.java(通常在src/main/java/[你的包路径]/security目录下),定位到configure(HttpSecurity http)方法。在authorizeRequests()规则里,把/api/users添加到允许匿名访问的列表中,注意要放在其他需要认证的/api/**规则前面,示例代码如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
            .disable()
        .headers()
            .frameOptions()
            .disable()
        .and()
        .authorizeRequests()
            .antMatchers("/api/users").permitAll() // 新增这行,开放/users接口
            .antMatchers("/api/**").authenticated() // 其他/api接口仍保持认证要求
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .and()
        .apply(securityConfigurerAdapter());
}

步骤2:调整UserResource的权限注解

找到UserResource.java(在src/main/java/[你的包路径]/web/rest目录下),查看获取用户列表的getAllUsers()方法。默认情况下这个方法会有@PreAuthorize注解限制只有管理员能访问,我们需要修改或者移除这个注解:

原默认代码可能是这样:

@GetMapping("/users")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public ResponseEntity<List<UserDTO>> getAllUsers() {
    // 方法逻辑
}

修改为开放所有访问:

@GetMapping("/users")
@PreAuthorize("permitAll()") // 或者直接删除这个@PreAuthorize注解
public ResponseEntity<List<UserDTO>> getAllUsers() {
    // 方法逻辑
}

最后验证

修改完成后重启你的JHipster应用,再用Postman请求http://localhost:8080/api/users,就能直接获取完整的用户列表,不需要携带任何认证令牌了。

内容的提问来源于stack exchange,提问作者Ginel Guiu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:07:57