· To get token using OAuth, add following code in Configuration() function of startup class:
HttpConfiguration config = new HttpConfiguration(); // create object of configuration
WebApiConfig.Register(config); // call Register method having routing, cors etc. code
config.Formatters.Remove(config.Formatters.XmlFormatter); // remove xml formatter (optional)
app.UseWebApi(config);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"), //from this path we will get token
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60), //token expiry
Provider = new TestAuthorizationServerProvider() // this class will authorize request
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
· As mentioned above, implement TestAuthorizationServerProvider class as below:
public class TestAuthorizationServerProvider : OAuthAuthorizationServerProvider {
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {
context.Validated(); // after validating request, validate context
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
context.Validated(new ClaimsIdentity(context.Options.AuthenticationType));
}
}
· Now we can call siteURL/token with form url encoded content ("grant_type", "password") to get token. From API we can call this API as below:
using (var client = new HttpClient()) {
client.BaseAddress = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, String.Empty)); //get base url
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //set content type
var postMessage = new Dictionary<string, string>();
postMessage.Add("grant_type", "password");
var Content = new FormUrlEncodedContent(postMessage); //pass formUrlEncdedContent
var tokenResponse = client.PostAsync("token", Content).Result; //call post api and get result
if (tokenResponse.IsSuccessStatusCode) { //check status of api call
responseString = tokenResponse.Content.ReadAsStringAsync().Result; //read result of api
}
}
· Now just add [Authorize] attribute on controller/action to get only authorized requests and pass Authorization header as authorization = “bearer sadfasdfsfsdfsdfsdfd”