Fail to connect an ASP.NET Web Client to a Web API 2.0 individual account authentication server

846 views Asked by At

I am trying to connect an ASP.NET Single Page Application to a ASP.NET Web API 2.0 server with individual authentication. I am able to authenticate with the server using Fiddler and raw http requests as shown in the below tutorial:

Individual Accounts in Web API

My question is how do I point the separate single page client sample easily to the Web API service? Is it just a simple change in a configuration file or a connection string somewhere?

Surprisingly I cannot find that much info on how to do this on the web probably because it is deceptively simple and I am just missing something because I am new to ASP.NET

Update:

I basically want this to point to a different Web API 2.0 server:

 static Startup()
    {
        PublicClientId = "self";

        UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };
    }


public void ConfigureAuth(IAppBuilder app)
    {
        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);


....
}

That currently points to the root of the application but the Web API 2.0 server is actually on another ASP.NET Application running somewhere else.

2

There are 2 answers

0
VsMaX On

This is all code you need to send request to Web Api 2.0:

//line below is for supporting self-generated ssl certificates, you can ommit if you're using http
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 
HttpClientHandler handler = new HttpClientHandler();
//this credentials will be in header
handler.Credentials = new NetworkCredential("someLogin", "somepassword");
client = new HttpClient(handler);

client.BaseAddress = new Uri("http://localhost:4567");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
mediaTypeFormatter = new JsonMediaTypeFormatter();
var content = new ObjectContent<T>(item, mediaTypeFormatter);
var response = await client.PostAsync("api/account/register", content);
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.BadRequest)
{
    throw new ArgumentException("Internal server error");
}
//and here you have successfully sent request and received response from web api.

You can put it into some method then and use method parameters to pass for example host Uri. You can have that saved for example in Web.config as you mentioned.

0
Louie Bacaj On

So after working with the new ASP.NET MVC 5 and the Single Page Application templates in visual studio 2013 I found that the authentication and security is significantly different. This isn't so obvious from any of the documentation.

They both use the "new" ASP.NET Identity which replaces the older membership however when you use the ASP.NET MVC 5 template you get the same old SQL Server type of security setup through the controllers that used to be there, with the SPA (Single Page Application) Template you get API based token authentication.

The only way to wire up the SPA to another API 2.0 located somewhere else is on the client side of things on the JavaScript side, which is slightly confusing because that's not how the ASP.NET MVC 5 template works. The confusion comes from the fact that the SPA gives you both the server side and the client side setup.