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

1

1 Answer 1

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] ");
    
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Make sure that configuration in the startup is the same as the configuration of the token (Audience, Issuer, IssuerSigningKey).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.