locked
Owin Authentication for Microsoft RRS feed

  • Question

  • User-1297497848 posted

    Hello All,

    I try to include OWIN authentication to my application using this tutorial :

    https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-webapp#how-the-sample-works

    The Sample Code downloaded from the website works fine but i try to include it in my application with no success.
    I use "Request.IsAuthenticated" to know if i'm connected or not. 
    Impossible to be authenticated and i don't find how to resolve this issue.

    The startup class is correct, i added the few necessary line in Web.config

    I re-do the operations several times with no success...

    I'm on .NET framework 4.6.1

    If someone has an idea to solve this issue...

    Best regards and stay safe,

    Bertrand

    Wednesday, April 8, 2020 12:18 PM

All replies

  • User753101303 posted

    Hi,

    What happens is not 100% clear. Do you mean that you have a button that triggers the authentication process, that you trigger this, but that you are still not authenticated without any apparent error? It's easier to solve your issue if we fully understand which problem you have.

    Wednesday, April 8, 2020 12:45 PM
  • User-1297497848 posted

    Hi,

    Sorry if it is not clear.

    Yes, i have a button that triggers the authentication process. I can connect with my microsoft account without any errors.
    But after the login, it redirect to my website (in this case, the localhost) and i'm not authenticate.

    To see if i'm authenticated, i use thise code in my view :

    @if (Request.IsAuthenticated)
    {
        <h1>Authentifié !</h1>
    }
    else
    {
        <h1>Pas Authentifié !</h1>
    }

    Thank you so much for your help :)

    Bertrand

    Wednesday, April 8, 2020 1:23 PM
  • User-17257777 posted

    Hi bertho,

    You can use f12 developer tool network to check if the token is returned correctly after you log in.

    Best Regards,

    Jiadong Meng

    Thursday, April 9, 2020 7:12 AM
  • User753101303 posted

    Hi,

    As pointed already F12 Network is always a good idea to understand what happens for http requests. Make sure cookies are not blocked (but the other sample works with the same browser?)

    My next step would to check if AuthenticationFailed is called as well maybe as other notifications found at https://docs.microsoft.com/en-us/previous-versions/aspnet/dn800270%28v%3dvs.113%29 to better track what happens.

    It's often shorter to spend few extra minutes to better understand what happens exactly rather than spendng and more in trying to guess without enough information.

    Thursday, April 9, 2020 7:40 AM
  • User-1297497848 posted

    Hello,

    I just try and see no errors...

    I try with my app and with the app distributed by microsoft but it has no difference between both...

    Thank you for your reply.

    Bertrand

    Thursday, April 9, 2020 7:47 AM
  • User-1297497848 posted

    Hi,

    Thank you for the link, i will check it.

    And yes, the sample from microsoft works fine.

    Bertrand

    Thursday, April 9, 2020 7:48 AM
  • User475983607 posted

    bertho

    The Sample Code downloaded from the website works fine but i try to include it in my application with no success.

    Can you clarify this comment.  You downloaded the sample application and the code functions as expected.  Next, you copied key parts of the working sample code into an existing web project and authentication is not working as expected.

    Did you register your existing application?  Can you share your code that shows how you integrated the code?  Have you tried running your code through the Visual Studio debugger?

    Thursday, April 9, 2020 11:34 AM
  • User-1297497848 posted

    Hello,

    Yes you are right...

    I downloaded the sample and it works perfectly.

    When i try to implement it into my existing application, it does not work... and i don't know why. i followed the microsoft tutorial with no success. I verify my configuration several times.

    When i say it does not work, it means that i can authenticate on Microsoft but when it redirect to my application, i'm not authenticated...

    I hope it is clear :s

    Thank you,

    Bertrand

    Thursday, April 9, 2020 11:50 AM
  • User-1297497848 posted

    Did you register your existing application?  Can you share your code that shows how you integrated the code?  Have you tried running your code through the Visual Studio debugger?

    Yes, my application is registered (i use these param into to sample and it works with the sample)

    i installed the require package as indicated on the tutorial.

    i created the statup.cs class (it is the same as the example). and configured the web.config file with the needed parameter.

    I also created a new Controller to signup with microsoft...

    What files do you want to see?

    Bertrand

    Thursday, April 9, 2020 11:55 AM
  • User475983607 posted

    bertho

    Yes, my application is registered (i use these param into to sample and it works with the sample)

    You kept the same configuration?  Did you add/registered the new redirect URL in Azure configuration?

    bertho

    What files do you want to see?

    For one, the Action where you are checking authentication and the login Action.  Do you have an empty catch that hides exception?  Are you checking  authentication before the cookie is set?  

    Lastly, the community has asked you to do basic debugging.  But you have not provided any feedback.  Did you try dev tools and look for the auth cookie?  Did you run your code through the Visual Studio debugger?

    Thursday, April 9, 2020 12:32 PM
  • User-1297497848 posted

    You kept the same configuration?  Did you add/registered the new redirect URL in Azure configuration?

    Yes, i added the right redirect URL.

    For one, the Action where you are checking authentication and the login Action.  Do you have an empty catch that hides exception?  Are you checking  authentication before the cookie is set?  

    Here is the "Microsoft" Controller i created to signin and signout. I redirect to the Index of this controller after authentication

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OpenIdConnect;
    
    namespace vCenterManager.Website.Controllers
    {
        public class MicrosoftController : Controller
        {
            // GET: Microsoft
            public ActionResult Index()
            {
                if (Request.IsAuthenticated)
                {
    //Use in debug } return View(); } /// <summary> /// Send an OpenID Connect sign-in request. /// Alternatively, you can just decorate the SignIn method with the [Authorize] attribute /// </summary> public void SignIn() { if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/Microsoft" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } /// <summary> /// Send an OpenID Connect sign-out request. /// </summary> public void SignOut() { HttpContext.GetOwinContext().Authentication.SignOut( OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } } }

    Lastly, the community has asked you to do basic debugging.  But you have not provided any feedback.  Did you try dev tools and look for the auth cookie?  Did you run your code through the Visual Studio debugger?

    Yes i try dev tools and i don't find any errors

    Yes i run the code through visual studio debugger and i don't get any errors

    Thank you for your help

    Bertrand

    Thursday, April 9, 2020 12:43 PM
  • User475983607 posted

    I created a demo first using the sample code and then integrated into an existing applcation.  I'm unable to reproduce your results. 

    Thursday, April 9, 2020 2:37 PM
  • User-1297497848 posted

    Hi,

    i'm checking some value in debug mode  

    var _cookie = Request.Cookies;
    
    String[] arr1 = _cookie.AllKeys;

    In the sample application arr1 return : 

    ".AspNet.Cookies"

    And in my application arr1 return 2 values : 

    "OpenIdConnect.nonce.WdHCvqCWT52Q%2BLr4JH0M6ZXdLm%2FWaWZMbb2Omp%2Bb65U%3D"
    "ASP.NET_SessionId"

    In my application, i use a class for simple authentication (the user provide a username and a password)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using vCenterManager.DAL;
    using vCenterManager.Models.User;
    
    namespace vCenterManager.Website.Tools
    {
        public class AuthorizationManager : AuthorizeAttribute
        {
            private List<Role> _roles = new List<Role>();
    
            public AuthorizationManager()
            {
                using (vCenterManagerContext db = new vCenterManagerContext())
                {
                    _roles = db.Roles.ToList();
                }
            }
    
            public AuthorizationManager(params string[] MyRoles)
            {
                using (vCenterManagerContext db = new vCenterManagerContext())
                {
                    foreach (string item in MyRoles)
                    {
                        Role _role = db.Roles.FirstOrDefault(r => r.Name.ToUpper() == item.ToUpper());
                        _roles.Add(_role);
                    }
                }
            }
    
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                UserSession _user = SessionManager.Instance.Session;
    
                if (_user.UserID <= 0)
                {
                    filterContext.Result = new RedirectResult("/User/Login");
                }
                else if (!_roles.Any(r => r == _roles.FirstOrDefault(x => x.RoleID == _user.Role.RoleID)))
                {
                    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                }
            }
        }
    }

    The issue maybe comes from that class?

    Bertrand

    Thursday, April 9, 2020 2:48 PM
  • User475983607 posted

    bertho

    The issue maybe comes from that class?

    If you want community support, you'll need to provide enough sample code to reproduce the issue.  We'll also need an overview of how the existing application works.

    Try creating a new MVC project and integrating the Azure authentication services.  If you're successful then there is probably issues with the project that is not working as expected.  You need to come up with a plan to troubleshoot the code.

    Thursday, April 9, 2020 3:07 PM
  • User-1297497848 posted

    If you want community support, you'll need to provide enough sample code to reproduce the issue.  We'll also need an overview of how the existing application works.

    Try creating a new MVC project and integrating the Azure authentication services.  If you're successful then there is probably issues with the project that is not working as expected.  You need to come up with a plan to troubleshoot the code.

    Ok, 

    Basically, i'm not a developer, so, probably, i don't have the good reflexion about this..

    I will create a new MVC project and try integrating the Azure Authentivation Services.

    If it works, i will try to create a new project based on the template i use for the front end

    Wait and see.

    I'll come back with news as soon as possible.

    Thank you so much to spend you time with me.

    Bertrand

    Thursday, April 9, 2020 3:37 PM
  • User-1297497848 posted

    Hi !

    I created a new MVC project and integrate Azure authentication with success.

    I created a new MVC project based on the asp.net template i use.. with success.

    I will do some other tests...

    Bertrand

    Thursday, April 9, 2020 5:45 PM
  • User-1297497848 posted

    Hello,

    After investigation, i think i found the reason why it doesn't work.

    I recreate my application from scratch and test it after i add a new class (copy/paste from the actual App).

    For the simple authentication (using email + password), i use two class :

    SessionManager.cs and AuthorizationManager.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using vCenterManager.DAL;
    using vCenterManager.Models.User;
    
    namespace vCenterManager.Website.Tools
    {
        public class AuthorizationManager : AuthorizeAttribute
        {
            private List<Role> _roles = new List<Role>();
    
            public AuthorizationManager()
            {
                using (vCenterManagerContext db = new vCenterManagerContext())
                {
                    _roles = db.Roles.ToList();
                }
            }
    
            public AuthorizationManager(params string[] MyRoles)
            {
                using (vCenterManagerContext db = new vCenterManagerContext())
                {
                    foreach (string item in MyRoles)
                    {
                        Role _role = db.Roles.FirstOrDefault(r => r.Name.ToUpper() == item.ToUpper());
                        _roles.Add(_role);
                    }
                }
            }
    
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                UserSession _user = SessionManager.Instance.Session;
    
                if (_user.UserID <= 0)
                {
                    filterContext.Result = new RedirectResult("/User/Login");
                }
                else if (!_roles.Any(r => r == _roles.FirstOrDefault(x => x.RoleID == _user.Role.RoleID)))
                {
                    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                }
            }
        }
    }
    public class SessionManager
        {
            private const string SESSION_KEY = "LoggedUser";
    
            #region Singleton
            private static SessionManager _Instance;
    
            public static SessionManager Instance
            {
                get { return _Instance ?? (_Instance = new SessionManager()); }
            }
    
            private SessionManager() { }
            #endregion
    
            public UserSession Session
            {
                get
                {
                    if (HttpContext.Current.Session[SESSION_KEY] == null)
                    {
                        HttpContext.Current.Session[SESSION_KEY] = new UserSession();
                    }
    
                    return (UserSession)HttpContext.Current.Session[SESSION_KEY];
                }
    
                set { HttpContext.Current.Session[SESSION_KEY] = value; }
            }
    
            public bool IsAuthenticated
            {
                get { return Session.UserID > 0; }
            }
        }

    Here is my HomeController

    using System.Web.Mvc;
    using vCenterManager.Website.Tools;
    
    namespace vCenterManager.Website.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                if (!SessionManager.Instance.IsAuthenticated)
                {
                    return RedirectToAction("Login", "User");
                }
    
                return View();
            }
        }
    }

    If i'm not authenticate, i redirect to the login page

    At this time, i think it delete "HttpContext" and then the owin cookie is also deleted.

    What do you think about that?

    Bertrand

    Friday, April 10, 2020 7:18 AM