Flutter医疗健康认证插件fhir_auth的使用

发布于 1周前 作者 zlyuanteng 来自 Flutter

Flutter医疗健康认证插件fhir_auth的使用

标题

fhir_auth

内容

This package is supposed to allow easier authentication for FHIR applications (mostly using SMART on FHIR, although there’s also support for general oauth2 and Google authentication). I will say, this continues to be the most frustrating package to try and develop/support. I continue to feel as though, even though each server that I work with SAYS that they support SMART on FHIR, and yet I still always struggle and fight with the process. Currently I’m successfully able to authenticate against GCP, Aidbox, Interopland, and MELD, and hopefully Azure soon. I still haven’t gotten to AWS. These all work for both mobile and web. If anyone has practice authenticating against any other servers, please let me know!

Fhl7.org is the registered trademark of HL7 and is used with the permission of HL7. Use of the FHL7 trademark does not constitute endorsement of this product by HL7.

Full SMART on FHIR All SMART on FHIR capabilities defined, all scopes allowed, all FHIR versions (Dstu2, Stu3, R4 and preview R5 #3) defined. Currently it only allows external to EHR launches, but soon should also support EHR launches.

Setup Setting up your app, because it go deeper in Android and iOS than most, is a pain. I’m using oauth2_client. And accordingly, I have followed their recommendations for setup (note, these are not exactly the same as my previous setup).

I’ve included examples in mobileauthdemo as well as webauthdemo.

Android Setup In your file android/app/build.gradle you should have a section entitled defaultConfig, you need to change it so that it looks similar to the following (please note the update, that for manifestPlaceholders it it now advised that you do += instead of simply =):

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "your.application.id"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        manifestPlaceholders += [
            'appAuthRedirectScheme': 'your.application.id'
        ]
    }

A few notes. 1 minSdkVersion needs at least 1, and preferably something like 21 or 23. “your.application.id” is usually a reverse of a typicaly url format, so could be something like: “dev.fhirfli.application”. This is also going to be your callback, although it should be something like: dev.fhirfli.application://callback (or in the case of google, sometimes they only allow a single slash, i.e. dev.fhirfli.application:/callback.

While it may not be completely necessary, I add the manifestPlaceholders as formatted above.

In the AndroidManifest.xml file (android/app/src/main/AndroidManifest.xml), you will need to add this section. You should be able to add it before or after the MainActivity.

<activity android:name="com.linusu.flutter_web_auth.CallbackActivity" >
  <intent-filter android:label="flutter_web_auth">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="dev.fhirfli.mobileauthdemo" />
  </intent-filter>
</activity>

iOS Setup You must set the platform in ios/Podfile

platform :ios, '1 11.0'

Basic Example Setup SmartClient

  final client = SmartClient.getSmartClient(
    fhirUrl: FhirUri(url),
    clientId: clientId,
    redirectUri: fhirCallback,
    Scopes(
      clinicalScopes: [
        ClinicalScope(
          role: Role.patient,
          resourceType: R4ResourceType.Patient,
          interaction: Interaction.any,
        ),
      ],
      openid: true,
      offlineAccess: true,
    ),
    secret: secret, /// should not be used
    authUrl: authUrl == null ? null : FhirUri(authUrl),
    tokenUrl: tokenUrl == null ? null : FhirUri(tokenUrl),
  );

Workflow

  await client.login();
  final request1 = FhirRequest.create(
    base: client.fhirUri!.value!,
    resource: _newPatient,
    fhirClient: client,
  );
  final response = await request.request();

Mobile Auth by Provider Google’s Healthcare API To briefly setup your app (assuming you have your GCP setup completed).

1 through the APIs & Services -> OAuth consent screen (fill in everything, including support email, and your authorized domains as your GCP domain) Your sensitive scopes - Cloud Healthcare API APIs & Services -> Credentials -> Create OAuth client ID Package name should be (assuming API file above): com.myshiny.newapp You do need the SHA-1 certificate for this (ALways remember to update this, I always forget and then spend at least an hour cursing at myself for why it’s not working when I didn’t change anything - and I forgot I changed computers, or reformatted, or something, and now my SHA-1 certificate is different) From the same menu, Create an OAuth client ID but select web application Identity Platform -> Add a Provider -> Select Google Web Client ID (from the above web app) and Web Client Secret (from the above web app) Alright, I can’t tell if you need to include the ClientId or not for this. Sometimes it seems to work without it and sometimes it doesn’t. You may need to try it both ways. Either way, you DO need to have registered the mobile client.

Aidbox Start by going to https://aidbox.app/ Create a new box called whatever you want, select your FHIR Version and Zone Create your client

PUT /Client/shinynewapp?_pretty=true
content-type: text/yaml
accept: text/yaml

secret: verysecret
grant_types:
  - code
auth:
  authorization_code:
    redirect_uri: com.myshiny.newapp://callback
first_party: true

Create User (can be found more detail here)

data:
  name: Grey Faulkenberry
  roles:
    - Administrator
    - Doctor
