Spring Securityによるカスタムセキュリティ表現

Spring Securityを使用したカスタムセキュリティ式

1. 概要

このチュートリアルでは、creating a custom security expression with Spring Securityに焦点を当てます。

時々、the expressions available in the frameworkは単に十分に表現力がありません。 そして、これらの場合、既存の表現よりも意味的に豊富な新しい表現を構築するのは比較的簡単です。

最初にカスタムPermissionEvaluatorを作成する方法、次に完全にカスタムの式を作成する方法、最後に組み込みのセキュリティ式の1つをオーバーライドする方法について説明します。

2. ユーザーエンティティ

まず、新しいセキュリティ式を作成するための基盤を準備しましょう。

PrivilegesOrganizationを持つUserエンティティを見てみましょう。

@Entity
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    private String password;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "users_privileges",
      joinColumns =
        @JoinColumn(name = "user_id", referencedColumnName = "id"),
      inverseJoinColumns =
        @JoinColumn(name = "privilege_id", referencedColumnName = "id"))
    private Set privileges;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "organization_id", referencedColumnName = "id")
    private Organization organization;

    // standard getters and setters
}

そして、これが私たちの単純なPrivilegeです:

@Entity
public class Privilege {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false, unique = true)
    private String name;

    // standard getters and setters
}

そして私たちのOrganization

@Entity
public class Organization {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false, unique = true)
    private String name;

    // standard setters and getters
}

最後に、より単純なカスタムPrincipalを使用します。

public class MyUserPrincipal implements UserDetails {

    private User user;

    public MyUserPrincipal(User user) {
        this.user = user;
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public Collection getAuthorities() {
        List authorities = new ArrayList();
        for (Privilege privilege : user.getPrivileges()) {
            authorities.add(new SimpleGrantedAuthority(privilege.getName()));
        }
        return authorities;
    }

    ...
}

これらのクラスがすべて準備できたら、基本的なUserDetailsService実装でカスタムPrincipalを使用します。

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        return new MyUserPrincipal(user);
    }
}

ご覧のとおり、これらの関係について複雑なことは何もありません。ユーザーには1つ以上の権限があり、各ユーザーは1つの組織に属しています。

3. データ設定

次へ–簡単なテストデータでデータベースを初期化しましょう。

@Component
public class SetupData {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PrivilegeRepository privilegeRepository;

    @Autowired
    private OrganizationRepository organizationRepository;

    @PostConstruct
    public void init() {
        initPrivileges();
        initOrganizations();
        initUsers();
    }
}

initメソッドは次のとおりです。

private void initPrivileges() {
    Privilege privilege1 = new Privilege("FOO_READ_PRIVILEGE");
    privilegeRepository.save(privilege1);

    Privilege privilege2 = new Privilege("FOO_WRITE_PRIVILEGE");
    privilegeRepository.save(privilege2);
}
private void initOrganizations() {
    Organization org1 = new Organization("FirstOrg");
    organizationRepository.save(org1);

    Organization org2 = new Organization("SecondOrg");
    organizationRepository.save(org2);
}
private void initUsers() {
    Privilege privilege1 = privilegeRepository.findByName("FOO_READ_PRIVILEGE");
    Privilege privilege2 = privilegeRepository.findByName("FOO_WRITE_PRIVILEGE");

    User user1 = new User();
    user1.setUsername("john");
    user1.setPassword("123");
    user1.setPrivileges(new HashSet(Arrays.asList(privilege1)));
    user1.setOrganization(organizationRepository.findByName("FirstOrg"));
    userRepository.save(user1);

    User user2 = new User();
    user2.setUsername("tom");
    user2.setPassword("111");
    user2.setPrivileges(new HashSet(Arrays.asList(privilege1, privilege2)));
    user2.setOrganization(organizationRepository.findByName("SecondOrg"));
    userRepository.save(user2);
}

ご了承ください:

  • ユーザー「john」にはFOO_READ_PRIVILEGEしかありません

  • ユーザー「tom」にはFOO_READ_PRIVILEGEFOO_WRITE_PRIVILEGEの両方があります

4. カスタムパーミッションエバリュエーター

この時点で、新しいカスタム権限エバリュエーターを使用して、新しい式の実装を開始する準備が整いました。

メソッドを保護するためにユーザーの権限を使用しますが、ハードコードされた権限名を使用する代わりに、よりオープンで柔軟な実装に到達したいと考えています。

