【发布时间】:2017-05-04 21:04:45
【问题描述】:
我正在尝试使用 Spring Security Annotations 实现 HTTP Basic Auth。
我有一个 REST 端点,定义如下:
@RequestMapping("/foo/")
我希望只有管理员角色的人才能访问 /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 进行测试,我正在使用具有正确凭据的基本身份验证,但我总是收到 401 错误。我是否缺少任何步骤?
【问题讨论】:
标签: spring spring-boot spring-security