spring-boot - HttpSecurity Spring Boot 配置
问题描述
我需要配置 3 个端点,2 个带身份验证,1 个不带。问题是我得到了所有带有 401 Unauthorized 错误的端点。
/users
无需身份验证/users/1
需要认证/details/1
需要认证
我正在使用依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
我实现了这个类:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin")
.password("pwd")
.roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/users").hasAnyRole("ADMIN", "USER")
.anyRequest().permitAll()
.and()
.authorizeRequests()
.anyRequest().hasAnyRole("ADMIN", "USER");
}
}
解决方案
根据您的要求,您只需要简单的 http 配置,所有用户都可以作为公共 url 访问 GET 用户,而其他需要基本身份验证的 ..below 将为您工作。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/users").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
推荐阅读
- php - 如何在php中最后一个下划线(_)字符之前获取整个字符串?
- javascript - 在异步等待中捕获错误
- wpf - WPF MVVM - 带参数的全局命令
- coq - Coq - 如何证明 eqb_neq?
- unix - 有人可以帮助为什么我的 zcat 命令不起作用吗?
- java - 创建只接受非抽象类类型的java方法
- c# - 在 UWP 应用程序中播放内置网络摄像头源后停止工作?
- firefox - GCloud 负载均衡器会话亲和性 cookie `Set-Cookie` 标头 - 由于滥用 `sameSite` 属性而在 Firefox 中出错
- karma-jasmine - Angular 6 的 Jenkins 上的无头 Chrome 问题
- java - ServerSocket 不接受来自客户端的新连接/请求