简体   繁体   中英

How to authenticate from automated tests against WebAPI with Owin security?

I have a .net web api app with owin security. The security middleware is configured with Google authentication (no local username/password authentication) and Oauth bearer token.

In startup:

public void ConfigureAuth(IAppBuilder app)
{
   ...
   app.UseOAuthBearerTokens(new OAuthAuthnorizationServerOptions {
      TokenEndpointPath = new PathString("/token"),
      AuthorizeEndpointPath = new PathString("/account/authorize"),
      Provider = new ApplicationOAuthProvider("web"),
      ...
   });

   app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions {
      ClientID = "...",
      ClientSecret = "..."
   });
}

From my client applications I go to

http://myapp.com/account/authorize?client_id=web&response_type=token&redirect_uri=...

This redirects to a google login that the user fills in, then back to my app with a bearer token that I peel off and add to request headers for my api.

I would like to write some integration tests where my tests call the API. The tests have the google credentials of a test user, but I am not sure how to have the test authenticate without bringing up a browser and a google login screen. I could drive that with Selenium but that seems heavy-handed.

How do I programmatically get a bearer token to use with my API such that I can impersonate my test user?

Normally you would use the OAuth2 resource owner password credentials grant in this case, but Google does not seem to support that .

So your best option seems to be to use the authorization code grant to authenticate the test user, extract the refresh token from the token endpoint response. Then use the refresh token and client ID and secret to get an access token from your integration test.

See this for more information: https://developers.google.com/identity/protocols/OAuth2InstalledApp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM