SpringSecurityの基本認証
1. 概要
このチュートリアルでは、 Spring を使用した基本認証を設定、構成、およびカスタマイズする方法について説明します。 単純なSpringMVCの例の上に構築し、Springセキュリティによって提供される基本認証メカニズムを使用してMVCアプリケーションのUIを保護します。
2. Springセキュリティ構成
Javaconfigを使用してSpringSecurityを構成できます。
@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();
}
}
ここでは、 httpBasic()要素を使用して、WebSecurityConfigurerAdapter。を拡張するクラスのconfigure()メソッド内で基本認証を定義しています。
XMLを使用しても同じ結果を得ることができます。
<http pattern="/securityNone" security="none"/>
<http use-expressions="true">
<intercept-url pattern="/**" access="isAuthenticated()" />
<http-basic />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="{noop}user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
ここで関連するのは
SpringSecurityを有効にするWebアプリケーションのweb.xmlについては、SpringLogoutチュートリアルですでに説明されています。
3. 保護されたアプリケーションの消費
curl コマンドは、セキュリティで保護されたアプリケーションを使用するための頼りになるツールです。
まず、セキュリティクレデンシャルを提供せずに/homepage.htmlをリクエストしてみましょう。
curl -i http://localhost:8080/spring-security-rest-basic-auth/api/foos/1
予想される401UnauthorizedおよびAuthenticationChallengeを取り戻します。
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 を使用しているため、そうではありません。
次に、同じリソースであるホームページをリクエストしますが、アクセスするための資格情報も提供します。
curl -i --user user1:user1Pass
http://localhost:8080/spring-security-rest-basic-auth/api/foos/1
その結果、サーバーからの応答は 200OKとCookieになります。
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. さらなる構成– tエントリポイント
デフォルトでは、SpringSecurityによってプロビジョニングされたBasicAuthenticationEntryPoint は、 401Unauthorized応答の全ページをクライアントに返します。 エラーのこのHTML表現は、ブラウザで適切にレンダリングされます。 逆に、json表現が優先されるRESTAPIなどの他のシナリオにはあまり適していません。
名前空間は、この新しい要件に対しても十分な柔軟性があります。 これに対処するために、エントリポイントをオーバーライドできます。
<http-basic entry-point-ref="myBasicAuthenticationEntryPoint" />
新しいエントリポイントは、標準の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("Baeldung");
super.afterPropertiesSet();
}
}
HTTP応答に直接書き込むことで、応答本文の形式を完全に制御できるようになりました。
5. Mavenの依存関係
Spring SecurityのMaven依存関係については、 Spring SecuritywithMavenの記事で以前に説明されています。 実行時にspring-security-webとspring-security-configの両方を使用できるようにする必要があります。
6. 結論
この記事では、SpringSecurityと基本認証を使用してMVCアプリケーションを保護しました。 XML構成について説明し、単純なcurlコマンドを使用してアプリケーションを使用しました。 最後に、標準のHTMLエラーページからカスタムテキストまたはJSON形式に移行して、正確なエラーメッセージ形式を制御しました。
この記事の完全な実装は、GitHubプロジェクトにあります。 これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。
プロジェクトがローカルで実行される場合、サンプルHTMLには次の場所からアクセスできます。
http:// localhost:8080 / spring-security-rest-basic-auth / api / foos /1。