DNN Forums

Ask questions about your website to get help learning DNN and help resolve issues.

Using JWT authentication fra a windows desktop app

Sort:
You are not authorized to post a reply.





New Around Here





    My service looks like this

    namespace Poul.Erik.Modules.ModulDatabase.Services
    {
        public class ImageController : DnnApiController
        {
            public ImageController() { }
            
            [DnnAuthorize(AuthTypes = "JWT")]
            [HttpGet]
            public HttpResponseMessage GetAllModules()
            {
                try
                {
                    //Load Data Into List
                    var moduler = ModulManager.Instance.GetModuler(ActiveModule.ModuleID).OrderBy(m => m.ModulNavn, StringComparer.CurrentCultureIgnoreCase);

                    //Convert List Into JSON
                    var jsonModules = JsonSerializer.Serialize(moduler);

                    //Create a HTTP response - Set to OK
                    var res = Request.CreateResponse(HttpStatusCode.OK);

                    //Set the content of the response to be JSON Format
                    res.Content = new StringContent(jsonModules, System.Text.Encoding.UTF8, "application/json");

                    //Return the Response
                    return res;
                }
                catch (Exception exc)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
                }
            }
        }
    }

    The RegisterRoutes look like this

    public void RegisterRoutes(IMapRoute mapRouteManager)
            {
                mapRouteManager.MapHttpRoute(
                    moduleFolderName: "ModulService",
                    routeName: "default",
                    url: "{controller}/{action}",
                    namespaces: new[] { "Poul.Erik.Modules.ModulDatabase.Services" });
            }

    I have testet the routing just using a web browser and the result proows thathe service can be reached, but requires authentication:

    Authorization has been denied for this request.

    So far so good.

    Next the windows app:

    await ProcessRepositoriesAsync(httpClient);

    static async Task ProcessRepositoriesAsync(HttpClient client)
    {
        var values = new Dictionary<string, string>
        {
            { "u", "......." },
            { "p", "............" }
        };

        var content = new StringContent(JsonSerializer.Serialize(values), Encoding.UTF8, "application/json");

        var response = await client.PostAsync(("http://development911.dnn...mobile/login"), content);

        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var responseString = await response.Content.ReadAsStringAsync();

            var LoginResultData = JsonSerializer.Deserialize<LoginResultData>(responseString);

            if (LoginResultData != null)
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", LoginResultData.accessToken);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                response = await client.GetAsync("http://development911.dnn...etAllModules");


                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    responseString = await response.Content.ReadAsStringAsync();
                }
            }
        }

    The post resuest for getting the token suceeds, but the get request fails with 401.

    This wrom the IIS log:
    2023-02-04 11:52:44 127.0.0.1 POST /API/JwtAuth/mobile/login - 80 - 127.0.0.1 - - 200 0 0 51
    2023-02-04 11:52:49 127.0.0.1 GET /API/ModulService/Image/GetAllModules - 80 - 127.0.0.1 - - 401 0 0 13

    DNN version is 9.11.0,

    IIS is running on my local machine

    The windows app is a console app targeting .NET 6

    Tha app is also running on my local machine

    I hope somone can help me out.

    Thank you in advance

    Poul Erik






    New Around Here





      It's time to say its an error40.

      The service is part of an MVC based module and therefore I have after 4 days of intensive testing added MVC to the moduleFolderName as shown below.

      mapRouteManager.MapHttpRoute(
      moduleFolderName: "MVC/ModulService",
      routeName: "default",
      url: "{controller}/{action}",
      namespaces: new[] { "Poul.Erik.Modules.ModulDatabase.Services" });

      Now everything works perfect.

      Poul Erik





      Veteran Member





        Oh, I'm just seeing this...  I created a blog post recently that helps people determine routes so they can worry more about the real code in your project and not about the route.  :)  

        https://dnncommunity.org/...eb-API-Routes-in-DNN






        New Around Here





          Thanks Will.

          Just installed it. Nice

          /Poul Erik

          You are not authorized to post a reply.

          These Forums are dedicated to the discussion of DNN Platform.

          For the benefit of the community and to protect the integrity of the ecosystem, please observe the following posting guidelines:

          1. If you have (suspected) security issues, please DO NOT post them in the forums but instead follow the official DNN security policy
          2. No Advertising. This includes the promotion of commercial and non-commercial products or services which are not directly related to DNN.
          3. No vendor trolling / poaching. If someone posts about a vendor issue, allow the vendor or other customers to respond. Any post that looks like trolling / poaching will be removed.
          4. Discussion or promotion of DNN Platform product releases under a different brand name are strictly prohibited.
          5. No Flaming or Trolling.
          6. No Profanity, Racism, or Prejudice.
          7. Site Moderators have the final word on approving / removing a thread or post or comment.
          8. English language posting only, please.

          Would you like to help us?

          Awesome! Simply post in the forums using the link below and we'll get you started.

          Get Involved