예제 #1
0
파일: auth_test.go 프로젝트: thanzen/hydra
func TestGetters(t *testing.T) {
	assert.False(t, IsAuthenticatedFromContext(context.Background()))
	_, err := PoliciesFromContext(context.Background())
	assert.NotNil(t, err)
	_, err = SubjectFromContext(context.Background())
	assert.NotNil(t, err)
	_, err = TokenFromContext(context.Background())
	assert.NotNil(t, err)

	ctx := context.Background()
	claims := hjwt.ClaimsCarrier{"sub": "peter"}
	token := &jwt.Token{Valid: true}
	policies := []policy.Policy{}
	ctx = NewContextFromAuthValues(ctx, claims, token, policies)

	assert.True(t, IsAuthenticatedFromContext(ctx))
	policiesContext, err := PoliciesFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, policies, policiesContext)

	subjectContext, err := SubjectFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, claims.GetSubject(), subjectContext)

	tokenContext, err := TokenFromContext(ctx)
	assert.Nil(t, err)
	assert.Equal(t, token, tokenContext)
}
예제 #2
0
func TestDefaultSession(t *testing.T) {
	token := &oauth2.Token{}
	s := DefaultSession{RemoteSubject: "subject", Extra: "extra", Token: token}
	assert.Equal(t, "subject", s.GetRemoteSubject())
	assert.Equal(t, "extra", s.GetExtra().(string))
	assert.Equal(t, token, s.GetToken())
}
예제 #3
0
func TestMiddleware(t *testing.T) {
	m := &Middleware{}

	for k, c := range cases {
		h := hcon.NewContextAdapter(
			context.Background(),
			mockContext(c),
			m.IsAuthenticated,
		).ThenFunc(hcon.ContextHandlerFunc(handler(m, c)))

		ts := httptest.NewServer(h)
		defer ts.Close()

		res, err := http.Get(ts.URL)
		require.Nil(t, err)
		res.Body.Close()

		if !c.expectAuthN {
			assert.Equal(t, http.StatusUnauthorized, res.StatusCode, "Authentication failed case %d", k)
		} else if !c.expectAuthZ {
			assert.Equal(t, http.StatusForbidden, res.StatusCode, "Authorization failed case %d", k)
		} else {
			assert.Equal(t, http.StatusOK, res.StatusCode, "Case %d should be authorized but wasn't.", k)
		}
	}
}
예제 #4
0
func TestNew(t *testing.T) {
	m := New("321", "client", "secret", "/callback")
	assert.Equal(t, "321", m.id)
	assert.Equal(t, "client", m.conf.ClientID)
	assert.Equal(t, "secret", m.conf.ClientSecret)
	assert.Equal(t, "/callback", m.conf.RedirectURL)
}
예제 #5
0
func TestGetAuthCodeURL(t *testing.T) {
	ar := &osin.AuthorizeRequest{
		RedirectUri: mock.conf.RedirectURL,
		Client:      &osin.DefaultClient{Id: mock.conf.ClientID},
		Scope:       "scope",
		Type:        osin.CODE,
		State:       "state",
	}

	path := mock.GetAuthCodeURL(ar)
	t.Logf("Got auth code url: %s", path)
	parsed, err := url.Parse(path)
	require.Nil(t, err)

	redirect, err := url.QueryUnescape(parsed.Query().Get("redirect_uri"))
	require.Nil(t, err)

	parsed, err = url.Parse(redirect)
	t.Logf("Got redirect url: %s", redirect)
	require.Nil(t, err)
	q := parsed.Query()

	assert.Equal(t, ar.RedirectUri, q.Get(RedirectQueryParam))
	assert.Equal(t, ar.Client.GetId(), q.Get(ClientQueryParam))
	assert.Equal(t, ar.Scope, q.Get(ScopeQueryParam))
	assert.Equal(t, ar.State, q.Get(StateQueryParam))
	assert.Equal(t, string(ar.Type), q.Get(TypeQueryParam))
}
예제 #6
0
func assertAccount(t *testing.T, c test, data string) account.Account {
	var acc account.DefaultAccount
	require.Nil(t, json.Unmarshal([]byte(data), &acc))
	assert.Equal(t, c.payload.Email, acc.Email)
	assert.Equal(t, c.payload.Data, acc.Data)
	assert.Empty(t, acc.Password)
	return &acc
}
예제 #7
0
파일: map_test.go 프로젝트: thanzen/hydra
func TestMap(t *testing.T) {
	m := Map{"foo": "bar", "1": float64(2)}
	enc, err := m.Marshall()
	require.Nil(t, err)
	dec, err := Unmarshal(enc)
	require.Nil(t, err)
	assert.Equal(t, m, dec, "%v does not equal %v", m, dec)
	assert.Equal(t, m["foo"], dec["foo"])
}
예제 #8
0
func TestAccountCases(t *testing.T) {
	for _, c := range [][]string{
		[]string{"1", "foo@bar", "secret"},
		[]string{"2", "baz@foo", "top secret"},
	} {
		a := &DefaultAccount{c[0], c[1], c[2], `{"foo": "bar"}`}
		assert.Equal(t, c[0], a.GetID())
		assert.Equal(t, c[1], a.GetEmail())
		assert.Equal(t, c[2], a.GetPassword())
		assert.Equal(t, `{"foo": "bar"}`, a.GetData())
	}
}
예제 #9
0
func TestWriteJSON(t *testing.T) {
	r := &rw{header: http.Header{}}
	js := struct {
		Foo string `json:"foo"`
	}{"bar"}
	WriteJSON(r, js)
	assert.Equal(t, http.StatusOK, r.code)
	assert.Equal(t, `{"foo":"bar"}`, string(r.written))
	assert.Equal(t, r.Header().Get("Content-Type"), "application/json")

	WriteJSON(r, func() {})
	assert.Equal(t, http.StatusInternalServerError, r.code)
}
예제 #10
0
func TestConnection(t *testing.T) {
	c := &DefaultConnection{
		ID:            uuid.New(),
		LocalSubject:  "peter",
		RemoteSubject: "*****@*****.**",
		Provider:      "google",
	}

	assert.Equal(t, c.ID, c.GetID())
	assert.Equal(t, c.Provider, c.GetProvider())
	assert.Equal(t, c.LocalSubject, c.GetLocalSubject())
	assert.Equal(t, c.RemoteSubject, c.GetRemoteSubject())
}
예제 #11
0
func TestRegistry(t *testing.T) {
	m := &provider{}
	r := NewRegistry([]Provider{m})

	p, err := r.Find("fooBar")
	assert.Nil(t, err)
	assert.Equal(t, m, p)

	p, err = r.Find("foobar")
	assert.Nil(t, err)
	assert.Equal(t, m, p)

	_, err = r.Find("bar")
	assert.NotNil(t, err)
}
예제 #12
0
파일: store_test.go 프로젝트: thanzen/hydra
func TestUpdateEmail(t *testing.T) {
	_, err := store.Create("3", "3@bar", "secret", `{"foo": "bar"}`)
	assert.Nil(t, err)

	_, err = store.UpdateEmail("3", "3@foo", "wrong secret")
	assert.NotNil(t, err)

	_, err = store.UpdateEmail("3", "3@foo", "secret")
	assert.Nil(t, err)

	r, err := store.Get("3")
	assert.Nil(t, err)

	assert.Equal(t, "3", r.GetID())
	assert.Equal(t, "3@foo", r.GetEmail())
	assert.NotEqual(t, "secret", r.GetPassword())
}
예제 #13
0
파일: jwt_test.go 프로젝트: thanzen/hydra
func TestLoadCertificate(t *testing.T) {
	for _, c := range TestCertificates {
		out, err := LoadCertificate(c[0])
		assert.Nil(t, err)
		assert.Equal(t, c[1], string(out))
	}
	_, err := LoadCertificate("")
	assert.NotNil(t, err)
	_, err = LoadCertificate("foobar")
	assert.NotNil(t, err)
}
예제 #14
0
func TestContextAdapterThenFuncExports(t *testing.T) {
	h := NewContextAdapter(context.Background(), middleware).ThenFunc(handler)

	recorder := httptest.NewRecorder()
	req, err := http.NewRequest("GET", "http://example.com/handler", nil)
	require.Nil(t, err)

	m := mux.NewRouter()
	m.Handle("/handler", h).Methods("GET")
	m.ServeHTTP(recorder, req)

	assert.Equal(t, 2, called)
	called = 0
}
예제 #15
0
파일: store_test.go 프로젝트: thanzen/hydra
func TestUpdatePassword(t *testing.T) {
	account, err := store.Create("4", "4@bar", "old secret", `{"foo": "bar"}`)
	assert.Nil(t, err)

	_, err = store.UpdatePassword("4", "wrong old secret", "new secret")
	assert.NotNil(t, err)

	updatedAccount, err := store.UpdatePassword("4", "old secret", "new secret")
	assert.Nil(t, err)

	resultAccount, err := store.Get("4")
	assert.Nil(t, err)

	assert.Equal(t, updatedAccount.GetPassword(), resultAccount.GetPassword())
	assert.NotEqual(t, account.GetPassword(), resultAccount.GetPassword())
}
예제 #16
0
func TestContextAdapter(t *testing.T) {
	h := &contextAdapter{
		ctx:   context.Background(),
		final: middleware(ContextHandlerFunc(handler)),
	}

	recorder := httptest.NewRecorder()
	req, err := http.NewRequest("GET", "http://example.com/handler", nil)
	require.Nil(t, err)

	m := mux.NewRouter()
	m.Handle("/handler", h).Methods("GET")
	m.ServeHTTP(recorder, req)

	assert.Equal(t, 2, called)
	called = 0
}
예제 #17
0
func TestGetAuthCodeURL(t *testing.T) {
	conf := oauth2.Config{
		ClientID:     "remote-client",
		ClientSecret: "secret",
		Endpoint: oauth2.Endpoint{
			AuthURL:  "http://third-party/oauth2/auth",
			TokenURL: "http://third-party/oauth2/token",
		},
		RedirectURL: "http://hydra/oauth2/auth",
		Scopes:      []string{"scope"},
	}
	ar := &osin.AuthorizeRequest{
		Type:        osin.CODE,
		Client:      &osin.DefaultClient{Id: "client", Secret: "secret"},
		Scope:       "scope",
		RedirectUri: "http://remote/callback",
		State:       "state",
	}
	url := GetAuthCodeURL(conf, ar, "foo")
	assert.Equal(t, "http://third-party/oauth2/auth?client_id=remote-client&redirect_uri=http%3A%2F%2Fhydra%2Foauth2%2Fauth%3Focl%3Dclient%26opr%3Dfoo%26ord%3Dhttp%253A%252F%252Fremote%252Fcallback%26osc%3Dscope%26ost%3Dstate%26otp%3Dcode&response_type=code&scope=scope&state=state", url)
}
예제 #18
0
func TestExchangeCode(t *testing.T) {

	router := mux.NewRouter()
	router.HandleFunc("/oauth2/token", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintln(w, `{"access_token": "ABCDEFG", "token_type": "bearer", "uid": "12345"}`)
	})
	router.HandleFunc("/users/get_current_account", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintln(w, `{"account_id": "dbid:2qrw3etsdtr","name": {"given_name": "Peter","surname": "Peter","familiar_name": "Peter","display_name": "Peter"},"email": "*****@*****.**","country": "DE","locale": "de","referral_link": "https://db.tt/w34setrdgxf","is_paired": false,"account_type": {".tag": "pro"}}`)
	})
	ts := httptest.NewServer(router)

	mock.api = ts.URL
	mock.conf.Endpoint.TokenURL = ts.URL + mock.conf.Endpoint.TokenURL

	t.Logf("Token URL: %s", mock.conf.Endpoint.TokenURL)
	t.Logf("API URL: %s", mock.api)
	code := "testcode"
	ses, err := mock.Exchange(code)
	require.Nil(t, err)
	assert.Equal(t, "dbid:2qrw3etsdtr", ses.GetRemoteSubject())
}
예제 #19
0
func TestClaimsCarrier(t *testing.T) {
	for k, c := range []struct {
		id        string
		issuer    string
		subject   string
		audience  string
		notBefore time.Time
		issuedAt  time.Time
	}{
		{uuid.New(), "hydra", "peter", "app", time.Now(), time.Now()},
	} {
		carrier := NewClaimsCarrier(c.id, c.issuer, c.subject, c.audience, c.notBefore, c.issuedAt)
		assert.Equal(t, c.id, carrier.GetID(), "Case %d", k)
		assert.Equal(t, c.issuer, carrier.GetIssuer(), "Case %d", k)
		assert.Equal(t, c.subject, carrier.GetSubject(), "Case %d", k)
		assert.Equal(t, c.audience, carrier.GetAudience(), "Case %d", k)
		assert.Equal(t, c.notBefore, carrier.GetNotBefore(), "Case %d", k)
		assert.Equal(t, c.issuedAt, carrier.GetIssuedAt(), "Case %d", k)
		assert.Empty(t, carrier.getAsString("doesnotexist"), "Case %d", k)
		assert.Equal(t, time.Time{}, carrier.getAsTime("doesnotexist"), "Case %d", k)
		assert.NotEmpty(t, carrier.String(), "Case %d", k)
	}
}
예제 #20
0
파일: store_test.go 프로젝트: thanzen/hydra
func TestCreateAndGetCases(t *testing.T) {
	for _, c := range []struct {
		data  []string
		extra string
		pass  bool
		find  bool
	}{
		{[]string{"1", "1@bar", "secret"}, `{"foo": "bar"}`, true, true},
		{[]string{"1", "1@foo", "secret"}, `{"foo": "bar"}`, false, true},
		{[]string{"2", "1@bar", "secret"}, `{"foo": "bar"}`, false, false},
	} {
		result, err := store.Create(c.data[0], c.data[1], c.data[2], c.extra)
		if c.pass {
			assert.Nil(t, err)
			assert.Equal(t, c.data[0], result.GetID())
			assert.Equal(t, c.data[1], result.GetEmail())
			assert.NotEqual(t, c.data[2], result.GetPassword())
			assert.Equal(t, c.extra, result.GetData())

			result, err = store.Get(c.data[0])
			if c.find {
				assert.Nil(t, err)
				assert.Equal(t, c.data[0], result.GetID())
				assert.Equal(t, c.data[1], result.GetEmail())
				assert.NotEqual(t, c.data[2], result.GetPassword())
				assert.Equal(t, c.extra, result.GetData())
			} else {
				assert.NotNil(t, err)
			}
		} else {
			assert.NotNil(t, err)
			_, err = store.Get(c.data[0])
			if c.find {
				assert.Nil(t, err)
			} else {
				assert.NotNil(t, err)
			}
		}
	}
}
예제 #21
0
func TestIntrospect(t *testing.T) {
	router := mux.NewRouter()
	handler.SetRoutes(router)
	ts := httptest.NewServer(router)
	defer ts.Close()

	config := configs["working"]
	user := logins["working"]
	clientConfig := clientcredentials.Config{
		ClientID:     config.ClientID,
		ClientSecret: config.ClientSecret,
		TokenURL:     ts.URL + config.Endpoint.TokenURL,
		Scopes:       config.Scopes,
	}
	config.Endpoint = oauth2.Endpoint{AuthURL: ts.URL + "/oauth2/auth", TokenURL: ts.URL + "/oauth2/token"}

	access, _ := clientConfig.Token(oauth2.NoContext)
	verify, _ := config.PasswordCredentialsToken(oauth2.NoContext, user.Username, user.Password)

	for k, c := range []*struct {
		accessToken string
		code        int
		pass        bool
	}{
		{"Bearer " + verify.AccessToken, http.StatusOK, true},
		{"", http.StatusUnauthorized, false},
		{"Bearer ", http.StatusUnauthorized, false},
		{"Bearer invalid", http.StatusForbidden, false},
		{"Bearer invalid", http.StatusForbidden, false},
		{"Bearer invalid", http.StatusForbidden, false},

		//
		{"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.e30.FvuwHdEjgGxPAyVUb-eqtiPl2gycU9WOHNzwpFKcpdN_QkXkBUxU3qFl3lLBaMzIuP_GjXLXcJZFhyQ2Ne3kfWuZSGLmob0Og8B4lAy7CA7iwpji2R3aUcwBwbJ41IJa__F8fMRz0dRDwhyrBKD-9y4TfV_-yZuzBZxq0UdjX6IdpzsdetphBSIZkPij5MY3thRwC-X_gXyIXi4-G2_CjRrV5lCGnPJrDbLqPCYqS71wK9NEsz_B8p5ENmwad8vZe4fEFR7XsqJrhPjbEVGeLpzSz0AOGp4G1iyvv1sdu4M3Y8KSSGYnZ8lXNGyi8QeUr374Y6XgJ5N5TVLWI2cMxg", http.StatusForbidden, false},

		//		 "exp": "2012-04-23T18:25:43.511Z"
		{"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDEyLTA0LTIzVDE4OjI1OjQzLjUxMVoifQ.YPCfgNDs-UT6vNqh6095cXiMe0jcA9HjHuLi6hK6YBPsEHwHFniFGXAYt1PpPabBHAz7lQQ8zZao6LrVXkfz7PLbeQZl3KY0SUb-Wb0eEDjX4naEdm20whrYMZQ36VcTMT-FsGk5MB-nIYKq3iX6FMhumV8StjpC0jrM14488lPwLXihC1uITQBNVFEyXV_emhfuyojWEcEq899oE_vVRd7pTOmIhU8dFEAonoLZyPTKzSfvqaurPeySA5ttA-TTMTxZNzGVxWV4cwYHlhTXfS57zoSF_EN_PULTqMepUe8RC9AFnwyvNAa5e4nxQG5yO6b7cUGa0vSCD5FPbNBh-w", http.StatusForbidden, false},

		//		{
		//			"exp": "2099-04-23T18:25:43.511Z",
		//			"nbf": "2099-04-23T18:25:43.511Z"
		//		}
		{"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDk5LTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJuYmYiOiIyMDk5LTA0LTIzVDE4OjI1OjQzLjUxMVoifQ.hCuvBuiwEjjTbL8NMfEe6exDaRUeQIHodTNc5uBdY1lxmJWfFPh2zykuEvinqTprQe2CPRmL3Dk6jX3pcnigg7IjMX-EZueOnJc229gwjmJJiIGuUJOV3bLc-0xQ3cu6FCRc2NgOEh6Nq6Jh8G7ko4Du4gGrFsn97kbzAUYyns98T8442p0YXdQF-KVCc87fCkdr6OTsbfomy7jUDLCWptyJqREOoBll-nzyFWTxGHgoH_DmHft64SwvsvRafqZv9Q48bRzr857ps6OjEPncjRTriAsJa-p7aPKO2e7LXLKpopcaNwC09RNteAO4XPc2_M-IrYf6a02UzgSmOkIZUg", http.StatusForbidden, false},

		//		{
		//			"exp": "2099-04-23T18:25:43.511Z",
		//			"iat": "2000-04-23T18:25:43.511Z",
		//			"nbf": "2099-04-23T18:25:43.511Z"
		//		}
		{"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDk5LTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJpYXQiOiIyMDAwLTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJuYmYiOiIyMDk5LTA0LTIzVDE4OjI1OjQzLjUxMVoifQ.WtRurXoCy4kHPxnaL5ccPaeHIaDogXRFE6mqyF8nVTSsv6E7FaJg4IiYylxa44ty8GRMYn7c2CSyQefTVauqjJm8b0Rpu4biIeyCQRzwTZZzqZbc6irdWYsJu4DkwfAU0yP2EaLEtQOG3scnDpmtyCp7NvDAi8XlVeytOSHjqyJMWzqO_z5eU4e2Ap-3wkLo4P9_W1W3Tx_V0xQR2VaOXtVjEa_VS36rAMBy6WAvYQrYNlvBAA6OBfqg2uvKUfmEoE6MchkFxHFTSGBmI2boDfF2XGlyLn0di7gIBG-udXDv_zaVp4BtuswygTskV5d2i3pvLGP6UuJJhc7VVOAoPw", http.StatusForbidden, false},

		//		{
		//			"exp": "2099-04-23T18:25:43.511Z",
		//			"iat": "2000-04-23T18:25:43.511Z",
		//			"nbf": "2000-04-23T18:25:43.511Z",
		//			"aud": "wrong-audience"
		//		}
		{"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDk5LTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJpYXQiOiIyMDAwLTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJuYmYiOiIyMDAwLTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJhdWQiOiJ3cm9uZy1hdWRpZW5jZSJ9.rF4JqVpawgHcg_H2hAAsEI2GUxzxCote4pUlruK9hLF-Dv-YSeEmMcFBhfxgsFuDCJotUCG6v8EhwI4u2wxGQHzLz70a-0AEZLQBccCfF_V4qAk8B7M5z2fO7xtEy8RkB2pZKCHbJ1f_6MSM_EyV6r4oiwedveBSsLKcjDhWE3_wExmtmtZaujJy53gR8Wh7BnUt6pl95_d7OMFjGEp1C_N0f3xd9SizIZ-qlIwHiX4xLHtvTZIjdmfyzXxPm_MK_aMOXmX0F6DQn5tgMzAggEdKSD6YdU8HM256zLQeddczrrDI5P3SASiBJ6MCUM4AzbvoFuFAilQi0WzpLpmlJw", http.StatusOK, false},

		//		{
		//			"exp": "2099-04-23T18:25:43.511Z",
		//			"iat": "2000-04-23T18:25:43.511Z",
		//			"nbf": "2000-04-23T18:25:43.511Z",
		//			"aud": "tests"
		//		}
		{"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDk5LTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJpYXQiOiIyMDAwLTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJuYmYiOiIyMDAwLTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJhdWQiOiJ0ZXN0cyJ9.NQZCoKU2qoC-_VFi-_8fQDzObeQrnld9wyaqF0jYHL_wqROn5VumCDVl1oxMN7g-L9wqo5U-xUXf1HS_Ae6CLDFlkbd6dI-h1_l7_ALn_L_GoxQsEo2lQUDQ-Q4eqlLabc764cTYFXd5EwcsZMHWs5ZFCeMOv3exfeTmg8E9e1FiyuTuKVjvMxL-ZCh113nzXEGFr6GRzqjL6VSnJPDX0Pv78R9tnL6CqWbCuDBlIPOccbpWLuWF0yKjV-OyvcWpjkLIVtAbrimi3A7cNUI_V3EJm9Y4tr8e6hv9zViPNbhycmqvOp-vur2k64PrzeMcbuj7TFRCJg2V3moPJF3NtQ", http.StatusOK, true},

		//		{
		//			"exp": "2099-04-23T18:25:43.511Z",
		//			"iat": "2000-04-23T18:25:43.511Z",
		//			"nbf": "2000-04-23T18:25:43.511Z",
		//			"aud": "tests"
		//		}
		{"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDk5LTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJpYXQiOiIyMDAwLTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJuYmYiOiIyMDAwLTA0LTIzVDE4OjI1OjQzLjUxMVoiLCJhdWQiOiJ0ZXN0cyJ9.NQZCoKU2qoC-_VFi-_8fQDzObeQrnld9wyaqF0jYHL_wqROn5VumCDVl1oxMN7g-L9wqo5U-xUXf1HS_Ae6CLDFlkbd6dI-h1_l7_ALn_L_GoxQsEo2lQUDQ-Q4eqlLabc764cTYFXd5EwcsZMHWs5ZFCeMOv3exfeTmg8E9e1FiyuTuKVjvMxL-ZCh113nzXEGFr6GRzqjL6VSnJPDX0Pv78R9tnL6CqWbCuDBlIPOccbpWLuWF0yKjV-OyvcWpjkLIVtAbrimi3A7cNUI_V3EJm9Y4tr8e6hv9zViPNbhycmqvOp-vur2k64PrzeMcbuj7TFRCJg2V3moPJF3NtQ", http.StatusOK, true},
	} {

		client := &http.Client{}
		form := url.Values{}
		form.Add("token", access.AccessToken)

		req, _ := http.NewRequest("POST", ts.URL+"/oauth2/introspect", strings.NewReader(form.Encode()))
		if c.accessToken != "" {
			req.Header.Add("Authorization", c.accessToken)
		}
		res, _ := client.Do(req)
		body, _ := ioutil.ReadAll(res.Body)
		require.Equal(t, c.code, res.StatusCode, "Case %d: %s", k, body)
		if res.StatusCode != http.StatusOK {
			continue
		}

		var result map[string]interface{}
		require.Nil(t, json.Unmarshal(body, &result))
		assert.Equal(t, c.pass, result["active"].(bool), "Case %d", k)
	}
}
예제 #22
0
파일: auth_test.go 프로젝트: thanzen/hydra
func TestNewContextFromAuthorization(t *testing.T) {
	for _, c := range []struct {
		id              string
		privateKey      []byte
		publicKey       []byte
		authorization   string
		isAuthenticated bool
	}{
		{
			"1",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// {"foo": "bar"}
			"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
			false,
		},
		{
			"2",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// {"subject": "nonexistent"}
			"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWJqZWN0Ijoibm9uZXhpc3RlbnQifQ.jDUnvVMQHrhuIRUr8qAJ0g-ZKArdiJ21LAPDktmV56KFknX712Yxdder78YjEjxvGOvgtxLpCiay0cV5pvcWLuFW65Ys1P1SwdmdebtWfiGQwBy2Ggm3MrHjD_-r5JNAxFZjFZfZ1Fk-JlSZ97r8S7gYfDSAkxhpDmDy5Bm8e5_xsGDNp8dByuXop7QEtJb_igaa0APWa2ZOp3oTgxjD4CP6ZX6N5fGjtwjJWx5wHt7JaKXq8CRG8elm7LnNezYyJxeHECVctQGVv3HUjJxKf0l7wZXbG87BrG2M7otT8Py2sJP8X4wYL0DEsbErkEieV4D-KEBqpkvfXOrDGMFNRQ",
			false,
		},
		{
			"3",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// not a valid token
			"Bearer eyJ0eXAaOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWJqZWN0IjoiMTMyIn0.WDC51GK5wIQPd00MqLjFy3AU3gNsvsCpWk5e8RObVxBqcYAdv-UwMfEUAFE6Y50C5pQ1t8_LHfxJYNfcW3fj_x5FXckdbqvpXHi-psxuDwk_rancpjZQegcutqYRH37_lnJ8lIq65ZgxnyYnQKGOMl3w7etK1gOvqEcP_eHn8HG0jeVk0SDZm82x0JXSk0lrVEEjWmWYtXEsLz0E4clNPUW37K9eyjYFKnyVCIPfmGwTlkDLjANsyu0P6kFiV28V1_XedtJXDI3MmG2SxSHogDhZJLb298JBwod0d6wTyygI9mUbX-C0PklTJTxIhSs7Pc6unNlWnbyL8Z4FJrdSEw",
			false,
		},
		{
			"4",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			//		{
			//			"exp": "2099-10-31T15:03:52.4620974+01:00",
			//			"iat": "2014-10-31T13:03:52.4620974+01:00",
			//			"nbf": "2014-10-31T13:03:52.4620974+01:00",
			//			"sub": "132"
			//		}
			"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDk5LTEwLTMxVDE1OjAzOjUyLjQ2MjA5NzQrMDE6MDAiLCJpYXQiOiIyMDE0LTEwLTMxVDEzOjAzOjUyLjQ2MjA5NzQrMDE6MDAiLCJuYmYiOiIyMDE0LTEwLTMxVDEzOjAzOjUyLjQ2MjA5NzQrMDE6MDAiLCJzdWIiOiIxMzIifQ.qnZr-msiG5GkVTDTyY3g26c5Edho36_E9CaANyCBVOrXWRfRPDMf7E2vrdZubO5tXlfKRgM_1avFQVWZhqrdrGBO8DiBa5OGX9IdAZaclqQFjg7vRSyIFllSs4zP4QREG4YL0qwiYGKS4SBcCS2LNfbaJfrKP_zUReXRAlWNdeFAw6zsGzlAtHQO_O0HnJCEB_wEBIkMIxdI2f-1yyTZJInyvY_wrFDkCkTfkmmW8EHzO2R44FXmaudxDCG1YAeN6WssAwgzBjR8WaQ2M_8VUYWN9TCDc3Fx58XWRTtWL_coDI9R6WtqaPkyr2_qn1Un3y3yLCGdVglRYnhJL1YCXA",
			true,
		},
		{
			"5",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			"",
			false,
		},
	} {
		message := "ok"
		ctx := context.Background()

		j := hjwt.New(c.privateKey, c.publicKey)

		ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx = NewContextFromAuthorization(ctx, r, j, ladonStore)
			assert.Equal(t, c.isAuthenticated, IsAuthenticatedFromContext(ctx), "Case %s", c.id)
			fmt.Fprintln(w, message)
		}))
		defer ts.Close()

		client := &http.Client{}
		req, err := http.NewRequest("GET", ts.URL, nil)
		require.Nil(t, err)
		req.Header.Set("Authorization", c.authorization)
		res, err := client.Do(req)
		require.Nil(t, err)

		result, err := ioutil.ReadAll(res.Body)
		res.Body.Close()

		require.Nil(t, err)
		assert.Equal(t, message+"\n", string(result))
	}
}
예제 #23
0
// Equal asserts that two objects are equal.
//
//    require.Equal(t, 123, 123, "123 and 123 should be equal")
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) {
	if !assert.Equal(t, expected, actual, msgAndArgs...) {
		t.FailNow()
	}
}
예제 #24
0
func TestGetID(t *testing.T) {
	assert.Equal(t, "123", mock.GetID())
}