LoginSignup
5
3

More than 3 years have passed since last update.

React NativeのWebViewでBasic認証を突破する方法まとめ

Last updated at Posted at 2019-03-25

問題 Problem

React Nativeで開発していてBASE_URLがBasic認証が必要なページのときに、WebViewで表示させたい!
調べたときにあんまり情報なかったので、めちゃ覚え書き程度にさらっと書きました

解決法 Solution

import React from 'react';
import { WebView } from 'react-native';
import {
  BASE_URL,
  BASIC_AUTH_USER_NAME,
  BASIC_AUTH_PASSWORD,
} from 'react-native-dotenv';

const MyComponent = () => {
  const basicAuthToken = btoa(`${BASIC_AUTH_USER_NAME}:${BASIC_AUTH_PASSWORD}`)

  return (
    <WebView
      source={{
        uri: `${BASE_URL}`,
        headers: {
          Authorization: `Basic ${basicAuthToken}`
        }
      }}
    />
  )
}

ポイントはbtoa()関数で、Basic認証に必要なusername:passwordという文字列をBase64エンコードして、WebViewheaders情報に渡します。

const basicAuthToken = btoa(`${BASIC_AUTH_USER_NAME}:${BASIC_AUTH_PASSWORD}`)

参考

The WebView has no support for Basic Authentication (or custom headers). · Issue #19200 · facebook/react-native

5
3
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
5
3