Skip to content

Instantly share code, notes, and snippets.

@ryu22e
Last active December 16, 2018 07:13
Show Gist options
  • Save ryu22e/d150229344fb38dd44c956a8382b7b04 to your computer and use it in GitHub Desktop.
Save ryu22e/d150229344fb38dd44c956a8382b7b04 to your computer and use it in GitHub Desktop.
WebAuthnサインイン(クライアントサイド)
{% load static %}
{# users/signin.html #}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>サインイン- django_webauthn_example</title>
</head>
<body>
<h2>サインイン</h2>
<div id="signin">
<form v-on:submit.prevent="onSubmit" :disabled="!isSupported" method="post">
<div v-if="!isSupported">このブラウザはWeb Authentication APIをサポートしていないため、サインインできません。</div>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" :disabled="!isSupported">サインイン</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
{# これを使っている→ https://github.com/paroga/cbor-js #}
<script src="{% static 'js/libs/cbor.min.js' %}"></script>
<script src="{% static 'js/users/signin.js' %}"></script>
</body>
</html>
'use strict';
// static/js/users/signin.js
var isSupported = navigator !== undefined && ('credentials' in navigator);
var csrftoken = Cookies.get('csrftoken');
new Vue({
el: '#signin',
delimiters: ['[[', ']]'],
data: {
username: '',
isSupported: isSupported
},
methods: {
onSubmit: function () {
if (!this.isSupported) {
return;
}
fetch('/users/apis/authenticate-begin/', {
method: 'POST',
body: JSON.stringify({
username: this.username
}),
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken
}
}).then(function(response) {
if(response.ok) return response.arrayBuffer();
throw new Error('No credential available to authenticate!');
}).then(CBOR.decode).then(function(options) {
return navigator.credentials.get(options);
}).then(function(assertion) {
return fetch('/users/apis/authenticate-complete/', {
method: 'POST',
headers: {
'Content-Type': 'application/cbor',
'X-CSRFToken': csrftoken
},
body: CBOR.encode({
"credentialId": new Uint8Array(assertion.rawId),
"authenticatorData": new Uint8Array(assertion.response.authenticatorData),
"clientDataJSON": new Uint8Array(assertion.response.clientDataJSON),
"signature": new Uint8Array(assertion.response.signature)
})
})
}).then(function(response) {
if (response.ok) {
response.json().then(function(data) {
window.location = data.redirect_to;
});
}
}, function(reason) {
alert(reason);
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment