8
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Spring Security】URLごとのアクセス制御

Posted at

Spring Securityでアクセス制御を書く機会があったので、備忘録として残します。

WebSecurityConfig.java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
	httpSecurity.authorizeHttpRequests(authorize -> authorize
            // 一般的な静的ファイルパス("/css/**"など)に対し、非ログインでのアクセスを許可
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            // "/hoge"と"/fuga"に対し、非ログインでのアクセスを許可
			.requestMatchers("/hoge", "/fuga").permitAll()
            // "/admin/"が先頭に付くパスすべてに対し、ROLE_ADMINの権限を持つユーザーのみのアクセスを許可
			.requestMatchers("/admin/**").hasRole("ADMIN")
            // 上記で指定していないパスについては、ログイン済みならアクセスを許可
			.anyRequest().authenticated()
		);

	return http.build();
}
  • requestMatchers()
    アクセス制御を設定したいパスを指定する。
  • permitAll()
    認証されていない状態でも、対象パスへのアクセスを許可する。
  • hasRole()
    指定した権限を持つ場合のみ、対象パスへのアクセスを許可する。
    引数に渡した文字列の先頭に、"ROLE_"をくっつけた文字列を権限としてアクセス制御を行うので注意。(上記の例では、"ADMIN"を引数に渡しているため、"ROLE_ADMIN"の権限を持つユーザーのみアクセスを許可す)
  • anyRequest()
    requestMatchers()で指定していないパスを対象とする。
  • authenticated()
    認証されている場合のみ、対象パスへのアクセスを許可する。

参考になれば幸いです。

参考文献

・【Spring Security】認証・認可の基礎
https://b1san-blog.com/post/spring/spring-sec-auth/

8
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?