0

I've developed my ASP.NET Core 5 MVC application with "Individual Login". Registering and logging within the app works fine.

Now I want to log in to my MVC web application with an API for my Xamarin App. From what I've read "JWT" should be used. I want to use as much "standard" in the backend as possible, ideally using standard APIs.

Unfortunately, all the sites I've tried could not help me (solution broken, non-existing urls,....).

Could somebody please post me a working tutorial or an example for the backend please.

Thanks, Jeppen

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jeppen
  • 414
  • 5
  • 12
  • This helped a lot https://stackoverflow.com/questions/40281050/jwt-authentication-for-asp-net-web-api – Jeppen Dec 28 '20 at 16:44

1 Answers1

1

From api, you can configure the jwt authentication as this.

  1. In Startup

     public void ConfigureServices(IServiceCollection services)
     {
         services.AddAuthentication(x =>
         {
             x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
             x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
         })
         .AddJwtBearer(o =>
         {
    
             o.TokenValidationParameters = new TokenValidationParameters
             {
                 NameClaimType = JwtClaimTypes.Name,
                 RoleClaimType = JwtClaimTypes.Role,
    
                 //The previous three items are required
                 ValidIssuer = "http://localhost:5000",
                 ValidAudience = "api",
                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("this is a long key"))
    
                 /***********************************default TokenValidationParameters parameter***********************************/
                 // RequireSignedTokens = true,
                 // SaveSigninToken = false,
                 // ValidateActor = false,
    
             };
    
         });
         services.AddControllers();
     }
    
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
     {
         //...
         app.UseRouting();
         app.UseAuthentication();
         app.UseAuthorization();
         //...
     }
    
  2. Apply for a token, generate a string token in the action.

     public IActionResult Authenticate()
     {
    
         var tokenHandler = new JwtSecurityTokenHandler();
         var key = Encoding.ASCII.GetBytes("this is a long key");
         var authTime = DateTime.UtcNow;
         var expiresAt = authTime.AddDays(7);
         var tokenDescriptor = new SecurityTokenDescriptor
         {
             Subject = new ClaimsIdentity(new Claim[]
             {
                 new Claim(JwtClaimTypes.Audience,"api"),
                 new Claim(JwtClaimTypes.Issuer,"http://localhost:5000"),
                 new Claim(JwtClaimTypes.Id, "10"),
                 new Claim(JwtClaimTypes.Name, "my name"),
                 new Claim(JwtClaimTypes.Email, "email"),
             }),
             Expires = expiresAt,
             SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
         };
         var token = tokenHandler.CreateToken(tokenDescriptor);
         var tokenString = tokenHandler.WriteToken(token);
    
         return Ok(tokenString);
     }
    
  3. Xamarin App receives token and save it. When Xamarin App access the authorized resource, it can carray this token with this header.

         var client = new HttpClient();
         var token = client.GetAsync("[url that get the token] ");
    
         client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
         client.GetAsync("[url that get the authorized resource] ");
    
Karney.
  • 4,803
  • 2
  • 7
  • 11
  • Thank you very much, the first time my app is creating a token. But when I run my site, I get a blank page. In the developper tools, I get a 401 Unauthorized. Do you have any idea? – Jeppen Dec 29 '20 at 13:41
  • 1
    Make sure that configuration in the startup is the same as the configuration of the token (Audience, Issuer, IssuerSigningKey). – Karney. Dec 30 '20 at 01:40