Spring Securityの基本認証
1. 概要
このチュートリアルでは、Basic Authentication with Springを設定、構成、およびカスタマイズする方法を示します。 単純なSpring MVC exampleの上に構築し、SpringSecurityが提供する基本認証メカニズムを使用してMVCアプリケーションのUIを保護します。
2. Springセキュリティ構成
Java configを使用してSpring Securityを構成できます。
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1Pass"))
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/securityNone").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(),
BasicAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
ここでは、WebSecurityConfigurerAdapter.を拡張するクラスのconfigure()メソッド内で、httpBasic()要素を使用して基本認証を定義しています。
XMLを使用しても同じことが実現できます。
ここで関連するのは、構成のメインの<http>要素内の<http-basic>要素です。これは、アプリケーション全体の基本認証を有効にするのに十分です。 認証マネージャーはこのチュートリアルの焦点ではないため、プレーンテキストで定義されたユーザーとパスワードでインメモリーマネージャーを使用しています。
Spring Securityを有効にするWebアプリケーションのweb.xmlについては、Spring Logout tutorialですでに説明しています。
3. 保護されたアプリケーションの消費
curlコマンドは、セキュリティで保護されたアプリケーションを使用するための頼りになるツールです。
まず、セキュリティ認証情報を提供せずに/homepage.htmlをリクエストしてみましょう。
curl -i http://localhost:8080/spring-security-rest-basic-auth/api/foos/1
予想される401 Unauthorizedとthe Authentication Challengeを取得します。
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-mvc-basic-auth/; HttpOnly
WWW-Authenticate: Basic realm="Spring Security Application"
Content-Type: text/html;charset=utf-8
Content-Length: 1061
Date: Wed, 29 May 2013 15:14:08 GMT
ブラウザはこの課題を解釈し、簡単なダイアログで資格情報の入力を求めますが、curlを使用しているため、そうではありません。
それでは、同じリソース(ホームページ)をリクエストしましょう。ただし、provide the credentialsもそれにアクセスします。
curl -i --user user1:user1Pass
http://localhost:8080/spring-security-rest-basic-auth/api/foos/1
これで、サーバーからの応答はCookieとともに200 OKになります。
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-mvc-basic-auth/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Content-Length: 90
Date: Wed, 29 May 2013 15:19:38 GMT
ブラウザーからは、アプリケーションを通常どおり使用できます。唯一の違いは、すべてのブラウザーが基本認証をサポートし、ダイアログを使用してユーザーに資格情報の入力を求めるため、ログインページが厳しい要件ではなくなることです。
4. さらなる構成– エントリーポイント
デフォルトでは、Spring SecurityによってプロビジョニングされたBasicAuthenticationEntryPointは、401 Unauthorized応答の全ページをクライアントに返します。 このエラーのHTML表現はブラウザーで適切にレンダリングされますが、json表現が優先される可能性のあるREST APIなどの他のシナリオにはあまり適していません。
名前空間は、この新しい要件にも十分に柔軟であるため、これに対処するために、エントリポイントをオーバーライドできます。
新しいエントリポイントは標準Beanとして定義されます。
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(
HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm="" + getRealmName() + """);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("example");
super.afterPropertiesSet();
}
}
HTTP応答に直接書き込むことで、応答本文の形式を完全に制御できるようになりました。
5. Mavenの依存関係
Spring SecurityのMaven依存関係については、以前にSpring Security with Maven articleで説明しました。実行時にspring-security-webとspring-security-configの両方を使用できる必要があります。
6. 結論
この例では、Spring SecurityとBasic Authenticationを使用してMVCアプリケーションを保護しました。 XML構成について説明し、簡単なcurlコマンドでアプリケーションを使用しました。 最終的に正確なエラーメッセージ形式を制御しました。標準のHTMLエラーページからカスタムテキストまたはJSON形式に移行しました。
このチュートリアルの完全な実装はthe GitHub projectにあります。これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。
プロジェクトをローカルで実行すると、サンプルHTMLにアクセスできます。