rest - 没有角色和权限的 Web 服务的 Spring Security
问题描述
我有一个基于 Spring Boot 构建的 REST Web 服务。对于身份验证,我使用 Spring Security 和 Basic Authentication,我对此并不陌生。我是否必须为我的解决方案使用角色和权限?
我只希望 Web 服务的用户声明用户名和密码凭据。我在数据库或其他地方没有任何用户。
在我的 WebSecurityConfigurerAdapter 配置中,我现在.authorities("ROLE_USER");
在我的 configureGlobal 方法的末尾,遵循互联网上的示例。我想跳过它,这样课程看起来像这样:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("username").password(passwordEncoder().encode("password"));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated().and().httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我发现我做不到。如果我改用,我会工作.roles("USER")
。但我既不想处理权限也不想处理角色,只想处理用户名和密码。为什么我需要这个或者我怎么能跳过这个?
我很高兴您可以就此事(身份验证和 Spring Security)向新手提供任何启示。
解决方案
如果您使用inMemoryAuthentication
,您通常通过以下方式提供角色roles("...")
InMemoryAuthentication 不能null
作为 GrantedAuthorities 使用。所以不打电话roles(...)
会导致BeanCreationException
但是没有什么能阻止你提供一个空列表......比如:
@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("username")
.password(passwordEncoder().encode("password"))
.roles(); // <--- leave roles empty
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated().and().httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
注意:不要认为您需要@EnableWebSecurity
或使用configureGlobal
...
或者,您始终可以选择创建自己的自定义 AuthenticationProvider。
自定义 AuthenticationProvider 的配置:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider());
}
@Bean
public AuthenticationProvider authProvider() {
return new CustomAuthenticationProvider();
}
推荐阅读
- javascript - 有没有办法让 superfish 插件与菜单的高度相同?
- javascript - 为 react/phonegap 应用程序存储视频剪辑
- c++ - 如何根据对象是否为右值引用路由到不同的实现?
- c# - 如何使用 html 中的 AJAX 通过另一个动作向一个动作发送请求?
- python - 有条件地在数据框中填充一个值
- angular - 如果验证失败,如何停止 Metronic 向导
- ios - Xcode 10 应用程序上传“协商连接……”
- unit-testing - 添加新数据后如何知道elasticsearch何时准备好进行查询?
- jquery - 根据 currentdate 在 flatpicker 上更改 mintime
- intellij-idea - Intellij 修复检测到的警告 - svn:警告:W155010