Multiple authentication methods in asp.Net core 2.2












0















Is there a way to use JWT bearer authentication AND a custom authentication method in .net core? I want all actions to default to JWT, except in a few cases where I want to use a custom authentication header.










share|improve this question

























  • the issue seems straight forward. Have you looked into the docs? Can you show what you have tried so far and where you were stuck? if you are not sure where to start you can check the official docs here: docs.microsoft.com/en-us/aspnet/core/security/authentication/…

    – Neville Nazerane
    Jan 19 at 0:27
















0















Is there a way to use JWT bearer authentication AND a custom authentication method in .net core? I want all actions to default to JWT, except in a few cases where I want to use a custom authentication header.










share|improve this question

























  • the issue seems straight forward. Have you looked into the docs? Can you show what you have tried so far and where you were stuck? if you are not sure where to start you can check the official docs here: docs.microsoft.com/en-us/aspnet/core/security/authentication/…

    – Neville Nazerane
    Jan 19 at 0:27














0












0








0








Is there a way to use JWT bearer authentication AND a custom authentication method in .net core? I want all actions to default to JWT, except in a few cases where I want to use a custom authentication header.










share|improve this question
















Is there a way to use JWT bearer authentication AND a custom authentication method in .net core? I want all actions to default to JWT, except in a few cases where I want to use a custom authentication header.







authentication asp.net-core .net-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 22 at 14:05







David Derman

















asked Jan 18 at 20:14









David DermanDavid Derman

261213




261213













  • the issue seems straight forward. Have you looked into the docs? Can you show what you have tried so far and where you were stuck? if you are not sure where to start you can check the official docs here: docs.microsoft.com/en-us/aspnet/core/security/authentication/…

    – Neville Nazerane
    Jan 19 at 0:27



















  • the issue seems straight forward. Have you looked into the docs? Can you show what you have tried so far and where you were stuck? if you are not sure where to start you can check the official docs here: docs.microsoft.com/en-us/aspnet/core/security/authentication/…

    – Neville Nazerane
    Jan 19 at 0:27

















the issue seems straight forward. Have you looked into the docs? Can you show what you have tried so far and where you were stuck? if you are not sure where to start you can check the official docs here: docs.microsoft.com/en-us/aspnet/core/security/authentication/…

– Neville Nazerane
Jan 19 at 0:27





the issue seems straight forward. Have you looked into the docs? Can you show what you have tried so far and where you were stuck? if you are not sure where to start you can check the official docs here: docs.microsoft.com/en-us/aspnet/core/security/authentication/…

– Neville Nazerane
Jan 19 at 0:27












1 Answer
1






active

oldest

votes


















0














I finally figured out how to do it. This example uses JWT authentication by default and custom authentication in certain rare cases. Please note, from what I've read, Microsoft seems to discourage writing your own auth. Please use at your own risk.



First, add this code to the startup.cs ConfigureServices method to ensure that authentication gets applied globally.



services.AddMvc(options => 
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})


Then, add this to configure the schemes you wish to use (in our case JWT and Custom).



services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// Jwt Authentication
.AddJwtBearer(options =>
{
options.Audience = ".......";
options.Authority = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_...";
})
// Custom auth
.AddScheme<CustomAuthOptions,
CustomAuthHandler>(CustomAuthOptions.DefaultScheme, options => { });


Next create a class to hold your custom authentication options:



public class CustomAuthOptions : AuthenticationSchemeOptions
{
public const string Scheme = "custom auth";
public const string CustomAuthType = "custom auth type";
}


Finally, add an authentication handler to implement the custom authentication logic.



public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
public CustomAuthHandler(
IOptionsMonitor<CustomAuthOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock) : base(options, logger, encoder, clock)
{
}

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Auth logic goes here
if (!Request.Headers....)
{
return Task.FromResult(AuthenticateResult.Fail("Authentication Failed."));
}

// Create authenticated user
ClaimsPrincipal principal = .... ;

List<ClaimsIdentity> identities =
new List<ClaimsIdentity> {
new ClaimsIdentity(CustomAuthOptions.CustomAuthType)};

AuthenticationTicket ticket =
new AuthenticationTicket(
new ClaimsPrincipal(identities), CustomAuthOptions.Scheme);

return Task.FromResult(AuthenticateResult.Success(ticket));
}
}


Finally, to tie it all together, add an authorize attribute to the actions you wish to use custom authorization on.



[HttpGet]
[Authorize(AuthenticationSchemes = CustomAuthOptions.Scheme)]
public HttpResponseMessage Get()
{
....
}


Now JWT authentication will automatically get applied to all actions, and custom authentication will get added to only the actions with the Authorize attribute set to the custom scheme.



I hope this helps someone.