始めましょう。

4.1. PermissionEvaluator

独自のカスタム権限エバリュエーターを作成するには、PermissionEvaluatorインターフェースを実装する必要があります。

public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(
      Authentication auth, Object targetDomainObject, Object permission) {
        if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)){
            return false;
        }
        String targetType = targetDomainObject.getClass().getSimpleName().toUpperCase();

        return hasPrivilege(auth, targetType, permission.toString().toUpperCase());
    }

    @Override
    public boolean hasPermission(
      Authentication auth, Serializable targetId, String targetType, Object permission) {
        if ((auth == null) || (targetType == null) || !(permission instanceof String)) {
            return false;
        }
        return hasPrivilege(auth, targetType.toUpperCase(),
          permission.toString().toUpperCase());
    }
}

hasPrivilege()メソッドは次のとおりです。

private boolean hasPrivilege(Authentication auth, String targetType, String permission) {
    for (GrantedAuthority grantedAuth : auth.getAuthorities()) {
        if (grantedAuth.getAuthority().startsWith(targetType)) {
            if (grantedAuth.getAuthority().contains(permission)) {
                return true;
            }
        }
    }
    return false;
}

これで、新しいセキュリティ式が使用可能になり、使用できるようになりました:hasPermission

したがって、よりハードコードされたバージョンを使用する代わりに:

@PostAuthorize("hasAuthority('FOO_READ_PRIVILEGE')")

useを使用できます:

@PostAuthorize("hasPermission(returnObject, 'read')")

or

@PreAuthorize("hasPermission(#id, 'Foo', 'read')")

注:#idはメソッドパラメータを参照し、 ‘Foo‘はターゲットオブジェクトタイプを参照します。

4.2. メソッドのセキュリティ構成

CustomPermissionEvaluatorを定義するだけでは不十分です。メソッドのセキュリティ構成でも使用する必要があります。

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler =
          new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator());
        return expressionHandler;
    }
}

4.3. 実際の例

ここで、いくつかの簡単なコントローラーメソッドで新しい式の使用を開始しましょう。

@Controller
public class MainController {

    @PostAuthorize("hasPermission(returnObject, 'read')")
    @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}")
    @ResponseBody
    public Foo findById(@PathVariable long id) {
        return new Foo("Sample");
    }

    @PreAuthorize("hasPermission(#foo, 'write')")
    @RequestMapping(method = RequestMethod.POST, value = "/foos")
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public Foo create(@RequestBody Foo foo) {
        return foo;
    }
}

そして、これで完了です。すべての準備が整い、実際に新しい式を使用しています。 __

4.4. ライブテスト

ここで、簡単なライブテストを作成しましょう。APIを使用して、すべてが正常に機能していることを確認します。

@Test
public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() {
    Response response = givenAuth("john", "123").get("http://localhost:8081/foos/1");
    assertEquals(200, response.getStatusCode());
    assertTrue(response.asString().contains("id"));
}

@Test
public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() {
    Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE)
                                                .body(new Foo("sample"))
                                                .post("http://localhost:8081/foos");
    assertEquals(403, response.getStatusCode());
}

@Test
public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() {
    Response response = givenAuth("tom", "111").contentType(MediaType.APPLICATION_JSON_VALUE)
                                               .body(new Foo("sample"))
                                               .post("http://localhost:8081/foos");
    assertEquals(201, response.getStatusCode());
    assertTrue(response.asString().contains("id"));
}

そして、これがgivenAuth()メソッドです。

private RequestSpecification givenAuth(String username, String password) {
    FormAuthConfig formAuthConfig =
      new FormAuthConfig("http://localhost:8081/login", "username", "password");

    return RestAssured.given().auth().form(username, password, formAuthConfig);
}

5. 新しいセキュリティ表現

以前のソリューションでは、hasPermission式を定義して使用することができました。これは非常に便利です。

ただし、ここでは、式自体の名前とセマンティクスによって、まだいくらか制限されています。

したがって、このセクションでは、完全なカスタムを実行し、isMember()というセキュリティ式を実装して、プリンシパルが組織のメンバーであるかどうかを確認します。 __

5.1. カスタムメソッドセキュリティ式

この新しいカスタム式を作成するには、すべてのセキュリティ式の評価が始まるルートノートを実装することから始める必要があります。

