// Access creates a OAuthAccessCall object in preparation for accessing the oauth.access endpoint
338138
func (s *OAuthService) Access(clientID string, clientSecret string, code string) *OAuthAccessCall {
	var call OAuthAccessCall
	call.service = s
	call.clientID = clientID
	call.clientSecret = clientSecret
	call.code = code
	return &call
}
803448
func GetAccessTokenBySHA(sha string) (*AccessToken, error) {
	if sha == "" {
		return nil, ErrAccessTokenEmpty{}
	}
	t := &AccessToken{Sha1: sha}
	has, err := x.Get(t)
	if err != nil {
		return nil, err
	} else if !has {
		return nil, ErrAccessTokenNotExist{sha}
	}
	return t, nil
}
329452
func (a *AuthorizationServer) HandlerAccessToken(request http.Request, response http.Response) (string, error) {
	grantType := request.GetParam(util.OAUTH_GRANT_TYPE)

	if grantType == "" {
		Logger.Debug("GrantType not found %s", grantType)
		return "", util.NewInvalidRequestError(grantType)
	}

	if _, ok := a.grants[grantType]; !ok {
		return "", util.NewUnSupportedGrantTypeError(grantType)
	}

	message, err := a.grants[grantType].HandleResponse(request)
	if err != nil {
		return "", err
	}

	if message == nil {
		return "", util.NewOAuthRuntimeError()
	}

	return message.Encode(), nil
}
867149
func GetOAuthToken(client httpClient, clientID, clientSecret, code, redirectURI string) (accessToken string, scope string, err error) {
	return GetOAuthTokenContext(context.Background(), client, clientID, clientSecret, code, redirectURI)
}
1298741
func (o *OAuthSession) AuthCodeURL(state string, scopes []string) string {
	o.OAuthConfig.Scopes = scopes
	return o.OAuthConfig.AuthCodeURL(state, oauth2.AccessTypeOnline)
}
1087264
func (c *Client) Authorization(authURI string) (Authorization, error) {
	var auth Authorization
	resp, err := c.client.Get(authURI)
	if err != nil {
		return auth, err
	}
	defer resp.Body.Close()
	if err = checkHTTPError(resp, http.StatusOK); err != nil {
		return auth, err
	}

	if err := json.NewDecoder(resp.Body).Decode(&auth); err != nil {
		return auth, fmt.Errorf("decoding response body: %v", err)
	}
	return auth, nil
}
821485
func AuthURL(authURL string) Option {
	return func(c *CredHub) error {
		if authURL != "" {
			var err error
			c.authURL, err = url.Parse(authURL)
			return err
		}
		return nil
	}
}
725700
func (s *Storage) LoadAccess(code string) (*osin.AccessData, error) {
	var extra, cid, prevAccessToken, authorizeCode string
	var result osin.AccessData

	if err := s.db.QueryRow(
		"SELECT client, authorize, previous, access_token, refresh_token, expires_in, scope, redirect_uri, created_at, extra FROM access WHERE access_token=$1 LIMIT 1",
		code,
	).Scan(
		&cid,
		&authorizeCode,
		&prevAccessToken,
		&result.AccessToken,
		&result.RefreshToken,
		&result.ExpiresIn,
		&result.Scope,
		&result.RedirectUri,
		&result.CreatedAt,
		&extra,
	); err == sql.ErrNoRows {
		return nil, pkg.ErrNotFound
	} else if err != nil {
		return nil, errors.New(err)
	}

	result.UserData = extra
	client, err := s.GetClient(cid)
	if err != nil {
		return nil, err
	}

	result.Client = client
	result.AuthorizeData, _ = s.LoadAuthorize(authorizeCode)
	prevAccess, _ := s.LoadAccess(prevAccessToken)
	result.AccessData = prevAccess
	return &result, nil
}
1209127
func (f *Forwarder) authenticate(req *http.Request) (*authContext, error) {
	const accessDeniedMsg = "[00] access denied"

	var isRemoteUser bool
	userTypeI := req.Context().Value(auth.ContextUser)
	switch userTypeI.(type) {
	case auth.LocalUser:

	case auth.RemoteUser:
		isRemoteUser = true
	default:
		f.Warningf("Denying proxy access to unsupported user type: %T.", userTypeI)
		return nil, trace.AccessDenied(accessDeniedMsg)
	}

	userContext, err := f.Auth.Authorize(req.Context())
	if err != nil {
		switch {
		// propagate connection problem error so we can differentiate
		// between connection failed and access denied
		case trace.IsConnectionProblem(err):
			return nil, trace.ConnectionProblem(err, "[07] failed to connect to the database")
		case trace.IsAccessDenied(err):
			// don't print stack trace, just log the warning
			f.Warn(err)
			return nil, trace.AccessDenied(accessDeniedMsg)
		default:
			f.Warn(trace.DebugReport(err))
			return nil, trace.AccessDenied(accessDeniedMsg)
		}
	}
	peers := req.TLS.PeerCertificates
	if len(peers) > 1 {
		// when turning intermediaries on, don't forget to verify
		// https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59
		return nil, trace.AccessDenied("access denied: intermediaries are not supported")
	}
	if len(peers) == 0 {
		return nil, trace.AccessDenied("access denied: only mutual TLS authentication is supported")
	}
	clientCert := peers[0]
	authContext, err := f.setupContext(*userContext, req, isRemoteUser, clientCert.NotAfter)
	if err != nil {
		f.Warn(err.Error())
		return nil, trace.AccessDenied(accessDeniedMsg)
	}
	return authContext, nil
}
637619
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
	p := provider.(*Provider)
	if params.Get("openid.mode") != "id_res" {
		return "", errors.New("Mode must equal to \"id_res\".")
	}

	if params.Get("openid.return_to") != s.CallbackURL {
		return "", errors.New("The \"return_to url\" must match the url of current request.")
	}

	v := make(url.Values)
	v.Set("openid.assoc_handle", params.Get("openid.assoc_handle"))
	v.Set("openid.signed", params.Get("openid.signed"))
	v.Set("openid.sig", params.Get("openid.sig"))
	v.Set("openid.ns", params.Get("openid.ns"))

	split := strings.Split(params.Get("openid.signed"), ",")
	for _, item := range split {
		v.Set("openid."+item, params.Get("openid."+item))
	}
	v.Set("openid.mode", "check_authentication")

	resp, err := p.Client().PostForm(apiLoginEndpoint, v)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	response := strings.Split(string(content), "\n")
	if response[0] != "ns:"+openIDNs {
		return "", errors.New("Wrong ns in the response.")
	}

	if response[1] == "is_valid:false" {
		return "", errors.New("Unable validate openId.")
	}

	openIDURL := params.Get("openid.claimed_id")
	validationRegExp := regexp.MustCompile("^(http|https)://steamcommunity.com/openid/id/[0-9]{15,25}$")
	if !validationRegExp.MatchString(openIDURL) {
		return "", errors.New("Invalid Steam ID pattern.")
	}

	s.SteamID = regexp.MustCompile("\\D+").ReplaceAllString(openIDURL, "")
	s.ResponseNonce = params.Get("openid.response_nonce")

	return s.ResponseNonce, nil
}
293492
func (c *oAuthClients) Get(name string, options v1.GetOptions) (result *oauth.OAuthClient, err error) {
	result = &oauth.OAuthClient{}
	err = c.client.Get().
		Resource("oauthclients").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}
