Where to store JWT Token in .net core web api?












0















I am using web api for accessing data and I want to authenticate and authorize web api.For that I am using JWT token authentication. But I have no idea where should I store access tokens?



What I want to do?



1)After login store the token



2)if user want to access any method of web api, check the token is valid for this user,if valid then give access.



I know two ways



1)using cookies



2)sql server database



which one is the better way to store tokens from above?










share|improve this question

























  • Can you please explain your use case further. Do you want to enforce authentication on your webapi so that your callers will need to authenticate before calling your controllers and actions or is your webapi making a call to another system that requires your calls to be authenticated? If you are trying to achieve the prior option, you need not worry about that if you are done customizing your middle ware unless you are looking at spinning off multiple instances of your app and you need your sessions shared across (not sure why would you use sessions though)

    – Mpho Shaun Majenge
    Nov 24 '18 at 7:07











  • But if you are asking about how to deliver the token back to your caller upon success authentication, you have two options. using the standard owin middleware to handle authentication using bearer then you can literally return the jwt on your response (the risk lies on your end client to secure the token) or configure the middleware to use cookies authentication and just return the cookie with the header Set cookie then your client can save the cookie and not worry about any other application being able to access its information

    – Mpho Shaun Majenge
    Nov 24 '18 at 7:12











  • why do you think you need to store jwt anywhere?

    – dee zg
    Nov 24 '18 at 7:59











  • for verifying if the user is valid or not by comparing tokens

    – Tejas
    Nov 24 '18 at 9:23
















0















I am using web api for accessing data and I want to authenticate and authorize web api.For that I am using JWT token authentication. But I have no idea where should I store access tokens?



What I want to do?



1)After login store the token



2)if user want to access any method of web api, check the token is valid for this user,if valid then give access.



I know two ways



1)using cookies



2)sql server database



which one is the better way to store tokens from above?










share|improve this question

























  • Can you please explain your use case further. Do you want to enforce authentication on your webapi so that your callers will need to authenticate before calling your controllers and actions or is your webapi making a call to another system that requires your calls to be authenticated? If you are trying to achieve the prior option, you need not worry about that if you are done customizing your middle ware unless you are looking at spinning off multiple instances of your app and you need your sessions shared across (not sure why would you use sessions though)

    – Mpho Shaun Majenge
    Nov 24 '18 at 7:07











  • But if you are asking about how to deliver the token back to your caller upon success authentication, you have two options. using the standard owin middleware to handle authentication using bearer then you can literally return the jwt on your response (the risk lies on your end client to secure the token) or configure the middleware to use cookies authentication and just return the cookie with the header Set cookie then your client can save the cookie and not worry about any other application being able to access its information

    – Mpho Shaun Majenge
    Nov 24 '18 at 7:12











  • why do you think you need to store jwt anywhere?

    – dee zg
    Nov 24 '18 at 7:59











  • for verifying if the user is valid or not by comparing tokens

    – Tejas
    Nov 24 '18 at 9:23














0












0








0








I am using web api for accessing data and I want to authenticate and authorize web api.For that I am using JWT token authentication. But I have no idea where should I store access tokens?



What I want to do?



1)After login store the token



2)if user want to access any method of web api, check the token is valid for this user,if valid then give access.



I know two ways



1)using cookies



2)sql server database



which one is the better way to store tokens from above?










share|improve this question
















I am using web api for accessing data and I want to authenticate and authorize web api.For that I am using JWT token authentication. But I have no idea where should I store access tokens?



What I want to do?



1)After login store the token



2)if user want to access any method of web api, check the token is valid for this user,if valid then give access.



I know two ways



1)using cookies



2)sql server database



which one is the better way to store tokens from above?







api authentication jwt






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 7:12







Tejas

















asked Nov 24 '18 at 7:00









TejasTejas

308