public class CustomMethodSecurityExpressionRoot
  extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    public CustomMethodSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }

    public boolean isMember(Long OrganizationId) {
        User user = ((MyUserPrincipal) this.getPrincipal()).getUser();
        return user.getOrganization().getId().longValue() == OrganizationId.longValue();
    }

    ...
}

ここで、この新しい操作をルートノートでどのように提供したか。 isMember()は、現在のユーザーが指定されたOrganizationのメンバーであるかどうかを確認するために使用されます。

また、SecurityExpressionRootを拡張して、組み込み式も含める方法にも注意してください。

5.2. カスタム式ハンドラー

次に、式ハンドラーにCustomMethodSecurityExpressionRootを挿入する必要があります。

public class CustomMethodSecurityExpressionHandler
  extends DefaultMethodSecurityExpressionHandler {
    private AuthenticationTrustResolver trustResolver =
      new AuthenticationTrustResolverImpl();

    @Override
    protected MethodSecurityExpressionOperations createSecurityExpressionRoot(
      Authentication authentication, MethodInvocation invocation) {
        CustomMethodSecurityExpressionRoot root =
          new CustomMethodSecurityExpressionRoot(authentication);
        root.setPermissionEvaluator(getPermissionEvaluator());
        root.setTrustResolver(this.trustResolver);
        root.setRoleHierarchy(getRoleHierarchy());
        return root;
    }
}

5.3. メソッドのセキュリティ構成

ここで、メソッドのセキュリティ構成でCustomMethodSecurityExpressionHandlerを使用する必要があります。

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        CustomMethodSecurityExpressionHandler expressionHandler =
          new CustomMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator());
        return expressionHandler;
    }
}

5.4. 新しい式の使用

isMember()を使用してコントローラーメソッドを保護する簡単な例を次に示します。

@PreAuthorize("isMember(#id)")
@RequestMapping(method = RequestMethod.GET, value = "/organizations/{id}")
@ResponseBody
public Organization findOrgById(@PathVariable long id) {
    return organizationRepository.findOne(id);
}

5.5. ライブテスト

最後に、ユーザー「john」の簡単なライブテストを次に示します。

@Test
public void givenUserMemberInOrganization_whenGetOrganization_thenOK() {
    Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/1");
    assertEquals(200, response.getStatusCode());
    assertTrue(response.asString().contains("id"));
}

@Test
public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() {
    Response response = givenAuth("john", "123").get("http://localhost:8081/organizations/2");
    assertEquals(403, response.getStatusCode());
}

6. 組み込みのセキュリティ式を無効にする

最後に、組み込みのセキュリティ式をオーバーライドする方法を見てみましょう。hasAuthority()を無効にする方法について説明します。

6.1. カスタムセキュリティ式ルート

同様に、独自のSecurityExpressionRootを作成することから始めます。これは主に、組み込みメソッドがfinalであるため、それらをオーバーライドできないためです。

public class MySecurityExpressionRoot implements MethodSecurityExpressionOperations {
    public MySecurityExpressionRoot(Authentication authentication) {
        if (authentication == null) {
            throw new IllegalArgumentException("Authentication object cannot be null");
        }
        this.authentication = authentication;
    }

    @Override
    public final boolean hasAuthority(String authority) {
        throw new RuntimeException("method hasAuthority() not allowed");
    }
    ...
}

このルートノートを定義したら、それを式ハンドラーに挿入してから、上記のセクション5で行ったように、そのハンドラーを構成にワイヤリングする必要があります。

6.2. 例–式の使用

ここで、hasAuthority()を使用してメソッドを保護する場合、次のように、メソッドにアクセスしようとするとRuntimeExceptionがスローされます。

@PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')")
@RequestMapping(method = RequestMethod.GET, value = "/foos")
@ResponseBody
public Foo findFooByName(@RequestParam String name) {
    return new Foo(name);
}

6.3. ライブテスト

最後に、簡単なテストを示します。

@Test
public void givenDisabledSecurityExpression_whenGetFooByName_thenError() {
    Response response = givenAuth("john", "123").get("http://localhost:8081/foos?name=sample");
    assertEquals(500, response.getStatusCode());
    assertTrue(response.asString().contains("method hasAuthority() not allowed"));
}

7. 結論

このガイドでは、既存のセキュリティ式では不十分な場合に、SpringSecurityでカスタムセキュリティ式を実装するさまざまな方法について詳しく説明しました。

そして、いつものように、完全なソースコードはover on GitHubで見つけることができます。