LoginSignup
0
0

More than 5 years have passed since last update.

spring boot アクセス認可 RESTful API

Last updated at Posted at 2018-11-20

概要

特定のURLにアクセスするために必要な権限を設定する

環境

JDK 1.8.0_144
spring-boot 1.5.10
spring-security 4.2.4

前提条件

ログイン時などにあらかじめ権限情報は取得しておく。(今回はそこじゃないので)
今回はすでにADMIN権限を取得できることが前提。

実装する箇所

  • SecurityConfig
  • Controllerメソッド

実装

  • SecurityConfig
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //...
}

すでにある(あるよね?)SecurityConfigクラスにアノテーション
@EnableGlobalMethodSecurity(prePostEnabled = true)
を追加する。

  • Controllerメソッド
@PreAuthorize("hasAuthority('ADMIN')")
//Controller
public void sampleAuth() {
    //…
}

アノテーション
@PreAuthorize("hasAuthority('ADMIN')")
を追加すると、このControllerメソッドには"ADMIN"権限を持つユーザーのみがアクセスできるようになる。

@PreAuthorizeの特性

式が利用できる
例えば、[ADMIN] と [MEMBER] という権限を持つユーザーのリクエストのみを認可したい場合
@PreAuthorize("hasAuthority('ADMIN OR hasAuthority('MEMBER')")
という使い方ができる。これ以外にも [AND] [OR] [NOT(!)] などが使用できる。

0
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
0
0