2015-06-24 4 views
0

При использовании oauth2 библиотеки Golang в:Golang oauth2 Получить токен Scope

https://godoc.org/golang.org/x/oauth2#Token

Я обменивать код авторизации для доступа токен и я получаю обратно эту структуру:

type Token struct { 
    // AccessToken is the token that authorizes and authenticates 
    // the requests. 
    AccessToken string `json:"access_token"` 

    // TokenType is the type of token. 
    // The Type method returns either this or "Bearer", the default. 
    TokenType string `json:"token_type,omitempty"` 

    // RefreshToken is a token that's used by the application 
    // (as opposed to the user) to refresh the access token 
    // if it expires. 
    RefreshToken string `json:"refresh_token,omitempty"` 

    // Expiry is the optional expiration time of the access token. 
    // 
    // If zero, TokenSource implementations will reuse the same 
    // token forever and RefreshToken or equivalent 
    // mechanisms for that TokenSource will not be used. 
    Expiry time.Time `json:"expiry,omitempty"` 
    // contains filtered or unexported fields 
} 

Теперь, когда я использую этот токен доступа в моем приложении, мне нужно знать область, для которой был предоставлен токен.

Но я не вижу никаких свойств или методов для получения области?

Как получить область токена, чтобы я мог ограничить права пользователя на основе этого?

Я могу видеть, что структура Config имеет Scopes срез:

type Config struct { 
    // ClientID is the application's ID. 
    ClientID string 

    // ClientSecret is the application's secret. 
    ClientSecret string 

    // Endpoint contains the resource server's token endpoint 
    // URLs. These are constants specific to each server and are 
    // often available via site-specific packages, such as 
    // google.Endpoint or github.Endpoint. 
    Endpoint Endpoint 

    // RedirectURL is the URL to redirect users going through 
    // the OAuth flow, after the resource owner's URLs. 
    RedirectURL string 

    // Scope specifies optional requested permissions. 
    Scopes []string 
} 

мне кажется, нет никакого способа, чтобы получить объем из маркеров, хотя?

Несомненно, точка видимости заключается в том, что она должна быть частью токена доступа для проверки разрешений?

Смотрите спецификации: https://tools.ietf.org/html/rfc6749#page-23

+0

ли 'token.Extra ("Сфера")' предоставить вам что-нибудь полезное? –

+0

@TimCooper No. Даже если моя конфигурация имеет разрез Scopes, указанный токен.Extra («scope») возвращает nil. Я не думаю, что область может быть выполнена неправильно. –

ответ

0

это должно сделать трюк

func GetTokensScope(tokUrl string, clientId string, secret string) (string,error){ 
     body := bytes.NewBuffer([]byte("grant_type=client_credentials&client_id="+clientId+"&client_secret="+secret+"&response_type=token")) 
     req, err := http.NewRequest("POST",tokUrl,body) 
     req.Header.Set("Content-Type","application/x-www-form-urlencoded") 
     client := &http.Client{} 
     resp, err := client.Do(req) 
     if err != nil { 
      return "",err 
     } 

     defer resp.Body.Close() 
     rsBody, err := ioutil.ReadAll(resp.Body) 
     type WithScope struct { 
      Scope string `json:"scope"` 
     } 
     var dat WithScope 
     err = json.Unmarshal(rsBody,&dat) 
     if err != nil { 
      return "",err 
     } 

     return dat.Scope,err 
    }