email: user@mail.com
password: password
id: user1
resourceType: User

Create AccessPolicy for user (for true production apps, you will need to consider how you actually want this to be done, what kind of access you need, etc. For now, we are giving all the permissions for the User)

engine: json-schema
schema:
  required:
    - client
    - user
    - request-method
  properties:
    user:
      required:
        - data
      properties:
        data:
          required:
            - roles
          properties:
            roles:
              not:
                items:
                  not:
                    enum:
                      - Administrator
              type: array
    client:
      required:
        - id
      properties:
        id:
          const: shinynewapp
    request-method:
      enum:
        - get
        - post
        - put
        - delete
        - option
        - patch
        - head
description: Full access for users with role Administrator from client shinynewapp
id: policy-for-shinynewapp-users-role-administrator
resourceType: AccessPolicy

The mobileauthdemo should now be ready to connect to Aidbox.

Interopland and MELD This is a relatively typical HAPI server After you have the server setup, select Apps, then create a new App. App Name and description can be what you’d like, Client Type should generally be Public Client App Launch URI for this is unimportant, because we’re not launching from within their portal App redirect (given above API): com.myshiny.newapp://callback You’ll need to choose your own scopes, I’ve gone with: launch patient/Patient.* openid profile offline_access user/Patient.* You’ll also need to add some users (Settings -> USERS)

Azure API for FHIR (needs to be updated) - ToDo

  static const azureClientId = 'myAzureClientId';
  static const azureTenantId = 'myAzureTenantId';
  static const azureSecret = 'myAzureSecret';
  static const azureUrl = 'https://myfhirserver.azurehealthcareapis.com';
  static const azureAuthUrl =
      'https://login.microsoftonline.com/$azureTenantId/oauth2/authorize?resource=$azureUrl';
  static const azureTokenUrl =
      'https://login.microsoftonline.com/$azureTenantId/oauth2/token';

更多关于Flutter医疗健康认证插件fhir_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter医疗健康认证插件fhir_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,关于Flutter中的fhir_auth插件,这是一个用于医疗健康认证的库,通常与FHIR(Fast Healthcare Interoperability Resources)标准一起使用,以实现医疗数据的互操作性。以下是如何在Flutter项目中集成和使用fhir_auth插件的示例代码。

首先,确保你的Flutter项目已经设置好,并且已经添加了fhir_auth依赖。在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  fhir_auth: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来安装依赖。

接下来,你需要配置fhir_auth插件。这通常涉及到设置认证服务器信息,以及处理认证流程。以下是一个简单的示例,展示了如何使用fhir_auth进行认证:

import 'package:flutter/material.dart';
import 'package:fhir_auth/fhir_auth.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter FHIR Auth Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FhirAuthScreen(),
    );
  }
}

class FhirAuthScreen extends StatefulWidget {
  @override
  _FhirAuthScreenState createState() => _FhirAuthScreenState();
}

class _FhirAuthScreenState extends State<FhirAuthScreen> {
  FhirAuthClient? _fhirAuthClient;
  String? _authToken;

  @override
  void initState() {
    super.initState();
    // 初始化 FhirAuthClient,这里需要你的认证服务器信息
    _fhirAuthClient = FhirAuthClient(
      issuer: 'https://你的认证服务器地址/.well-known/openid-configuration',
      clientId: '你的客户端ID',
      redirectUri: '你的重定向URI',
    );

    // 尝试获取令牌(这里通常会有一个用户交互过程,比如点击登录按钮)
    _attemptAuthentication();
  }

  Future<void> _attemptAuthentication() async {
    try {
      // 这里假设你已经有了一个授权码(code),通常这是通过用户登录流程获得的
      String authorizationCode = '用户登录后获得的授权码';

      // 使用授权码获取访问令牌
      FhirAuthCredentials credentials = await _fhirAuthClient!.exchangeCodeForToken(authorizationCode);
      setState(() {
        _authToken = credentials.accessToken;
      });

      print('成功获取访问令牌: $_authToken');
    } catch (e) {
      print('认证失败: ${e.message}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter FHIR Auth Demo'),
      ),
      body: Center(
        child: Text(
          _authToken ?? '等待认证...',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

注意

  1. 上面的代码是一个简化的示例,用于展示如何初始化fhir_auth客户端并尝试获取访问令牌。在实际应用中,你需要处理用户登录流程,并在用户成功登录后获取授权码。
  2. FhirAuthClient的初始化需要认证服务器的元数据URL(issuer)、客户端ID(clientId)和重定向URI(redirectUri)。这些信息通常由你的认证服务提供商提供。
  3. exchangeCodeForToken方法用于交换授权码以获取访问令牌。在实际应用中,你需要确保在调用此方法之前已经获得了有效的授权码。

由于fhir_auth插件的具体使用可能会根据你的认证服务器和需求有所不同,因此建议查阅该插件的官方文档以获取更详细的信息和最新的使用指南。

回到顶部