1083176
func (b *basicAuth) requestAuth(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, b.opts.Realm))
	b.opts.UnauthorizedHandler.ServeHTTP(w, r)
}
847020
func (tc *TeleportClient) accessPoint(clt auth.AccessPoint, proxyHostPort string, clusterName string) (auth.AccessPoint, error) {
	// If no caching policy was set or on Windows (where Teleport does not
	// support file locking at the moment), return direct access to the access
	// point.
	if tc.CachePolicy == nil || runtime.GOOS == teleport.WindowsOS {
		log.Debugf("not using caching access point")
		return clt, nil
	}
	return clt, nil
}
1135412
func (a *AccessTokenGenDefault) GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error) {
	token := uuid.NewRandom()
	accesstoken = base64.RawURLEncoding.EncodeToString([]byte(token))

	if generaterefresh {
		rtoken := uuid.NewRandom()
		refreshtoken = base64.RawURLEncoding.EncodeToString([]byte(rtoken))
	}
	return
}
299839
func (s *OauthService) AuthorizeURL(clientID string, options *AuthorizationOptions) string {
	uri, _ := url.Parse(strings.Replace(s.client.BaseURL, "api.", "", 1))
	uri.Path = "/oauth/authorize"
	query := uri.Query()
	query.Add("client_id", clientID)
	query.Add("response_type", "code")
	uri.RawQuery = query.Encode()

	path, _ := addURLQueryOptions(uri.String(), options)
	return path
}
922649
func (h *accessAuthenticator) HandleAccess(ar *osin.AccessRequest, w http.ResponseWriter) error {
	var (
		info *authenticator.Response
		ok   bool
		err  error
	)

	switch ar.Type {
	case osin.AUTHORIZATION_CODE, osin.REFRESH_TOKEN:
		// auth codes and refresh tokens are assumed allowed
		ok = true
	case osin.PASSWORD:
		ctx := context.TODO()
		if ar.HttpRequest != nil {
			ctx = ar.HttpRequest.Context()
		}
		info, ok, err = h.password.AuthenticatePassword(ctx, ar.Username, ar.Password)
	case osin.ASSERTION:
		info, ok, err = h.assertion.AuthenticateAssertion(ar.AssertionType, ar.Assertion)
	case osin.CLIENT_CREDENTIALS:
		info, ok, err = h.client.AuthenticateClient(ar.Client)
	default:
		klog.Warningf("Received unknown access token type: %s", ar.Type)
	}

	if err != nil {
		klog.V(4).Infof("Unable to authenticate %s: %v", ar.Type, err)
		return err
	}

	if ok {
		// Disable refresh_token generation
		ar.GenerateRefresh = false
		ar.Authorized = true
		if info != nil {
			// TODO something with audiences?
			ar.AccessData.UserData = info.User
		}

		if e, ok := ar.Client.(TokenMaxAgeSeconds); ok {
			if maxAge := e.GetTokenMaxAgeSeconds(); maxAge != nil {
				ar.Expiration = *maxAge
			}
		}
	}

	return nil
}
358137
func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error) {
	urlStr := fmt.Sprintf(refreshAccessTokenURL, oauth.AppID, refreshToken)
	var response []byte
	response, err = util.HTTPGet(urlStr)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &result)
	if err != nil {
		return
	}
	if result.ErrCode != 0 {
		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
		return
	}
	return
}