none
Owin authentication - GrantResourceOwnerCredentials not executed RRS feed

  • Question

  • Hi!I'm trieng to use Owin authentication with existing user tables,I've followed this link

    https://www.codeproject.com/Articles/1187872/Token-Based-Authentication-for-Web-API-where-Legac



    and added the code in my app.If I put  [Authorize] to action I get on Postman GET request 

    http://localhost:3590/api/com/opened

    {
        "$id": "1",
        "Message": "Authorization has been denied for this request."
    }



    If I try to get the token using POST to http://localhost:3590/Token I got this:

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Index</title> <link href="/Content/jquery-ui.min.css" rel="stylesheet"/> <link href="/Content/bootstrap.css" rel="stylesheet"/> <link href="/Content/font-awesome.css" rel="stylesheet"/> <link href="/Content/keyboard.css" rel="stylesheet"/> <link href="/Content/site.css" rel="stylesheet"/> <script src="/Scripts/modernizr-2.8.3.js"></script> <script src="/node_modules/core-js/client/shim.min.js"></script> <script src="/node_modules/zone.js/dist/zone.js"></script> <script src="/node_modules/systemjs/dist/system.src.js"></script> <script src="/systemjs.config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> </head> <body> <div class="container body-content"> <body> <div class="container"> <user-app><i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw fa-i-centered"></i><user-app> </div> <!-- Visual Studio Browser Link --> <script type="application/json" id="__browserLink_initializationData"> {"appName":"Chrome","requestId":"037898ef990f483a86c5d74934d87d55"} </script> <script type="text/javascript" src="http://localhost:2756/3bde59ad8ad64b279f336adff8c4a10a/browserLink" async="async"></script> <!-- End Browser Link --> </body> <footer> </footer> </div> <script src="/Scripts/jquery-3.2.1.js"></script> <script src="/Scripts/jquery-ui.min.js"></script> <script src="/Scripts/bootstrap.js"></script> <script src="/Scripts/jquery.keyboard.js"></script> <script src="/Scripts/respond.js"></script>

    </body>
    </html>




        

    Debuging the code,GrantResourceOwnerCredentials it is not executed
     this is GrantResourceOwnerCredentials code:
     
     
    public override async Task GrantResourceOwnerCredentials
            (OAuthGrantResourceOwnerCredentialsContext context)
            {
                using (var obj = new POSEntities())
                {
    
                    GS_POS_OPERATORI entry = obj.GS_POS_OPERATORI.Where(o =>
                    o.NAME == context.UserName &&
                    o.PASSWOR  == context.Password).FirstOrDefault();
    
                    if (entry == null)
                    {
                        context.SetError("invalid_grant",
                        "The user name or password is incorrect.");
                        return;
                    }
                }
    
    
                ClaimsIdentity oAuthIdentity =
                new ClaimsIdentity(context.Options.AuthenticationType);
                ClaimsIdentity cookiesIdentity =
                new ClaimsIdentity(context.Options.AuthenticationType);
    
                AuthenticationProperties properties = CreateProperties(context.UserName);
                AuthenticationTicket ticket =
                new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
     
     


     I'm also using Angular 4 for front
     thanks for any help










    • Edited by Johny27 Thursday, October 12, 2017 7:27 AM
    Thursday, October 12, 2017 6:18 AM

Answers

  • Hi Johny27,

    It seems you missed the step which changes the WebApiConfig.cs, you need to add below code to your current WebApiConfig.cs.

                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    

    I suggest you make a test with below code.

    public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
                config.Formatters.Remove(config.Formatters.XmlFormatter);
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
                config.MapHttpAttributeRoutes();
                 
    
                config.Routes.MapHttpRoute(
                    name: "ActionApi", 
                     routeTemplate: "api/{controller}/{action}/{id}", //"api/{controller}/{id}"
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

    Best Regards,

    Edward


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Johny27 Thursday, October 12, 2017 9:06 AM
    Thursday, October 12, 2017 7:51 AM

All replies

  • Hi Johny27,

    >> If I try to get the token using POST to http://localhost:3590/Token

    How did you try to get the token? I made a test by following the link, and send Token request on Postman, it returns the expected response, and GrantResourceOwnerCredentials has been hit.

    Best Regards,

    Edward


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, October 12, 2017 7:30 AM
  • Hi I've used Postman and sent POST request to http://localhost:3590/Token  and set values for user,password and grant_type as in image abolve..I'm thinking that could be something wrong in my api route configuration

     public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
                config.Formatters.Remove(config.Formatters.XmlFormatter);
    
                config.MapHttpAttributeRoutes();
                 
    
                config.Routes.MapHttpRoute(
                    name: "ActionApi", 
                     routeTemplate: "api/{controller}/{action}/{id}", //"api/{controller}/{id}"
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

    or in my Angular 4 route :

    const appRoutes: Routes = [
        { path: '', redirectTo: 'op', pathMatch: 'full' },
        { path: 'op', component: OpComponent },
        { path: 'mes', component: MesComponent, canActivate: [UserGuard] },
        { path: 'com', component: ComComponent, canActivate: [UserGuard] }
        
    ];
    thanks


    • Edited by Johny27 Thursday, October 12, 2017 7:42 AM
    Thursday, October 12, 2017 7:42 AM
  • Hi Johny27,

    It seems you missed the step which changes the WebApiConfig.cs, you need to add below code to your current WebApiConfig.cs.

                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    

    I suggest you make a test with below code.

    public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
                config.Formatters.Remove(config.Formatters.XmlFormatter);
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
                config.MapHttpAttributeRoutes();
                 
    
                config.Routes.MapHttpRoute(
                    name: "ActionApi", 
                     routeTemplate: "api/{controller}/{action}/{id}", //"api/{controller}/{id}"
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

    Best Regards,

    Edward


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Johny27 Thursday, October 12, 2017 9:06 AM
    Thursday, October 12, 2017 7:51 AM
  • Hi,I've used your code but now on GET request I have tis message:

    {
        "$id": "1",
        "Message": "An error has occurred.",
        "ExceptionMessage": "No OWIN authentication manager is associated with the request.",
        "ExceptionType": "System.InvalidOperationException",
        "StackTrace": "   at System.Web.Http.Owin.PassiveAuthenticationMessageHandler.SuppressDefaultAuthenticationChallenges(HttpRequestMessage request)\r\n   at System.Web.Http.Owin.PassiveAuthenticationMessageHandler.<SendAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()"
    }


    on POST,just the same as before

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width" />
            <title>Index</title>
            <link href="/Content/jquery-ui.min.css" rel="stylesheet"/>
            <link href="/Content/bootstrap.css" rel="stylesheet"/>
            <link href="/Content/font-awesome.css" rel="stylesheet"/>
            <link href="/Content/keyboard.css" rel="stylesheet"/>
            <link href="/Content/site.css" rel="stylesheet"/>
            <script src="/Scripts/modernizr-2.8.3.js"></script>
            <script src="/node_modules/core-js/client/shim.min.js"></script>
            <script src="/node_modules/zone.js/dist/zone.js"></script>
            <script src="/node_modules/systemjs/dist/system.src.js"></script>
            <script src="/systemjs.config.js"></script>
            <script>
       System.import('app').catch(function(err){ console.error(err); });
        </script>
        </head>
        <body>
            <div class="container body-content">
                <body>
                    <div class="container">
                        <user-app>
                            <i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw fa-i-centered"></i>
                            <user-app>
        
                            </div>
                            <!-- Visual Studio Browser Link -->
                            <script type="application/json" id="__browserLink_initializationData">
        {"appName":"Chrome","requestId":"50c439682c584c289ebfba6aa52aa2d2"}
    </script>
                            <script type="text/javascript" src="http://localhost:7452/739a7052646f4bea8695afd71a1ee495/browserLink" async="async"></script>
                            <!-- End Browser Link -->
    
    
                        </body>
                        <footer>
                
            </footer>
                    </div>
                    <script src="/Scripts/jquery-3.2.1.js"></script>
                    <script src="/Scripts/jquery-ui.min.js"></script>
                    <script src="/Scripts/bootstrap.js"></script>
                    <script src="/Scripts/jquery.keyboard.js"></script>
                    <script src="/Scripts/respond.js"></script>
                </body>
            </html>
    thanks

    Thursday, October 12, 2017 8:07 AM
  • I've followed this  https://stackoverflow.com/questions/21089196/no-owin-authentication-manager-is-associated-with-the-request

    and installed  Microsoft.Owin.Host.SystemWeb,

    error is gone,GrantResourceOwnerCredentials is executed  and I get the expected response,

    what is next step in my app,afther I have user and pass send request to get the token and all is done?

    also for GrantResourceOwnerCredentials I have this warning:

    Warning

    This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. POSweb D:\myapp\Providers\ApplicationOAuthProvider.cs

    thanks 





    • Edited by Johny27 Thursday, October 12, 2017 9:06 AM
    Thursday, October 12, 2017 8:27 AM
  • Hi Johny27,

    >> what is next step in my app,afther I have user and pass send request to get the token and all is done?

    After getting token, you just need to add token on next request to call API method. You could check the CodeProject to see how to request web api method.

    If you have any trouble about this, please feel free to post a new thread, and share us your steps.

    Best Regards,

    Edward


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, October 12, 2017 9:26 AM