Spring Security Annotationsを使用してHTTP Basic Authを実装しようとしています。SpringセキュリティでBasic Authを実装した後、常に401エラーが発生する
@RequestMapping("/foo/")
私は唯一のアクセス/ fooの/エンドポイントに対する管理役割の人々が望む:
は、私は以下のように定義RESTエンドポイントを、持っています。
次は、以下に示すように、私は、春のセキュリティを設定しています:
@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エンドポイントを呼び出すことができるようにしたいです。
次に、私は私が正しい資格情報で基本認証を使用していますが、私は常に401エラーを取得し、
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();
}
}
私はポストマンとのテストを試してみまし返すべきエラーを定義します。私は一歩も逃していますか?
郵便配達員の下のスクリーンショットをご覧ください。ヘッダーがありませんか?
と、ここでヘッダーセクション (私は上のスクリーンショットでは、ベースURLを非表示にしています)
注釈などの
。私の質問は、(Javaクラスの)@Import({SecurityConfiguration.class})アノテーションをどこに置くのですか?それはCustomBasicAuthenticationEntryPoint.javaかSecurityConfiguration.javaかApplication.javaですか? – Sai
私は、任意の成功 @Configuration @import({} SecurityConfiguration.class) publicクラスのAppConfigの助けを{ } – Sai
感謝せずに次のことを試してみました。あなたは正しかった。私はApplication.javaに次の行を追加して、今動作します:ApplicationContext context = new AnnotationConfigApplicationContext( \t \t \t \t AppConfig.class); – Sai