308













  • Can you please explain your use case further. Do you want to enforce authentication on your webapi so that your callers will need to authenticate before calling your controllers and actions or is your webapi making a call to another system that requires your calls to be authenticated? If you are trying to achieve the prior option, you need not worry about that if you are done customizing your middle ware unless you are looking at spinning off multiple instances of your app and you need your sessions shared across (not sure why would you use sessions though)

    – Mpho Shaun Majenge
    Nov 24 '18 at 7:07











  • But if you are asking about how to deliver the token back to your caller upon success authentication, you have two options. using the standard owin middleware to handle authentication using bearer then you can literally return the jwt on your response (the risk lies on your end client to secure the token) or configure the middleware to use cookies authentication and just return the cookie with the header Set cookie then your client can save the cookie and not worry about any other application being able to access its information

    – Mpho Shaun Majenge
    Nov 24 '18 at 7:12











  • why do you think you need to store jwt anywhere?

    – dee zg
    Nov 24 '18 at 7:59











  • for verifying if the user is valid or not by comparing tokens

    – Tejas
    Nov 24 '18 at 9:23



















  • Can you please explain your use case further. Do you want to enforce authentication on your webapi so that your callers will need to authenticate before calling your controllers and actions or is your webapi making a call to another system that requires your calls to be authenticated? If you are trying to achieve the prior option, you need not worry about that if you are done customizing your middle ware unless you are looking at spinning off multiple instances of your app and you need your sessions shared across (not sure why would you use sessions though)

    – Mpho Shaun Majenge
    Nov 24 '18 at 7:07











  • But if you are asking about how to deliver the token back to your caller upon success authentication, you have two options. using the standard owin middleware to handle authentication using bearer then you can literally return the jwt on your response (the risk lies on your end client to secure the token) or configure the middleware to use cookies authentication and just return the cookie with the header Set cookie then your client can save the cookie and not worry about any other application being able to access its information

    – Mpho Shaun Majenge
    Nov 24 '18 at 7:12











  • why do you think you need to store jwt anywhere?

    – dee zg
    Nov 24 '18 at 7:59











  • for verifying if the user is valid or not by comparing tokens

    – Tejas
    Nov 24 '18 at 9:23

















Can you please explain your use case further. Do you want to enforce authentication on your webapi so that your callers will need to authenticate before calling your controllers and actions or is your webapi making a call to another system that requires your calls to be authenticated? If you are trying to achieve the prior option, you need not worry about that if you are done customizing your middle ware unless you are looking at spinning off multiple instances of your app and you need your sessions shared across (not sure why would you use sessions though)

– Mpho Shaun Majenge
Nov 24 '18 at 7:07





Can you please explain your use case further. Do you want to enforce authentication on your webapi so that your callers will need to authenticate before calling your controllers and actions or is your webapi making a call to another system that requires your calls to be authenticated? If you are trying to achieve the prior option, you need not worry about that if you are done customizing your middle ware unless you are looking at spinning off multiple instances of your app and you need your sessions shared across (not sure why would you use sessions though)

– Mpho Shaun Majenge
Nov 24 '18 at 7:07













But if you are asking about how to deliver the token back to your caller upon success authentication, you have two options. using the standard owin middleware to handle authentication using bearer then you can literally return the jwt on your response (the risk lies on your end client to secure the token) or configure the middleware to use cookies authentication and just return the cookie with the header Set cookie then your client can save the cookie and not worry about any other application being able to access its information

– Mpho Shaun Majenge
Nov 24 '18 at 7:12





But if you are asking about how to deliver the token back to your caller upon success authentication, you have two options. using the standard owin middleware to handle authentication using bearer then you can literally return the jwt on your response (the risk lies on your end client to secure the token) or configure the middleware to use cookies authentication and just return the cookie with the header Set cookie then your client can save the cookie and not worry about any other application being able to access its information

– Mpho Shaun Majenge
Nov 24 '18 at 7:12













why do you think you need to store jwt anywhere?

– dee zg
Nov 24 '18 at 7:59





why do you think you need to store jwt anywhere?

– dee zg
Nov 24 '18 at 7:59













for verifying if the user is valid or not by comparing tokens

– Tejas
Nov 24 '18 at 9:23





for verifying if the user is valid or not by comparing tokens

– Tejas
Nov 24 '18 at 9:23












2 Answers
2






active

oldest

votes


















0














