我正在尝试使用 Spring Security Annotations 实现 HTTP Basic Auth。
我有一个 REST 端点,定义如下:
@RequestMapping("/foo/")
我希望只有 Admin 角色的人才能访问/foo/端点。
接下来,我正在配置Spring Security,如下图:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static String REALM="MY_TEST_REALM";
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("ADMIN");
auth.inMemoryAuthentication().withUser("tom").password("abc123").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//http.csrf().disable()
http
.authorizeRequests()
.antMatchers("/foo/").hasRole("ADMIN")
.and().httpBasic().realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint())
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);//We don't need sessions to be created.
}
@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
return new CustomBasicAuthenticationEntryPoint();
}
/* To allow Pre-flight [OPTIONS] request from browser */
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}
}
所以,我只希望使用密码 abc123 的账单用户名能够调用 REST 端点。
接下来,我定义了应该返回的错误
public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
//Authentication failed, send error response.
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 : " + authException.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("MY_TEST_REALM");
super.afterPropertiesSet();
}
}
我尝试使用 Postman 进行测试,我使用的是具有正确凭据的 Basic Auth,但我总是收到 401 错误。我错过了任何一步吗?
请参阅以下来自 Postman 的屏幕截图。我错过了任何标题吗?
而且,这是标题部分
(我在上面的屏幕截图中隐藏了基本 URL)
最佳答案
编辑
别忘了制作 SecurityConfiguration
工作。
喜欢 @Import({ SecurityConfiguration.class })
或 ComponentScan("<packageName>")
关于spring - 在 Spring Security 中实现 Basic Auth 后总是收到 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228917/