1

I have come across a situation where I make a call from my angular 7 application to my asp.net web api application. When I call an HTTP post method in angular to the application running on a different port it throws an exception.

Access to XMLHttpRequest at 'http://localhost/oauthservice/api/token' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My Angular application Running on 'http://localhost:4200' port number:4200 My asp.net web api application running on 'http://localhost/oauthservice/api/token': port number:80 Microsoft IIS .

if you have a time please help me.

                                        

sign-in.component.ts

OnSubmit(userName: any, password: any) {
 this.userService.userAuthentication(userName, password).subscribe((data: any) => {
   localStorage.setItem('userToken', JSON.stringify(data));
   this.router.navigate(['/home']);
 },
 (err: HttpErrorResponse) => {
     this.isLoginError = true;
   });
}

user.service.ts

userAuthentication(userName, password) {
const data = 'grant_type=password&username=' + userName + '&password=' + password;
// let reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'No-Auth': 'True' });
 // tslint:disable-next-line:max-line-length
 return this.http.post(this.apiUrl + 'token', data, { headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
  }

form server side

startup.cs

public void ConfigureOAuth(IAppBuilder app, HttpConfiguration config)
        {
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {

                TokenEndpointPath = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new AuthorizationServerProvider((IAccountsRepository)config.DependencyResolver.GetService(typeof(IAccountsRepository))),
                RefreshTokenProvider = new RefreshTokenProvider(),
                AllowInsecureHttp = true,
            };
            //Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        }

AuthorizationServerProvider.cs

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);

        //Authenticate the user credentials
        if (_accounts.Login(context.UserName, context.Password))
        {
            t_userDetail user = await _accounts.GetUserDetails(context.UserName);

            identity.AddClaim(new Claim(ClaimTypes.Role, _accounts.GetUserRole(context.UserName)));
            identity.AddClaim(new Claim("username", context.UserName));
            identity.AddClaim(new Claim("fullName", user.firstName + " " + user.lastName));
            identity.AddClaim(new Claim("Email", user.email));
            identity.AddClaim(new Claim("Phone", user.phone));
            identity.AddClaim(new Claim("role", _accounts.GetUserRole(context.UserName)));
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("LoggedOn",DateTime.Now.ToString()));

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "as:client_id", context.ClientId ?? string.Empty
                },
                {
                    "userName", context.UserName
                },
                {
                    "fullName",user.firstName + " "  + user.lastName
                },
                {
                    "Email", user.email
                },
                {
                    "role", _accounts.GetUserRole(context.UserName)
                },
                {
                    "Phone", user.phone
                },

            });
            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
        else
        {
            context.SetError("invalid_grant", "Provided username or password is incorrect");
        }
    }
Mes Fine
  • 33
  • 1
  • 1
  • 8
  • 2
    I have edited your tags because the issue has nothing to do with Angular. You juste have to allow your client origin on your API, which is ASP.NET. Some people might help you, but that's all I can do. Good luck ! –  Jan 11 '19 at 13:47

1 Answers1

0

CORS is when a web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin. The best solution is to reconfigure the server but for quick testing, using a proxy can help.

Jae Yang
  • 479
  • 3
  • 13