I'm not familiar with storing your users tokens on your back end app, I'll quickly check how does that work however if you are using dotnet core to authenticate with either cookies or with jwt, from my understanding and experience you need not store anything on your side.



If you are using cookies then you just need to to configure middleware to validate the validity of a cookie if it comes present in the users / consumer's headers and if not available or has expired or can't resolve it, you simply reject the request and the user won't even hit any of your protected Controllers and actions. Here's a very simplified approach with cookies.(I'm still in Development with it and haven't tested in production but it works perfectly fine locally for now using JS client and Postman)



    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "yourCookieName";
options.Cookie.SameSite = SameSiteMode.None;//its recommended but you can set it to any of the other 3 depending on your reqirements
options.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
{
OnRedirectToLogin = redirectContext =>//this will be called if an unauthorized connection comes and you can do something similar to this or more
{
redirectContext.HttpContext.Response.StatusCode = 401;
return Task.CompletedTask;
},
OnValidatePrincipal = context => //if a call comes with a valid cookie, you can use this to do validations. in there you have access to the request and http context so you should have enough to work with
{
var userPrincipal = context.Principal;//I'm not doing anything with this right now but I could for instance validate if the user has the right privileges like claims etc
return Task.CompletedTask;
}
};
});


Obviously this would be placed or called in the ConfigureServices method of your startup to register authentication



and then in your Configure method of your Startup, you'd hookup Authentication like



app.UseAuthentication();


before



app.UseMvc()





