Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. ASP.Net Core Identity

ASP.Net Core Identity

Scheduled Pinned Locked Moved ASP.NET
asp-netcsharpdatabasedotnetjson
4 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Mycroft Holmes
    wrote on last edited by
    #1

    Using VS2019 with Core 3 I am attempting to secure a web project. Web API does the validation and returns a JWT token with the user authorisation details, role only. Tihs works fine as the JWT decodes with all the correct info in it. My problem is to get that information into MS Identity (or have I got it completely wrong). I am NOT using EntityFrameworkCore just to service the user validation. My login partial has the following.

    @if (User.Identity.IsAuthenticated)
    {

    		*   				Log out
    

    }
    else
    {

    	*   Log in
    

    }

    The .cs code

    	public async Task OnPostAsync(string returnUrl = null)
    	{
    		CSDUtil.PWDUtil oUtil = new CSDUtil.PWDUtil();
    		try
    		{
    			ReturnUrl = returnUrl;
    			// Verification.
    			if (ModelState.IsValid)
    			{
    				UserDetailsDB data = UserDetails;
    				UserDetailsDB oUser = await dsUserDetails.AutenticateAsync(data);
    				if (oUser == null)
    				{
    					ModelState.AddModelError(string.Empty, "Invalid user details.");
    					return Page();
    				}
    				JwtSecurityTokenHandler oHandler = new JwtSecurityTokenHandler();
    				var key = Code.MainUI.Key;
    				var handler = new JwtSecurityTokenHandler();
    				var jwtToken = new JwtSecurityToken(oUser.Token);
    				var validations = new TokenValidationParameters
    				{
    					ValidateIssuerSigningKey = true,
    					IssuerSigningKey = new SymmetricSecurityKey(key),
    					ValidateIssuer = false,
    					ValidateAudience = false
    				};
    				ClaimsPrincipal oPrincipal = handler.ValidateToken(oUser.Token, validations, out SecurityToken oToken);									
    				int i = oPrincipal.Claims.Count();
    				var authProperties = new AuthenticationProperties
    				{
    					AllowRefresh = true,
    					ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
    					IsPersistent = true,
    					IssuedUtc = DateTimeOffset.Now,
    					RedirectUri = "/Index"
    				};
    				await HttpContext.SignInAsync(
    									CookieAuthenticationDefaults.AuthenticationScheme,
    									new ClaimsPrincipal(oPrincipal),										
    									authProperties); 
    				var B = User.Identity.IsAuthenticated;**///////this is always false**
    				return LocalRedirect(Url.GetLocalUrl(returnUrl));
    			}
    		}
    

    The ClaimsPricipal populates correctly with the details of the user in identities[0] of that collection. How do I mov

    J 1 Reply Last reply
    0
    • M Mycroft Holmes

      Using VS2019 with Core 3 I am attempting to secure a web project. Web API does the validation and returns a JWT token with the user authorisation details, role only. Tihs works fine as the JWT decodes with all the correct info in it. My problem is to get that information into MS Identity (or have I got it completely wrong). I am NOT using EntityFrameworkCore just to service the user validation. My login partial has the following.

      @if (User.Identity.IsAuthenticated)
      {

      		*   				Log out
      

      }
      else
      {

      	*   Log in
      

      }

      The .cs code

      	public async Task OnPostAsync(string returnUrl = null)
      	{
      		CSDUtil.PWDUtil oUtil = new CSDUtil.PWDUtil();
      		try
      		{
      			ReturnUrl = returnUrl;
      			// Verification.
      			if (ModelState.IsValid)
      			{
      				UserDetailsDB data = UserDetails;
      				UserDetailsDB oUser = await dsUserDetails.AutenticateAsync(data);
      				if (oUser == null)
      				{
      					ModelState.AddModelError(string.Empty, "Invalid user details.");
      					return Page();
      				}
      				JwtSecurityTokenHandler oHandler = new JwtSecurityTokenHandler();
      				var key = Code.MainUI.Key;
      				var handler = new JwtSecurityTokenHandler();
      				var jwtToken = new JwtSecurityToken(oUser.Token);
      				var validations = new TokenValidationParameters
      				{
      					ValidateIssuerSigningKey = true,
      					IssuerSigningKey = new SymmetricSecurityKey(key),
      					ValidateIssuer = false,
      					ValidateAudience = false
      				};
      				ClaimsPrincipal oPrincipal = handler.ValidateToken(oUser.Token, validations, out SecurityToken oToken);									
      				int i = oPrincipal.Claims.Count();
      				var authProperties = new AuthenticationProperties
      				{
      					AllowRefresh = true,
      					ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
      					IsPersistent = true,
      					IssuedUtc = DateTimeOffset.Now,
      					RedirectUri = "/Index"
      				};
      				await HttpContext.SignInAsync(
      									CookieAuthenticationDefaults.AuthenticationScheme,
      									new ClaimsPrincipal(oPrincipal),										
      									authProperties); 
      				var B = User.Identity.IsAuthenticated;**///////this is always false**
      				return LocalRedirect(Url.GetLocalUrl(returnUrl));
      			}
      		}
      

      The ClaimsPricipal populates correctly with the details of the user in identities[0] of that collection. How do I mov

      J Offline
      J Offline
      jkirkerx
      wrote on last edited by
      #2

      I'm probably way off on this one. I haven't worked on this subject in over 3 years and I was using MVC, not .Net Core 3.0. I understand the JWT Token and how it works, but thought that was for frameworks like Angular, React, Vue, where you just write the token in a cookie or Local Storage. I use JWT currently and can do OAuth2 with Google in my Angular project. To the best of my knowledge, and I did a lot of research on this subject because I didn't want to use Microsoft Identity and get wrapped up in it's complex authentication methods. But the way I understood Microsoft.Identity was that under the hood, it took care of a lot of stuff in the background. Stuff like OAuth2 into Google, Facebook for alternative methods of sign in credentials other than the typical ones we make. But I'm not clear on it's life cycle and how it reloads Identity on every page cycle. So I used GenericIdentity from System.Security.Principals. I could create a new Identity, store all the stuff I need in it, and it would trickle down to the Controller, View and Razor. But the caveat was that it had a short lifespan of 1 page cycle. So my code had to be wrapped in a custom controller attribute on each page I wanted to be secure. So the user logs in, you generate the JWT token, create a fresh Identity, and then when you redirect to the next page and the Identity is blank and authenticated is false. Code sample to clarify my work around: Controller action with my AdminSecurityCheck attribute

      [HttpGet]
      [AdminSecurityCheck]
      [Route("{userName}/Messages/{page?}/{id?}/{q?}/{s?}")]
      public IActionResult Messages(int? page, int? id, string q, int? s)

      Simple Attribute Code

      [AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
      public class AdminCheckAttribute : ActionFilterAttribute, IActionFilter
      {
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
      var controller = filterContext.Controller as Controller;
      var httpContext = controller.HttpContext;

          Model\_Admin\_Login pResult = SecurityCookies.CookieRead\_Admin\_Login(httpContext);
          if (pResult.AccountName != null)
          {   
              Model\_Admin\_Login model = new Model\_Admin\_Login();
              bool result = EF\_Website\_Users.AdminCheck\_AccountName(pResult.AccountName, ref model);
              if (result)
              {
                  // Program the HttpContext.Current
                  // This will persist for the cu
      
      M 1 Reply Last reply
      0
      • J jkirkerx

        I'm probably way off on this one. I haven't worked on this subject in over 3 years and I was using MVC, not .Net Core 3.0. I understand the JWT Token and how it works, but thought that was for frameworks like Angular, React, Vue, where you just write the token in a cookie or Local Storage. I use JWT currently and can do OAuth2 with Google in my Angular project. To the best of my knowledge, and I did a lot of research on this subject because I didn't want to use Microsoft Identity and get wrapped up in it's complex authentication methods. But the way I understood Microsoft.Identity was that under the hood, it took care of a lot of stuff in the background. Stuff like OAuth2 into Google, Facebook for alternative methods of sign in credentials other than the typical ones we make. But I'm not clear on it's life cycle and how it reloads Identity on every page cycle. So I used GenericIdentity from System.Security.Principals. I could create a new Identity, store all the stuff I need in it, and it would trickle down to the Controller, View and Razor. But the caveat was that it had a short lifespan of 1 page cycle. So my code had to be wrapped in a custom controller attribute on each page I wanted to be secure. So the user logs in, you generate the JWT token, create a fresh Identity, and then when you redirect to the next page and the Identity is blank and authenticated is false. Code sample to clarify my work around: Controller action with my AdminSecurityCheck attribute

        [HttpGet]
        [AdminSecurityCheck]
        [Route("{userName}/Messages/{page?}/{id?}/{q?}/{s?}")]
        public IActionResult Messages(int? page, int? id, string q, int? s)

        Simple Attribute Code

        [AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
        public class AdminCheckAttribute : ActionFilterAttribute, IActionFilter
        {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
        var controller = filterContext.Controller as Controller;
        var httpContext = controller.HttpContext;

            Model\_Admin\_Login pResult = SecurityCookies.CookieRead\_Admin\_Login(httpContext);
            if (pResult.AccountName != null)
            {   
                Model\_Admin\_Login model = new Model\_Admin\_Login();
                bool result = EF\_Website\_Users.AdminCheck\_AccountName(pResult.AccountName, ref model);
                if (result)
                {
                    // Program the HttpContext.Current
                    // This will persist for the cu
        
        M Offline
        M Offline
        Mycroft Holmes
        wrote on last edited by
        #3

        Now that feels like a hack :-D Does JWT not allow you to recycle the credentials via the server by passing them back and forth in the token?

        Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

        J 1 Reply Last reply
        0
        • M Mycroft Holmes

          Now that feels like a hack :-D Does JWT not allow you to recycle the credentials via the server by passing them back and forth in the token?

          Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

          J Offline
          J Offline
          jkirkerx
          wrote on last edited by
          #4

          JWT just generates a unique token, that contains information about the user, and some other parameters such as length of authorized time, and expiration date. So with a token, you can store it in the browsers Local Storage using JavaScript and read it back it using JavaScript. With JavaScript you can get info out of the token, or check to see if the token is expired, and then refresh it or issue a new one. In Angular, you pickup the token, and pass the token in the header sent to the .Net Core V2.2+ API.

          headers: new HttpHeaders({
          "Content-Type": "application/json",
          "Accept": "application/json",
          "Authorization": "Bearer " + tokenGetter
          })

          And then the API will run a service or something called Authorize.

          [HttpGet("GetAdminBrands/{page}/{show}"), Authorize]
          public async Task GetAdminBrands(int page, int show)
          {
          var brand = await _brandsRepository.GetBrands(page, show);
          return brand;
          }

          You set this up in Startup

          services.AddAuthorization(auth =>
          {
          auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
          .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
          .RequireAuthenticatedUser().Build());
          });

          services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddJwtBearer(options =>
          {
          var settings = Configuration.GetSection("Settings");
          var secretKey = settings.GetValue("Auth0:Secret");
          var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
          var authority = settings.GetValue("Auth0:Authority");
          var audience = settings.GetValue("Auth0:Audience");

          options.RequireHttpsMetadata = false;
          options.TokenValidationParameters = new TokenValidationParameters
          {
              ValidateIssuerSigningKey = true,
              ValidateIssuer = true,
              ValidateAudience = true,
              ValidateLifetime = true,
              ValidIssuer = authority,
              ValidAudience = audience,
              IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
          };
          

          });

          So above is what I'm using now, which is Angular wrapped in .Net Core V2.2+ The code I posted earlier was a work around or hack to avoid using Microsoft.Identity in it's full scale, since I just wanted a partial portion of it. What I mean by full scale was having to use such a large chunk of controllers, models and views in which no explanation was really provided in how it works and why. Microsoft.Identity was take it or leave it with

          1 Reply Last reply
          0
          Reply
          • Reply as topic
          Log in to reply
          • Oldest to Newest
          • Newest to Oldest
          • Most Votes


          • Login

          • Don't have an account? Register

          • Login or register to search.
          • First post
            Last post
          0
          • Categories
          • Recent
          • Tags
          • Popular
          • World
          • Users
          • Groups