How do I implement secure OAuth2 consumption in Javascript?

前端 未结 2 1592
南方客
南方客 2020-12-07 08:37

I\'m in the process of designing an API in PHP that will use OAuth2.0. My end goal is to build a front-end application in javascript (using AngularJS) that accesses this API

2条回答
  •  有刺的猬
    2020-12-07 08:56

    There's an example of Authorization Code Grant approach to get a token from OAuth server. I used jQuery ($) to make some operations.

    First, redirect user to authorization page.

    var authServerUri = "http://your-aouth2-server.com/authorize",
    authParams = {
      response_type: "code",
      client_id: this.model.get("clientId"),
      redirect_uri: this.model.get("redirectUri"),
      scope: this.model.get("scope"),
      state: this.model.get("state")
    };
    
    // Redirect to Authorization page.
    var replacementUri = authServerUri + "?" + $.param(authParams);
    window.location.replace(replacementUri);
    

    When one gave authorization pass to get token:

    var searchQueryString = window.location.search;
    if ( searchQueryString.charAt(0) === "?") {
      searchQueryString = searchQueryString.substring(1);
    }
    var searchParameters = $.deparam.fragment(searchQueryString);
    
    if ( "code" in searchParameters) {
      // TODO: construct a call like in previous step using $.ajax() to get token.
    }
    

    You could implement the Resource Owner Password Credentials Grant in the same manner using jQuery or pure XMLHttpRequest and don't make any redirects - because on each redirect you'll loose state of your application.

    For me, I used HTML5 local storage to persist state of my application for data which were not likely to pose a security threat.

提交回复
热议问题