Spring REST 安全:仅在特定端点上启用基本身份验证
Spring REST Security : Enable Basic Authentication only on a specific endpoint
我已经为我的 REST API 配置了 Spring 安全性(使用 HeaderHttpSessionStrategy)。
我的 'WebSecurityConfigurerAdapter' 实现如下所示。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/**").permitAll()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic()
;
}
现在,我如何配置 'HttpSecurity' object 以便基本身份验证仅适用于特定端点。
例如:
/user/login : 基本认证应该只能在这端进行 point.After 认证成功 x-auth-token header 是 returned.
/user/create :客户端不应该能够在此 endpoint.Should 上进行身份验证,仅 return 401.Can 只能使用'x-auth-token' 使用 /user/login 端点创建。
您可以定义多个 WebSecurityConfigurerAdapter
。一个更高优先级的请求匹配器将适用性限制为 /user/login
,例如:http.requestMatcher(new AntPathRequestMatcher("/user/login"))
,另一个作为其余部分的包罗万象。您可以省略 requestMatcher
以使 http 定义不受限制。
您必须始终定义从特定到通用的限制。在您的情况下,它应该是针对一般安全检查的特定 URL 检查。
- 您应该配置并允许登录/注册 URLs。
- 您应该避免模式 /** 允许所有。而是单独配置静态资源 URL。
你最终应该像你在 URL 中提到的那样应用更通用的限制,/user/** 进行身份验证并拥有一些角色。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/user/login, /user/signup, /logout").permitAll()
.antMatchers("/user/**").hasRole("ADMIN")
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic();
}
我已经为我的 REST API 配置了 Spring 安全性(使用 HeaderHttpSessionStrategy)。
我的 'WebSecurityConfigurerAdapter' 实现如下所示。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/**").permitAll()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic()
;
}
现在,我如何配置 'HttpSecurity' object 以便基本身份验证仅适用于特定端点。
例如:
/user/login : 基本认证应该只能在这端进行 point.After 认证成功 x-auth-token header 是 returned.
/user/create :客户端不应该能够在此 endpoint.Should 上进行身份验证,仅 return 401.Can 只能使用'x-auth-token' 使用 /user/login 端点创建。
您可以定义多个 WebSecurityConfigurerAdapter
。一个更高优先级的请求匹配器将适用性限制为 /user/login
,例如:http.requestMatcher(new AntPathRequestMatcher("/user/login"))
,另一个作为其余部分的包罗万象。您可以省略 requestMatcher
以使 http 定义不受限制。
您必须始终定义从特定到通用的限制。在您的情况下,它应该是针对一般安全检查的特定 URL 检查。
- 您应该配置并允许登录/注册 URLs。
- 您应该避免模式 /** 允许所有。而是单独配置静态资源 URL。
你最终应该像你在 URL 中提到的那样应用更通用的限制,/user/** 进行身份验证并拥有一些角色。
@Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/user/login, /user/signup, /logout").permitAll() .antMatchers("/user/**").hasRole("ADMIN") .and() .requestCache() .requestCache(new NullRequestCache()) .and() .httpBasic();
}