Пример #1
0
func encodeToken(referal *url.URL, outhToken *oauth2.Token) error {
	str := outhToken.Extra("expires_in")
	expiresIn, err := strconv.Atoi(fmt.Sprintf("%v", str))
	if err != nil {
		return errs.WithStack(errors.New("cant convert expires_in to integer " + err.Error()))
	}
	str = outhToken.Extra("refresh_expires_in")
	refreshExpiresIn, err := strconv.Atoi(fmt.Sprintf("%v", str))
	if err != nil {
		return errs.WithStack(errors.New("cant convert refresh_expires_in to integer " + err.Error()))
	}
	tokenData := &app.TokenData{
		AccessToken:      &outhToken.AccessToken,
		RefreshToken:     &outhToken.RefreshToken,
		TokenType:        &outhToken.TokenType,
		ExpiresIn:        &expiresIn,
		RefreshExpiresIn: &refreshExpiresIn,
	}
	b, err := json.Marshal(tokenData)
	if err != nil {
		return errs.WithStack(errors.New("cant marshal token data struct " + err.Error()))
	}

	parameters := url.Values{}
	parameters.Add("token", outhToken.AccessToken) // Temporary keep the old "token" param. We will drop this param as soon as UI adopt the new json param.
	parameters.Add("token_json", string(b))
	referal.RawQuery = parameters.Encode()

	return nil
}
Пример #2
0
func (c *Client) DelegationToken(token *oauth2.Token, apiType string) (string, error) {
	body, err := json.Marshal(map[string]interface{}{
		"client_id":  c.ClientID,
		"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
		"id_token":   token.Extra("id_token"),
		"target":     c.ClientID,
		"scope":      "openid name email",
		"api_type":   apiType,
	})
	if err != nil {
		return "", err
	}
	url := fmt.Sprintf(delegationEndpoint, c.Domain)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
	if err != nil {
		return "", err
	}
	req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token))
	req.Header.Set("Content-Type", "application/json")
	resp, err := new(http.Client).Do(req)
	if err != nil {
		return "", err
	}
	raw, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		return "", err
	}
	var obj map[string]interface{}
	if err := json.Unmarshal(raw, &obj); err != nil {
		return "", err
	}
	return obj["id_token"].(string), nil
}
Пример #3
0
func (a *app) handleCallback(w http.ResponseWriter, r *http.Request) {
	if errMsg := r.FormValue("error"); errMsg != "" {
		http.Error(w, errMsg+": "+r.FormValue("error_description"), http.StatusBadRequest)
		return
	}

	if state := r.FormValue("state"); state != exampleAppState {
		http.Error(w, fmt.Sprintf("expected state %q got %q", exampleAppState, state), http.StatusBadRequest)
		return
	}

	code := r.FormValue("code")
	refresh := r.FormValue("refresh_token")
	var (
		err   error
		token *oauth2.Token
	)
	oauth2Config := a.oauth2Config(nil)
	switch {
	case code != "":
		token, err = oauth2Config.Exchange(a.ctx, code)
	case refresh != "":
		t := &oauth2.Token{
			RefreshToken: refresh,
			Expiry:       time.Now().Add(-time.Hour),
		}
		token, err = oauth2Config.TokenSource(r.Context(), t).Token()
	default:
		http.Error(w, fmt.Sprintf("no code in request: %q", r.Form), http.StatusBadRequest)
		return
	}

	if err != nil {
		http.Error(w, fmt.Sprintf("failed to get token: %v", err), http.StatusInternalServerError)
		return
	}

	rawIDToken, ok := token.Extra("id_token").(string)
	if !ok {
		http.Error(w, "no id_token in token response", http.StatusInternalServerError)
		return
	}

	idToken, err := a.verifier.Verify(r.Context(), rawIDToken)
	if err != nil {
		http.Error(w, fmt.Sprintf("Failed to verify ID token: %v", err), http.StatusInternalServerError)
		return
	}
	var claims json.RawMessage
	idToken.Claims(&claims)

	buff := new(bytes.Buffer)
	json.Indent(buff, []byte(claims), "", "  ")

	renderToken(w, a.redirectURI, rawIDToken, token.RefreshToken, buff.Bytes())
}
Пример #4
0
// Utility method which gets the AWS credentials for the given OAuth token
func FetchCredentialsForToken(w http.ResponseWriter, r *http.Request,
	token *oauth2.Token, rawQuery string) {

	user, err := GetUserFromGoogleOauthToken(token.Extra("id_token").(string))
	if err != nil {
		log.Printf("failed to parse google id_token: %s", err)
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	groups, err := GetUserGroups(user)
	if err != nil {
		log.Printf("failed to fetch google group membership for %s: %s", user, err)
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	policy, err := MapUserAndGroupsToPolicy(user, groups)
	if err != nil {
		log.Printf("failed to determine policy for %s: %s", user, err)
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	if policy == nil {
		log.Printf("no matching policy for %s", user)
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	credentials, err := GetCredentials(user, policy.Policy, time.Second*43200)
	if err != nil {
		log.Printf("failed to get credentials for %s: %s", user, err)
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	query, err := url.ParseQuery(rawQuery)
	if err != nil {
		log.Printf("ERROR: parse query: %s", err)
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	fmt.Printf("login %s from %s with policy %s key %s\n", user, getRemoteAddress(r),
		policy.Name, credentials.AccessKeyId)

	RespondWithCredentials(w, r, credentials, query, token)
}
Пример #5
0
func (s *sinaAuthSupply) GetProfileInfoURL(token *oauth2.Token) string {
	return "https://api.weibo.com/2/users/show.json" + "?" + "access_token=" + token.AccessToken + "&" + "uid=" + token.Extra("uid").(string)
}