Authentication¶
A Service accomplishes user authentication via
Authenticator components which are responsible for
associating incoming requests with users.
Every Service can be configured with an
Authenticator. When so configured, the
Service will dispatch each HTTP request to that
Authenticator’s
authenticate method. This method will
use credentials in the request (e.g., HTTP Basic Auth credentials, API-key,
etc…) to authenticate and return the user associated with those credentials,
if one exists. The Service will then store the resolved
user object in the req (e.g., req.user).
Built-in authenticators¶
Carbond comes with several out-of-the-box Authenticators:
HttpBasicAuthenticator`- Base class for implementing HTTP basic authentication.MongoDBHttpBasicAuthenticator- AnHttpBasicAuthenticatorbacked by MongoDB.ApiKeyAuthenticator- Base class for implementing API-key based authentication.MongoDBApiKeyAuthenticator`- AnApiKeyAuthenticatorbacked by MongoDB.OauthAuthenticator(not yet implemented)
Custom Authenticators¶
You can define your own custom Authenticators by
creating an instance of Authenicator (or a
subclass) with a custom authenticate
method.
1 2 3 4 5 6 7 | authenticator: o({
_type: carbon.carbond.security.Authenticator,
authenticate: function(req) {
var user = figureOutWhoUserIs(req)
return user
}
}),
|
Examples¶
HTTP Basic authentication
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | __(function() {
module.exports = o.main({
_type: carbon.carbond.Service,
port: 8888,
dbUri: 'mongodb://localhost:27017/mydb',
authenticator: o({
_type: carbon.carbond.security.MongoDBHttpBasicAuthenticator,
userCollection: "users",
usernameField: "username",
passwordField: "password"
}),
endpoints: {
hello: o({
_type: carbon.carbond.Endpoint,
get: function(req) {
return {msg: 'Hello ' + req.user.email + '!'}
}
})
}
})
})
|
API Key authentication
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | __(function() {
module.exports = o.main({
_type: carbon.carbond.Service,
port: 8888,
dbUri: 'mongodb://localhost:27017/mydb',
authenticator: o({
_type: carbon.carbond.security.MongoDBApiKeyAuthenticator,
apiKeyParameterName: "API_KEY",
apiKeyLocation: "header", // can be "header" or "query"
userCollection: "users",
apiKeyField: "apiKey"
}),
endpoints: {
hello: o({
_type: carbon.carbond.Endpoint,
get: function(req) {
return {msg: 'Hello ' + req.user.email + '!'}
}
})
}
})
})
|
Custom authentication
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | __(function() {
module.exports = o.main({
_type: carbon.carbond.Service,
port: 8888,
authenticator: o({
_type: carbon.carbond.security.Authenticator,
authenticate: function(req) {
var user = figureOutWhoUserIs(req)
return user
}
}),
endpoints: {
hello: o({
_type: carbon.carbond.Endpoint,
get: function(req) {
return {msg: 'Hello ' + req.user.email + '!'}
}
})
}
})
})
|