share|improve this answer































    0














    Alternatively, if you just wanted to authenticate using JWT the implementation would be slightly different



            services.AddAuthentication(options =>
    {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
    options.Events = new JwtBearerEvents
    {
    OnTokenValidated = context =>
    {

    var user = context.Principal.Identity.Name;
    //Grab the http context user and validate the things you need to
    //if you are not satisfied with the validation fail the request using the below commented code
    //context.Fail("Unauthorized");

    //otherwise succeed the request
    return Task.CompletedTask;
    }
    };
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = new SymmetricSecurityKey("MyVeryStrongKeyHiddenFromAnyone"),
    ValidateIssuer = false,
    ValidateAudience = false

    };
    });


    still applying use authentication before use MVC.



    [Please note these are very simplified examples and you may need to tighten your security more and implement best practices such as using strong keys, loading configs perhaps from the environment etc]



    Then the actual authentication action, say perhaps in AuthenticationController would be something like



    [Route("api/[controller]")]
    [Authorize]
    public class AuthenticationController : Controller
    {


    [HttpPost("authenticate")]
    [AllowAnonymous]
    public async Task<IActionResult> AuthenticateAsync([FromBody]LoginRequest loginRequest)
    {
    //LoginRequest may have any number of fields expected .i.e. username and password

    //validate user credentials and if they fail return
    //return Unauthorized();

    var claimsIdentity = new ClaimsIdentity(new Claim
    {
    //add relevant user claims if any
    }, "Cookies");

    var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
    await Request.HttpContext.SignInAsync("Cookies", claimsPrincipal);
    return Ok();
    }
    }
    }


    in this instance I'm using cookies so I'm returning an HTTP result with Set Cookie. If I was using JWT, I'd return something like



    [HttpPost("authenticate")]
    public IActionResult Authenticate([FromBody]LoginRequest loginRequest)
    {

    //validate user credentials and if they validation failed return a similar response to below
    //return NotFound();

    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes("MySecurelyInjectedAsymKey");
    var tokenDescriptor = new SecurityTokenDescriptor
    {
    Subject = new ClaimsIdentity(new Claim
    {
    //add my users claims etc
    }),
    Expires = DateTime.UtcNow.AddDays(1),//configure your token lifespan and needed
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey("MyVerySecureSecreteKey"), SecurityAlgorithms.HmacSha256Signature),
    Issuer = "YourOrganizationOrUniqueKey",
    IssuedAt = DateTime.UtcNow
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);
    var cookieOptions = new CookieOptions();
    cookieOptions.Expires = DateTimeOffset.UtcNow.AddHours(4);//you can set this to a suitable timeframe for your situation
    cookieOptions.Domain = Request.Host.Value;
    cookieOptions.Path = "/";
    Response.Cookies.Append("jwt", tokenString, cookieOptions);
    return Ok();

    }


    I hope these helps






    share|improve this answer


























    • Thanks for this solution but what is the IUserDomain here...?

      – Tejas
      Nov 24 '18 at 9:44











    • No problem, don't worry about them, those are basically just service orchestrations that help to do certain things like going to the database to validate users credentials or calling an internal authentication system. But do you get the basic that you don't really need to use database for storing tokens

      – Mpho Shaun Majenge
      Nov 24 '18 at 11:36











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455939%2fwhere-to-store-jwt-token-in-net-core-web-api%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I'm not familiar with storing your users tokens on your back end app, I'll quickly check how does that work however if you are using dotnet core to authenticate with either cookies or with jwt, from my understanding and experience you need not store anything on your side.



    If you are using cookies then you just need to to configure middleware to validate the validity of a cookie if it comes present in the users / consumer's headers and if not available or has expired or can't resolve it, you simply reject the request and the user won't even hit any of your protected Controllers and actions. Here's a very simplified approach with cookies.(I'm still in Development with it and haven't tested in production but it works perfectly fine locally for now using JS client and Postman)



        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
    options.Cookie.Name = "yourCookieName";
    options.Cookie.SameSite = SameSiteMode.None;//its recommended but you can set it to any of the other 3 depending on your reqirements
    options.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
    {
    OnRedirectToLogin = redirectContext =>//this will be called if an unauthorized connection comes and you can do something similar to this or more
    {
    redirectContext.HttpContext.Response.StatusCode = 401;
    return Task.CompletedTask;
    },
    OnValidatePrincipal = context => //if a call comes with a valid cookie, you can use this to do validations. in there you have access to the request and http context so you should have enough to work with
    {
    var userPrincipal = context.Principal;//I'm not doing anything with this right now but I could for instance validate if the user has the right privileges like claims etc
    return Task.CompletedTask;
    }
    };
    });


    Obviously this would be placed or called in the ConfigureServices method of your startup to register authentication



    and then in your Configure method of your Startup, you'd hookup Authentication like



    app.UseAuthentication();


    before



    app.UseMvc()





    share|improve this answer




























      0














      I'm not familiar with storing your users tokens on your back end app, I'll quickly check how does that work however if you are using dotnet core to authenticate with either cookies or with jwt, from my understanding and experience you need not store anything on your side.



      If you are using cookies then you just need to to configure middleware to validate the validity of a cookie if it comes present in the users / consumer's headers and if not available or has expired or can't resolve it, you simply reject the request and the user won't even hit any of your protected Controllers and actions. Here's a very simplified approach with cookies.(I'm still in Development with it and haven't tested in production but it works perfectly fine locally for now using JS client and Postman)



          services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddCookie(options =>
      {
      options.Cookie.Name = "yourCookieName";
      options.Cookie.SameSite = SameSiteMode.None;//its recommended but you can set it to any of the other 3 depending on your reqirements
      options.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
      {
      OnRedirectToLogin = redirectContext =>//this will be called if an unauthorized connection comes and you can do something similar to this or more
      {
      redirectContext.HttpContext.Response.StatusCode = 401;
      return Task.CompletedTask;
      },
      OnValidatePrincipal = context => //if a call comes with a valid cookie, you can use this to do validations. in there you have access to the request and http context so you should have enough to work with
      {
      var userPrincipal = context.Principal;//I'm not doing anything with this right now but I could for instance validate if the user has the right privileges like claims etc
      return Task.CompletedTask;
      }
      };
      });


      Obviously this would be placed or called in the ConfigureServices method of your startup to register authentication



      and then in your Configure method of your Startup, you'd hookup Authentication like



      app.UseAuthentication();


      before



      app.UseMvc()





      share|improve this answer


























        0












        0








        0







        I'm not familiar with storing your users tokens on your back end app, I'll quickly check how does that work however if you are using dotnet core to authenticate with either cookies or with jwt, from my understanding and experience you need not store anything on your side.



        If you are using cookies then you just need to to configure middleware to validate the validity of a cookie if it comes present in the users / consumer's headers and if not available or has expired or can't resolve it, you simply reject the request and the user won't even hit any of your protected Controllers and actions. Here's a very simplified approach with cookies.(I'm still in Development with it and haven't tested in production but it works perfectly fine locally for now using JS client and Postman)



            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
        options.Cookie.Name = "yourCookieName";
        options.Cookie.SameSite = SameSiteMode.None;//its recommended but you can set it to any of the other 3 depending on your reqirements
        options.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
        {
        OnRedirectToLogin = redirectContext =>//this will be called if an unauthorized connection comes and you can do something similar to this or more
        {
        redirectContext.HttpContext.Response.StatusCode = 401;
        return Task.CompletedTask;
        },
        OnValidatePrincipal = context => //if a call comes with a valid cookie, you can use this to do validations. in there you have access to the request and http context so you should have enough to work with
        {
        var userPrincipal = context.Principal;//I'm not doing anything with this right now but I could for instance validate if the user has the right privileges like claims etc
        return Task.CompletedTask;
        }
        };
        });


        Obviously this would be placed or called in the ConfigureServices method of your startup to register authentication



        and then in your Configure method of your Startup, you'd hookup Authentication like



        app.UseAuthentication();


        before



        app.UseMvc()





        share|improve this answer













        I'm not familiar with storing your users tokens on your back end app, I'll quickly check how does that work however if you are using dotnet core to authenticate with either cookies or with jwt, from my understanding and experience you need not store anything on your side.



        If you are using cookies then you just need to to configure middleware to validate the validity of a cookie if it comes present in the users / consumer's headers and if not available or has expired or can't resolve it, you simply reject the request and the user won't even hit any of your protected Controllers and actions. Here's a very simplified approach with cookies.(I'm still in Development with it and haven't tested in production but it works perfectly fine locally for now using JS client and Postman)



            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
        options.Cookie.Name = "yourCookieName";
        options.Cookie.SameSite = SameSiteMode.None;//its recommended but you can set it to any of the other 3 depending on your reqirements
        options.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
        {
        OnRedirectToLogin = redirectContext =>//this will be called if an unauthorized connection comes and you can do something similar to this or more
        {
        redirectContext.HttpContext.Response.StatusCode = 401;
        return Task.CompletedTask;
        },
        OnValidatePrincipal = context => //if a call comes with a valid cookie, you can use this to do validations. in there you have access to the request and http context so you should have enough to work with
        {
        var userPrincipal = context.Principal;//I'm not doing anything with this right now but I could for instance validate if the user has the right privileges like claims etc
        return Task.CompletedTask;
        }
        };
        });


        Obviously this would be placed or called in the ConfigureServices method of your startup to register authentication



        and then in your Configure method of your Startup, you'd hookup Authentication like



        app.UseAuthentication();


        before



        app.UseMvc()






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 7:43









        Mpho Shaun MajengeMpho Shaun Majenge

        1996




        1996

























            0














            Alternatively, if you just wanted to authenticate using JWT the implementation would be slightly different



                    services.AddAuthentication(options =>
            {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
            options.Events = new JwtBearerEvents
            {
            OnTokenValidated = context =>
            {

            var user = context.Principal.Identity.Name;
            //Grab the http context user and validate the things you need to
            //if you are not satisfied with the validation fail the request using the below commented code
            //context.Fail("Unauthorized");

            //otherwise succeed the request
            return Task.CompletedTask;
            }
            };
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey("MyVeryStrongKeyHiddenFromAnyone"),
            ValidateIssuer = false,
            ValidateAudience = false

            };
            });


            still applying use authentication before use MVC.



            [Please note these are very simplified examples and you may need to tighten your security more and implement best practices such as using strong keys, loading configs perhaps from the environment etc]



            Then the actual authentication action, say perhaps in AuthenticationController would be something like



            [Route("api/[controller]")]
            [Authorize]
            public class AuthenticationController : Controller
            {


            [HttpPost("authenticate")]
            [AllowAnonymous]
            public async Task<IActionResult> AuthenticateAsync([FromBody]LoginRequest loginRequest)
            {
            //LoginRequest may have any number of fields expected .i.e. username and password

            //validate user credentials and if they fail return
            //return Unauthorized();

            var claimsIdentity = new ClaimsIdentity(new Claim
            {
            //add relevant user claims if any
            }, "Cookies");

            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            await Request.HttpContext.SignInAsync("Cookies", claimsPrincipal);
            return Ok();
            }
            }
            }


            in this instance I'm using cookies so I'm returning an HTTP result with Set Cookie. If I was using JWT, I'd return something like



            [HttpPost("authenticate")]
            public IActionResult Authenticate([FromBody]LoginRequest loginRequest)
            {

            //validate user credentials and if they validation failed return a similar response to below
            //return NotFound();

            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("MySecurelyInjectedAsymKey");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
            Subject = new ClaimsIdentity(new Claim
            {
            //add my users claims etc
            }),
            Expires = DateTime.UtcNow.AddDays(1),//configure your token lifespan and needed
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey("MyVerySecureSecreteKey"), SecurityAlgorithms.HmacSha256Signature),
            Issuer = "YourOrganizationOrUniqueKey",
            IssuedAt = DateTime.UtcNow
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            var cookieOptions = new CookieOptions();
            cookieOptions.Expires = DateTimeOffset.UtcNow.AddHours(4);//you can set this to a suitable timeframe for your situation
            cookieOptions.Domain = Request.Host.Value;
            cookieOptions.Path = "/";
            Response.Cookies.Append("jwt", tokenString, cookieOptions);
            return Ok();

            }


            I hope these helps






            share|improve this answer


























            • Thanks for this solution but what is the IUserDomain here...?

              – Tejas
              Nov 24 '18 at 9:44











            • No problem, don't worry about them, those are basically just service orchestrations that help to do certain things like going to the database to validate users credentials or calling an internal authentication system. But do you get the basic that you don't really need to use database for storing tokens

              – Mpho Shaun Majenge
              Nov 24 '18 at 11:36
















            0














            Alternatively, if you just wanted to authenticate using JWT the implementation would be slightly different



                    services.AddAuthentication(options =>
            {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
            options.Events = new JwtBearerEvents
            {
            OnTokenValidated = context =>
            {

            var user = context.Principal.Identity.Name;
            //Grab the http context user and validate the things you need to
            //if you are not satisfied with the validation fail the request using the below commented code
            //context.Fail("Unauthorized");

            //otherwise succeed the request
            return Task.CompletedTask;
            }
            };
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey("MyVeryStrongKeyHiddenFromAnyone"),
            ValidateIssuer = false,
            ValidateAudience = false

            };
            });


            still applying use authentication before use MVC.



            [Please note these are very simplified examples and you may need to tighten your security more and implement best practices such as using strong keys, loading configs perhaps from the environment etc]



            Then the actual authentication action, say perhaps in AuthenticationController would be something like



            [Route("api/[controller]")]
            [Authorize]
            public class AuthenticationController : Controller
            {


            [HttpPost("authenticate")]
            [AllowAnonymous]
            public async Task<IActionResult> AuthenticateAsync([FromBody]LoginRequest loginRequest)
            {
            //LoginRequest may have any number of fields expected .i.e. username and password

            //validate user credentials and if they fail return
            //return Unauthorized();

            var claimsIdentity = new ClaimsIdentity(new Claim
            {
            //add relevant user claims if any
            }, "Cookies");

            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            await Request.HttpContext.SignInAsync("Cookies", claimsPrincipal);
            return Ok();
            }
            }
            }


            in this instance I'm using cookies so I'm returning an HTTP result with Set Cookie. If I was using JWT, I'd return something like



            [HttpPost("authenticate")]
            public IActionResult Authenticate([FromBody]LoginRequest loginRequest)
            {

            //validate user credentials and if they validation failed return a similar response to below
            //return NotFound();

            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("MySecurelyInjectedAsymKey");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
            Subject = new ClaimsIdentity(new Claim
            {
            //add my users claims etc
            }),
            Expires = DateTime.UtcNow.AddDays(1),//configure your token lifespan and needed
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey("MyVerySecureSecreteKey"), SecurityAlgorithms.HmacSha256Signature),
            Issuer = "YourOrganizationOrUniqueKey",
            IssuedAt = DateTime.UtcNow
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            var cookieOptions = new CookieOptions();
            cookieOptions.Expires = DateTimeOffset.UtcNow.AddHours(4);//you can set this to a suitable timeframe for your situation
            cookieOptions.Domain = Request.Host.Value;
            cookieOptions.Path = "/";
            Response.Cookies.Append("jwt", tokenString, cookieOptions);
            return Ok();

            }


            I hope these helps






            share|improve this answer


























            • Thanks for this solution but what is the IUserDomain here...?

              – Tejas
              Nov 24 '18 at 9:44











            • No problem, don't worry about them, those are basically just service orchestrations that help to do certain things like going to the database to validate users credentials or calling an internal authentication system. But do you get the basic that you don't really need to use database for storing tokens

              – Mpho Shaun Majenge
              Nov 24 '18 at 11:36














            0












            0








            0







            Alternatively, if you just wanted to authenticate using JWT the implementation would be slightly different



                    services.AddAuthentication(options =>
            {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
            options.Events = new JwtBearerEvents
            {
            OnTokenValidated = context =>
            {

            var user = context.Principal.Identity.Name;
            //Grab the http context user and validate the things you need to
            //if you are not satisfied with the validation fail the request using the below commented code
            //context.Fail("Unauthorized");

            //otherwise succeed the request
            return Task.CompletedTask;
            }
            };
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey("MyVeryStrongKeyHiddenFromAnyone"),
            ValidateIssuer = false,
            ValidateAudience = false

            };
            });


            still applying use authentication before use MVC.



            [Please note these are very simplified examples and you may need to tighten your security more and implement best practices such as using strong keys, loading configs perhaps from the environment etc]



            Then the actual authentication action, say perhaps in AuthenticationController would be something like



            [Route("api/[controller]")]
            [Authorize]
            public class AuthenticationController : Controller
            {


            [HttpPost("authenticate")]
            [AllowAnonymous]
            public async Task<IActionResult> AuthenticateAsync([FromBody]LoginRequest loginRequest)
            {
            //LoginRequest may have any number of fields expected .i.e. username and password

            //validate user credentials and if they fail return
            //return Unauthorized();

            var claimsIdentity = new ClaimsIdentity(new Claim
            {
            //add relevant user claims if any
            }, "Cookies");

            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            await Request.HttpContext.SignInAsync("Cookies", claimsPrincipal);
            return Ok();
            }
            }
            }


            in this instance I'm using cookies so I'm returning an HTTP result with Set Cookie. If I was using JWT, I'd return something like



            [HttpPost("authenticate")]
            public IActionResult Authenticate([FromBody]LoginRequest loginRequest)
            {

            //validate user credentials and if they validation failed return a similar response to below
            //return NotFound();

            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("MySecurelyInjectedAsymKey");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
            Subject = new ClaimsIdentity(new Claim
            {
            //add my users claims etc
            }),
            Expires = DateTime.UtcNow.AddDays(1),//configure your token lifespan and needed
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey("MyVerySecureSecreteKey"), SecurityAlgorithms.HmacSha256Signature),
            Issuer = "YourOrganizationOrUniqueKey",
            IssuedAt = DateTime.UtcNow
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            var cookieOptions = new CookieOptions();
            cookieOptions.Expires = DateTimeOffset.UtcNow.AddHours(4);//you can set this to a suitable timeframe for your situation
            cookieOptions.Domain = Request.Host.Value;
            cookieOptions.Path = "/";
            Response.Cookies.Append("jwt", tokenString, cookieOptions);
            return Ok();

            }


            I hope these helps






            share|improve this answer















            Alternatively, if you just wanted to authenticate using JWT the implementation would be slightly different



                    services.AddAuthentication(options =>
            {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
            options.Events = new JwtBearerEvents
            {
            OnTokenValidated = context =>
            {

            var user = context.Principal.Identity.Name;
            //Grab the http context user and validate the things you need to
            //if you are not satisfied with the validation fail the request using the below commented code
            //context.Fail("Unauthorized");

            //otherwise succeed the request
            return Task.CompletedTask;
            }
            };
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey("MyVeryStrongKeyHiddenFromAnyone"),
            ValidateIssuer = false,
            ValidateAudience = false

            };
            });


            still applying use authentication before use MVC.



            [Please note these are very simplified examples and you may need to tighten your security more and implement best practices such as using strong keys, loading configs perhaps from the environment etc]



            Then the actual authentication action, say perhaps in AuthenticationController would be something like



            [Route("api/[controller]")]
            [Authorize]
            public class AuthenticationController : Controller
            {


            [HttpPost("authenticate")]
            [AllowAnonymous]
            public async Task<IActionResult> AuthenticateAsync([FromBody]LoginRequest loginRequest)
            {
            //LoginRequest may have any number of fields expected .i.e. username and password

            //validate user credentials and if they fail return
            //return Unauthorized();

            var claimsIdentity = new ClaimsIdentity(new Claim
            {
            //add relevant user claims if any
            }, "Cookies");

            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            await Request.HttpContext.SignInAsync("Cookies", claimsPrincipal);
            return Ok();
            }
            }
            }


            in this instance I'm using cookies so I'm returning an HTTP result with Set Cookie. If I was using JWT, I'd return something like



            [HttpPost("authenticate")]
            public IActionResult Authenticate([FromBody]LoginRequest loginRequest)
            {

            //validate user credentials and if they validation failed return a similar response to below
            //return NotFound();

            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("MySecurelyInjectedAsymKey");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
            Subject = new ClaimsIdentity(new Claim
            {
            //add my users claims etc
            }),
            Expires = DateTime.UtcNow.AddDays(1),//configure your token lifespan and needed
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey("MyVerySecureSecreteKey"), SecurityAlgorithms.HmacSha256Signature),
            Issuer = "YourOrganizationOrUniqueKey",
            IssuedAt = DateTime.UtcNow
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            var cookieOptions = new CookieOptions();
            cookieOptions.Expires = DateTimeOffset.UtcNow.AddHours(4);//you can set this to a suitable timeframe for your situation
            cookieOptions.Domain = Request.Host.Value;
            cookieOptions.Path = "/";
            Response.Cookies.Append("jwt", tokenString, cookieOptions);
            return Ok();

            }


            I hope these helps







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 24 '18 at 11:32

























            answered Nov 24 '18 at 7:57









            Mpho Shaun MajengeMpho Shaun Majenge

            1996




            1996













            • Thanks for this solution but what is the IUserDomain here...?

              – Tejas
              Nov 24 '18 at 9:44











            • No problem, don't worry about them, those are basically just service orchestrations that help to do certain things like going to the database to validate users credentials or calling an internal authentication system. But do you get the basic that you don't really need to use database for storing tokens

              – Mpho Shaun Majenge
              Nov 24 '18 at 11:36



















            • Thanks for this solution but what is the IUserDomain here...?

              – Tejas
              Nov 24 '18 at 9:44











            • No problem, don't worry about them, those are basically just service orchestrations that help to do certain things like going to the database to validate users credentials or calling an internal authentication system. But do you get the basic that you don't really need to use database for storing tokens

              – Mpho Shaun Majenge
              Nov 24 '18 at 11:36

















            Thanks for this solution but what is the IUserDomain here...?

            – Tejas
            Nov 24 '18 at 9:44





            Thanks for this solution but what is the IUserDomain here...?

            – Tejas
            Nov 24 '18 at 9:44













            No problem, don't worry about them, those are basically just service orchestrations that help to do certain things like going to the database to validate users credentials or calling an internal authentication system. But do you get the basic that you don't really need to use database for storing tokens

            – Mpho Shaun Majenge
            Nov 24 '18 at 11:36





            No problem, don't worry about them, those are basically just service orchestrations that help to do certain things like going to the database to validate users credentials or calling an internal authentication system. But do you get the basic that you don't really need to use database for storing tokens

            – Mpho Shaun Majenge
            Nov 24 '18 at 11:36


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455939%2fwhere-to-store-jwt-token-in-net-core-web-api%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Fotorealismo