-
Notifications
You must be signed in to change notification settings - Fork 927
/
Copy pathoauth2.js
201 lines (163 loc) · 5.45 KB
/
oauth2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { encodeQuery, parseQuery } from '../utilities'
import nanoid from 'nanoid'
const isHttps = process.server ? require('is-https') : null
const DEFAULTS = {
token_type: 'Bearer',
response_type: 'token',
tokenName: 'Authorization'
}
export default class Oauth2Scheme {
constructor (auth, options) {
this.$auth = auth
this.req = auth.ctx.req
this.name = options._name
this.options = Object.assign({}, DEFAULTS, options)
}
get _scope () {
return Array.isArray(this.options.scope)
? this.options.scope.join(' ')
: this.options.scope
}
get _redirectURI () {
const url = this.options.redirect_uri
if (url) {
return url
}
if (process.server && this.req) {
const protocol = 'http' + (isHttps(this.req) ? 's' : '') + '://'
return protocol + this.req.headers.host + this.$auth.options.redirect.callback
}
if (process.client) {
return window.location.origin + this.$auth.options.redirect.callback
}
}
async mounted () {
// Sync token
const token = this.$auth.syncToken(this.name)
// Set axios token
if (token) {
this._setToken(token)
}
// Handle callbacks on page load
const redirected = await this._handleCallback()
if (!redirected) {
return this.$auth.fetchUserOnce()
}
}
_setToken (token) {
// Set Authorization token for all axios requests
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, token)
}
_clearToken () {
// Clear Authorization token for all axios requests
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, false)
}
async logout () {
this._clearToken()
return this.$auth.reset()
}
login ({ params, state, nonce } = {}) {
const opts = {
protocol: 'oauth2',
response_type: this.options.response_type,
access_type: this.options.access_type,
client_id: this.options.client_id,
redirect_uri: this._redirectURI,
scope: this._scope,
// Note: The primary reason for using the state parameter is to mitigate CSRF attacks.
// https://auth0.com/docs/protocols/oauth2/oauth-state
state: state || nanoid(),
...params
}
if (this.options.audience) {
opts.audience = this.options.audience
}
// Set Nonce Value if response_type contains id_token to mitigate Replay Attacks
// More Info: https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes
// More Info: https://tools.ietf.org/html/draft-ietf-oauth-v2-threatmodel-06#section-4.6.2
if (opts.response_type.includes('id_token')) {
// nanoid auto-generates an URL Friendly, unique Cryptographic string
// Recommended by Auth0 on https://auth0.com/docs/api-auth/tutorials/nonce
opts.nonce = nonce || nanoid()
}
this.$auth.$storage.setUniversal(this.name + '.state', opts.state)
const url = this.options.authorization_endpoint + '?' + encodeQuery(opts)
window.location = url
}
async fetchUser () {
if (!this.$auth.getToken(this.name)) {
return
}
if (!this.options.userinfo_endpoint) {
this.$auth.setUser({})
return
}
const user = await this.$auth.requestWith(this.name, {
url: this.options.userinfo_endpoint
})
this.$auth.setUser(user)
}
async _handleCallback (uri) {
// Handle callback only for specified route
if (this.$auth.options.redirect && this.$auth.ctx.route.path !== this.$auth.options.redirect.callback) {
return
}
// Callback flow is not supported in static generation
if (process.server && process.static) {
return
}
const hash = parseQuery(this.$auth.ctx.route.hash.substr(1))
const parsedQuery = Object.assign({}, this.$auth.ctx.route.query, hash)
// accessToken/idToken
let token = parsedQuery[this.options.token_key || 'access_token']
// refresh token
let refreshToken = parsedQuery[this.options.refresh_token_key || 'refresh_token']
// Validate state
const state = this.$auth.$storage.getUniversal(this.name + '.state')
this.$auth.$storage.setUniversal(this.name + '.state', null)
if (state && parsedQuery.state !== state) {
return
}
// -- Authorization Code Grant --
if (this.options.response_type === 'code' && parsedQuery.code) {
const data = await this.$auth.request({
method: 'post',
url: this.options.access_token_endpoint,
baseURL: process.server ? undefined : false,
data: encodeQuery({
code: parsedQuery.code,
client_id: this.options.client_id,
redirect_uri: this._redirectURI,
response_type: this.options.response_type,
audience: this.options.audience,
grant_type: this.options.grant_type
})
})
if (data.access_token) {
token = data.access_token
}
if (data.refresh_token) {
refreshToken = data.refresh_token
}
}
if (!token || !token.length) {
return
}
// Append token_type
if (this.options.token_type) {
token = this.options.token_type + ' ' + token
}
// Store token
this.$auth.setToken(this.name, token)
// Set axios token
this._setToken(token)
// Store refresh token
if (refreshToken && refreshToken.length) {
refreshToken = this.options.token_type + ' ' + refreshToken
this.$auth.setRefreshToken(this.name, refreshToken)
}
// Redirect to home
this.$auth.redirect('home', true)
return true // True means a redirect happened
}
}