auth_oauth2

strategy for OAuth2 login, i.e. Facebook or Github.

Usage

First, create an options object:

  1. typedef FutureOr<User> OAuth2Verifier(oauth2.Client, RequestContext, ResponseContext);
  2.  
  3. /// You might use a pure function to create a verifier that queries a
  4. /// given service.
  5. OAuth2Verifier oauth2verifier(Service<User> userService) {
  6. return (client) async {
  7. var response = await client.get('https://api.github.com/user');
  8. var ghUser = json.decode(response.body);
  9. var id = ghUser['id'] as int;
  10.  
  11. var matchingUsers = await mappedUserService.index({
  12. 'query': {'github_id': id}
  13. });
  14.  
  15. if (matchingUsers.isNotEmpty) {
  16. return matchingUsers.first;
  17. } else {
  18. // Otherwise,create a user
  19. return await mappedUserService.create(User(githubId: id));
  20. }
  21. };
  22. }

Now, initialize an OAuth2Strategy, using the options and verifier.You'll also need to provide a name for this instance of the strategy.Consider using the name of the remote authentication provider (ex. facebook).

Lastly, connect it to an AngelAuth instance, and wire it up to an server.Set up two routes:

  • Redirect users to the external provider
  • Acts as a callback and handles an access codeIn the case of the callback route, you may want to display an HTML page that closesa popup window. In this case, use confirmPopupAuthentication, which is bundled withpackage:angel_auth, as a callback function:
  1. configureServer(Angel app) async {
  2. // ...
  3. var auth = AngelAuth<User>();
  4. auth.strategies['github'] = oauth2Strategy;
  5.  
  6. // Redirect
  7. app.get('/auth/github', auth.authenticate('github'));
  8.  
  9. // Callback
  10. 'github',
  11. AngelAuthOptions(callback: confirmPopupAuthentication())
  12. ));
  13.  
  14. // Connect the plug-in!!!
  15. await app.configure(auth);
  16. }

Handling non-JSON responses

Many OAuth2 providers do not follow the specification, and do not returnapplication/json responses.

You can add a getParameters callback to parse the contents of any arbitraryresponse:

  1. OAuth2Strategy(
  2. // ...
  3. getParameters: (contentType, body) {
  4. if (contentType.type == 'application') {
  5. if (contentType.subtype == 'x-www-form-urlencoded')
  6. return Uri.splitQueryString(body);
  7. else if (contentType.subtype == 'json') return JSON.decode(body);
  8. }
  9.  
  10. throw FormatException('Invalid content-type $contentType; expected application/x-www-form-urlencoded or application/json.');
  11. }