需要spring security java配置示例,仅显示基本身份验证

时间:2013-07-09 22:00:01

标签: spring-security

我当前的java安全配置如下所示:

@Configuration
@EnableWebSecurity
public class RootConfig extends WebSecurityConfigurerAdapter {

@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
    .withUser("tester").password("passwd").roles("USER");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
     http
     .authorizeUrls()
         .anyRequest().authenticated()
         .and()
     .httpBasic();       
  }
}

当我使用浏览器执行GET请求时,我将收到错误403。 我希望得到一个浏览器弹出窗口,询问我的用户名/密码。 可能是什么问题?

2 个答案:

答案 0 :(得分:13)

更新:这已在Spring Security 3.2.0.RC1 +

中修复

这是安全Java配置中的一个错误,将在下一个版本中解决。我创建了SEC-2198来跟踪它。目前,解决方法是使用以下内容:

@Bean
public BasicAuthenticationEntryPoint entryPoint() {
    BasicAuthenticationEntryPoint basicAuthEntryPoint = new BasicAuthenticationEntryPoint();
    basicAuthEntryPoint.setRealmName("My Realm");
    return basicAuthEntryPoint;
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
        .exceptionHandling()
            .authenticationEntryPoint(entryPoint())
            .and()
        .authorizeUrls()
            .anyRequest().authenticated()
            .and()
        .httpBasic();       
}

PS:感谢您试用Spring Security Java Configuration!保持反馈:)

答案 1 :(得分:0)

使用Spring Security 4.2.3,可能之前只需使用此配置:

@Configuration
@EnableWebSecurity
public class CommonWebSecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(final HttpSecurity http) throws Exception {
     http
        .authorizeRequests()
           .anyRequest().authenticated()
           .and()
        .httpBasic();
  }
  @Autowired
  public void dlcmlUserDetails(final AuthenticationManagerBuilder auth) throws Exception {
      auth.inMemoryAuthentication()
          .withUser("tom").password("111").roles("USER");
  }
}