HI ,
I am working with Web Api and trying to add token based authentication using OWIN
I have implemented in my code and able to generate the token and access the webapi resource uing the token .
it is working when client and service in the same port and getting problem when both are in different server.
I have implemented Web API CORS and able to access from other server .
I have implemented Microsoft.Owin.Cors and used in the Startup class .
I am using Jquery Ajax method to call the token service .
Here is the code sample i have used .
OWIN Code :
- public class Startup
- {
- public void Configuration(IAppBuilder app)
- {
- HttpConfiguration config = new HttpConfiguration();
- WebApiConfig.Register(config);
- ConfigureOAuth(app);
- app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
- app.UseWebApi(config);
- }
- public void ConfigureOAuth(IAppBuilder app)
- {
- OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
- {
- AllowInsecureHttp = true,
- TokenEndpointPath = new PathString("/WagtokenService"),
- AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
- Provider = new ProjectAuthorizationServiceProvider()
- };
- // Token Generation
- app.UseOAuthAuthorizationServer(OAuthServerOptions);
- app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
- }
- }
- public class ProjectAuthorizationServiceProvider : OAuthAuthorizationServerProvider
- {
- public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
- {
- context.Validated();
- }
- public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
- {
- var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
- if (allowedOrigin == null) allowedOrigin = "*";
- bool isValidUser = false;
- context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
- if (context.UserName == "[email protected]" && context.Password == "national")
- {
- isValidUser = true;
- }
- if (!isValidUser)
- {
- context.SetError("invalid_grant", "The user name or password is incorrect.");
- return;
- }
- var identity = new ClaimsIdentity(context.Options.AuthenticationType);
- identity.AddClaim(new Claim("sub", context.UserName));
- identity.AddClaim(new Claim("role", "admin"));
- context.Validated(identity);
- }
- }
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- var cors = new EnableCorsAttribute("http://192.168.2.175:3330", "WagtokenService,accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");
- config.EnableCors(cors);
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- config.Routes.MapHttpRoute(
- name: "NewActionApi",
- routeTemplate: "api/{controller}/{action}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- $('#a_login').click(function (e) {
- debugger;
- if (isValidEmailAddress($('#txt_UID').val()) && $('#txt_PWD').val() != "") {
- var loginData = {
- grant_type: 'password',
- username: $('#txt_UID').val(),
- password: $('#txt_PWD').val()
- };
- $.ajax({
- url: url_bearerToken,
- type: 'POST',
- data: loginData,
- contentType: "application/json",
- done: function (data) {
- // alert('success fully sign in to the application');
- sessionStorage.setItem(bearer_token_key, data.access_token);
- },
- success: function (data) {
- // alert('success fully sign in to the application');
- sessionStorage.setItem(bearer_token_key, data.access_token);
- window.location.href = "../Admin/UserProfiler.html";
- },
- error: function (x, h, r) {
- ///e.preventDefault();
- // alert("Invalid user credentials");
- $('#div_alert').show();
- sessionStorage.setItem(bearer_token_key, '');
- }
- });
- }
- else {
- $('#div_alert').show();
- }
- });
XMLHttpRequest cannot load http://localhost:53014/WagtokenService. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.175:3330' is therefore not allowed access.

Bikesh SrivastavaPosted Dec 9, 2016, 7:25 AM
Ravi Kiran ChanduriPosted Dec 13, 2016, 9:02 AM
Ravi Kiran ChanduriPosted Dec 9, 2016, 7:33 AM
Ravi Kiran ChanduriPosted Dec 9, 2016, 7:20 AM
Fabio Silva LimaPosted Dec 9, 2016, 6:01 AM
Bikesh SrivastavaPosted Dec 9, 2016, 6:01 AM