share|improve this answer

























    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%2f54260837%2fmultiple-authentication-methods-in-asp-net-core-2-2%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I finally figured out how to do it. This example uses JWT authentication by default and custom authentication in certain rare cases. Please note, from what I've read, Microsoft seems to discourage writing your own auth. Please use at your own risk.



    First, add this code to the startup.cs ConfigureServices method to ensure that authentication gets applied globally.



    services.AddMvc(options => 
    {
    var policy = new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
    })


    Then, add this to configure the schemes you wish to use (in our case JWT and Custom).



    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    // Jwt Authentication
    .AddJwtBearer(options =>
    {
    options.Audience = ".......";
    options.Authority = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_...";
    })
    // Custom auth
    .AddScheme<CustomAuthOptions,
    CustomAuthHandler>(CustomAuthOptions.DefaultScheme, options => { });


    Next create a class to hold your custom authentication options:



    public class CustomAuthOptions : AuthenticationSchemeOptions
    {
    public const string Scheme = "custom auth";
    public const string CustomAuthType = "custom auth type";
    }


    Finally, add an authentication handler to implement the custom authentication logic.



    public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
    {
    public CustomAuthHandler(
    IOptionsMonitor<CustomAuthOptions> options,
    ILoggerFactory logger,
    UrlEncoder encoder,
    ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
    // Auth logic goes here
    if (!Request.Headers....)
    {
    return Task.FromResult(AuthenticateResult.Fail("Authentication Failed."));
    }

    // Create authenticated user
    ClaimsPrincipal principal = .... ;

    List<ClaimsIdentity> identities =
    new List<ClaimsIdentity> {
    new ClaimsIdentity(CustomAuthOptions.CustomAuthType)};

    AuthenticationTicket ticket =
    new AuthenticationTicket(
    new ClaimsPrincipal(identities), CustomAuthOptions.Scheme);

    return Task.FromResult(AuthenticateResult.Success(ticket));
    }
    }


    Finally, to tie it all together, add an authorize attribute to the actions you wish to use custom authorization on.



    [HttpGet]
    [Authorize(AuthenticationSchemes = CustomAuthOptions.Scheme)]
    public HttpResponseMessage Get()
    {
    ....
    }


    Now JWT authentication will automatically get applied to all actions, and custom authentication will get added to only the actions with the Authorize attribute set to the custom scheme.



    I hope this helps someone.






    share|improve this answer






























      0














      I finally figured out how to do it. This example uses JWT authentication by default and custom authentication in certain rare cases. Please note, from what I've read, Microsoft seems to discourage writing your own auth. Please use at your own risk.



      First, add this code to the startup.cs ConfigureServices method to ensure that authentication gets applied globally.



      services.AddMvc(options => 
      {
      var policy = new AuthorizationPolicyBuilder()
      .RequireAuthenticatedUser()
      .Build();
      options.Filters.Add(new AuthorizeFilter(policy));
      })


      Then, add this to configure the schemes you wish to use (in our case JWT and Custom).



      services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
      // Jwt Authentication
      .AddJwtBearer(options =>
      {
      options.Audience = ".......";
      options.Authority = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_...";
      })
      // Custom auth
      .AddScheme<CustomAuthOptions,
      CustomAuthHandler>(CustomAuthOptions.DefaultScheme, options => { });


      Next create a class to hold your custom authentication options:



      public class CustomAuthOptions : AuthenticationSchemeOptions
      {
      public const string Scheme = "custom auth";
      public const string CustomAuthType = "custom auth type";
      }


      Finally, add an authentication handler to implement the custom authentication logic.



      public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
      {
      public CustomAuthHandler(
      IOptionsMonitor<CustomAuthOptions> options,
      ILoggerFactory logger,
      UrlEncoder encoder,
      ISystemClock clock) : base(options, logger, encoder, clock)
      {
      }

      protected override Task<AuthenticateResult> HandleAuthenticateAsync()
      {
      // Auth logic goes here
      if (!Request.Headers....)
      {
      return Task.FromResult(AuthenticateResult.Fail("Authentication Failed."));
      }

      // Create authenticated user
      ClaimsPrincipal principal = .... ;

      List<ClaimsIdentity> identities =
      new List<ClaimsIdentity> {
      new ClaimsIdentity(CustomAuthOptions.CustomAuthType)};

      AuthenticationTicket ticket =
      new AuthenticationTicket(
      new ClaimsPrincipal(identities), CustomAuthOptions.Scheme);

      return Task.FromResult(AuthenticateResult.Success(ticket));
      }
      }


      Finally, to tie it all together, add an authorize attribute to the actions you wish to use custom authorization on.



      [HttpGet]
      [Authorize(AuthenticationSchemes = CustomAuthOptions.Scheme)]
      public HttpResponseMessage Get()
      {
      ....
      }


      Now JWT authentication will automatically get applied to all actions, and custom authentication will get added to only the actions with the Authorize attribute set to the custom scheme.



      I hope this helps someone.






      share|improve this answer




























        0












        0








        0







        I finally figured out how to do it. This example uses JWT authentication by default and custom authentication in certain rare cases. Please note, from what I've read, Microsoft seems to discourage writing your own auth. Please use at your own risk.



        First, add this code to the startup.cs ConfigureServices method to ensure that authentication gets applied globally.



        services.AddMvc(options => 
        {
        var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
        })


        Then, add this to configure the schemes you wish to use (in our case JWT and Custom).



        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        // Jwt Authentication
        .AddJwtBearer(options =>
        {
        options.Audience = ".......";
        options.Authority = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_...";
        })
        // Custom auth
        .AddScheme<CustomAuthOptions,
        CustomAuthHandler>(CustomAuthOptions.DefaultScheme, options => { });


        Next create a class to hold your custom authentication options:



        public class CustomAuthOptions : AuthenticationSchemeOptions
        {
        public const string Scheme = "custom auth";
        public const string CustomAuthType = "custom auth type";
        }


        Finally, add an authentication handler to implement the custom authentication logic.



        public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
        {
        public CustomAuthHandler(
        IOptionsMonitor<CustomAuthOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
        // Auth logic goes here
        if (!Request.Headers....)
        {
        return Task.FromResult(AuthenticateResult.Fail("Authentication Failed."));
        }

        // Create authenticated user
        ClaimsPrincipal principal = .... ;

        List<ClaimsIdentity> identities =
        new List<ClaimsIdentity> {
        new ClaimsIdentity(CustomAuthOptions.CustomAuthType)};

        AuthenticationTicket ticket =
        new AuthenticationTicket(
        new ClaimsPrincipal(identities), CustomAuthOptions.Scheme);

        return Task.FromResult(AuthenticateResult.Success(ticket));
        }
        }


        Finally, to tie it all together, add an authorize attribute to the actions you wish to use custom authorization on.



        [HttpGet]
        [Authorize(AuthenticationSchemes = CustomAuthOptions.Scheme)]
        public HttpResponseMessage Get()
        {
        ....
        }


        Now JWT authentication will automatically get applied to all actions, and custom authentication will get added to only the actions with the Authorize attribute set to the custom scheme.



        I hope this helps someone.






        share|improve this answer















        I finally figured out how to do it. This example uses JWT authentication by default and custom authentication in certain rare cases. Please note, from what I've read, Microsoft seems to discourage writing your own auth. Please use at your own risk.



        First, add this code to the startup.cs ConfigureServices method to ensure that authentication gets applied globally.



        services.AddMvc(options => 
        {
        var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
        })


        Then, add this to configure the schemes you wish to use (in our case JWT and Custom).



        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        // Jwt Authentication
        .AddJwtBearer(options =>
        {
        options.Audience = ".......";
        options.Authority = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_...";
        })
        // Custom auth
        .AddScheme<CustomAuthOptions,
        CustomAuthHandler>(CustomAuthOptions.DefaultScheme, options => { });


        Next create a class to hold your custom authentication options:



        public class CustomAuthOptions : AuthenticationSchemeOptions
        {
        public const string Scheme = "custom auth";
        public const string CustomAuthType = "custom auth type";
        }


        Finally, add an authentication handler to implement the custom authentication logic.



        public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
        {
        public CustomAuthHandler(
        IOptionsMonitor<CustomAuthOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
        // Auth logic goes here
        if (!Request.Headers....)
        {
        return Task.FromResult(AuthenticateResult.Fail("Authentication Failed."));
        }

        // Create authenticated user
        ClaimsPrincipal principal = .... ;

        List<ClaimsIdentity> identities =
        new List<ClaimsIdentity> {
        new ClaimsIdentity(CustomAuthOptions.CustomAuthType)};

        AuthenticationTicket ticket =
        new AuthenticationTicket(
        new ClaimsPrincipal(identities), CustomAuthOptions.Scheme);

        return Task.FromResult(AuthenticateResult.Success(ticket));
        }
        }


        Finally, to tie it all together, add an authorize attribute to the actions you wish to use custom authorization on.



        [HttpGet]
        [Authorize(AuthenticationSchemes = CustomAuthOptions.Scheme)]
        public HttpResponseMessage Get()
        {
        ....
        }


        Now JWT authentication will automatically get applied to all actions, and custom authentication will get added to only the actions with the Authorize attribute set to the custom scheme.



        I hope this helps someone.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 22 at 14:08

























        answered Jan 22 at 14:02









        David DermanDavid Derman

        261213




        261213






























            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%2f54260837%2fmultiple-authentication-methods-in-asp-net-core-2-2%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

            Homophylophilia

            Updating UILabel text programmatically using a function

            Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage