java - 添加凭据以访问 REST 控制器
问题描述
我有一个带有多个控制器的 Web 服务。我只需要为其中一个添加身份验证。其余的应该保持没有身份验证。请注意,我只需要在请求标头中添加用户名和密码。没有登录表格。我正在使用弹簧启动应用程序。
我试过的代码:
@Configuration
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}pass").roles("ADMIN");
}
// Secure the endpoints with HTTP Basic authentication
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//HTTP Basic authentication
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/myController").hasRole("ADMIN")
.and()
.csrf().disable()
.formLogin().disable();
}
但是,它不要求用户和密码。如果我删除 {noop} 它会但会抛出无效密码编码器的异常
解决方案
我最终使用以下代码解决了我的问题:
@Configuration 公共类 ApplicationSecurityConfig 扩展 WebSecurityConfigurerAdapter {
public static String ROLE_NAME = "ROLENAME";
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new Pbkdf2PasswordEncoder("key", 10000, 128))
.withUser("userName").password("encryptedPassword").roles(ROLE_NAME);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/securedPath").hasRole(ROLE_NAME)
.and()
.csrf().disable()
.formLogin().disable();
}
}
您可以配置加密密码并对此代码应用所需的任何更改。主要目标是只保护一个带有路径securedPath的其余API,给定的用户名和密码可以在加密或不加密的情况下使用。在我的示例中,我使用了加密密码并将其添加到配置文件中。这个类会自动解密密码并使用它。无需 UI,因为浏览器会自动弹出登录表单。
推荐阅读
- php - WooCommerce:在不接触模板的情况下禁用产品循环
- javascript - 在 WooCommerce 商店页面上添加数量字段并添加到购物车按钮
- mysql - 为什么 MySQL InnoDB 在发生重复键错误时对重复索引记录设置 S 或 X Next-Key 锁?
- r - [TypeError]:无法读取 Null 的属性“substr”
- vhdl - VHDL:案例语句选择必须涵盖表达式的所有可能值
- python - Pandas groupby 在某些特定组中划分连续行
- sql - 这可以作为 SQL VIEW 完成吗
- git - 有没有办法将文件保存在 GIT 存储库中并在本地删除它而不提交删除?
- apache-flink - Flink Logging 在集群模式下不工作
- google-cloud-platform - GCSFileSystem 的 requests_timeout 参数缺少文档