Click here to Skip to main content
13,454,554 members (55,016 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


15 bookmarked
Posted 8 Sep 2017

ASP.NET Core 2.0 Bearer Authentication

, 8 Sep 2017
Rate this:
Please Sign up or sign in to vote.
How to implement bearer authentication in ASP.NET Core 2.0. Continue reading...


How to implement bearer authentication in ASP.NET Core 2.0.


Create an empty project and update Startup to configure JWT bearer authentication:

public void ConfigureServices(
            IServiceCollection services)
                    .AddJwtBearer(options => {
                        options.TokenValidationParameters = 
                             new TokenValidationParameters
                            ValidateIssuer = true,
                            ValidateAudience = true,
                            ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,

                            ValidIssuer = "Fiver.Security.Bearer",
                            ValidAudience = "Fiver.Security.Bearer",
                            IssuerSigningKey = 
                                  JwtSecurityKey.Create("fiversecret ")


        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env)


Add a class to create signing key:

public static class JwtSecurityKey
        public static SymmetricSecurityKey Create(string secret)
            return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret));

Add an API controller and secure with [Authorize] attribute:

    public class MoviesController : Controller
        public IActionResult Get()
            var dict = new Dictionary<string, string>();

               .ForEach(item => dict.Add(item.Type, item.Value));

            return Ok(dict);


Bearer Tokens (or just Tokens) are commonly used to authenticate Web APIs because they are framework independent, unlike something like Cookie Authentication that is tightly coupled with ASP.NET Core framework.

JSON Web Tokens (JWT) is commonly used to transfer user claims to the server as a base 64 URL encoded value. In order for clients to send a token, they must include an Authorization header with a value of “Bearer [token]”, where [token] is the token value.


When setting up bearer services, you specify how incoming token is validated, e.g., code in the Solution section would validate based on Issuer, Audience and Expiry values.

When configuring authentication, you could hook into lifecycle events too:

options.Events = new JwtBearerEvents
                            OnAuthenticationFailed = context =>
                                Console.WriteLine("OnAuthenticationFailed: " + 
                                return Task.CompletedTask;
                            OnTokenValidated = context =>
                                Console.WriteLine("OnTokenValidated: " + 
                                return Task.CompletedTask;


Usually, tokens will be created by using OAuth framework like IdentityServer 4. However, you could also have an endpoint in your application to create token based on client credentials. Below is a snippet from the sample project that creates a JWT:

// in JwtTokenBuilder.cs
        public JwtToken Build()

            var claims = new List<Claim>
              new Claim(JwtRegisteredClaimNames.Sub, this.subject),
              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            .Union( => new Claim(item.Key, item.Value)));

            var token = new JwtSecurityToken(
                              issuer: this.issuer,
                              audience: this.audience,
                              claims: claims,
                              expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),
                              signingCredentials: new SigningCredentials(

            return new JwtToken(token);

You could have a controller to use this method and create tokens:

    public class TokenController : Controller
        public IActionResult Create([FromBody]LoginInputModel inputModel)
            if (inputModel.Username != "james" && inputModel.Password != "bond")
                return Unauthorized();

            var token = new JwtTokenBuilder()
                                .AddSecurityKey(JwtSecurityKey.Create("fiversecret "))
                                .AddSubject("james bond")
                                .AddClaim("MembershipId", "111")

            return Ok(token.Value);

Now you could make a request to this controller in order to obtain a new token:

Using the token, you could access the API:


You could use jQuery to get tokens and access secure resources. To do so, enable the use of Static Files in Startup:

public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)

Create a controller to return a view:

public class JQueryController : Controller
        public IActionResult Index()
            return View();

Add Index view that uses jQuery (jQuery script lives in folder wwwroot/js):

    <meta name="viewport" content="width=device-width" />
    <title>ASP.NET Core Bearer Auth</title>

    <script src="~/js/jquery.min.js"></script>
        <h1>ASP.NET Core Bearer Auth</h1>

        <input type="button" id="GetToken" value="Get Token" />
        <div id="token"></div>
        <hr />
        <input type="button" id="UseToken" value="Use Token" />
        <div id="result"></div>
        $(function () {
            $("#GetToken").click(function () {
                    type: 'POST',
                    url: '@Url.Action("Create", "Token")',
                    data: JSON.stringify({ "Username": "james", "Password": "bond" }),
                    contentType: "application/json"
                }).done(function (data, statusText, xhdr) {
                }).fail(function (xhdr, statusText, errorText) {

            $("#UseToken").click(function () {
                    method: 'GET',
                    url: '@Url.Action("Get", "Movies")',
                    beforeSend: function (xhdr) {
                           "Authorization", "Bearer " + $("#token").text());
                }).done(function (data, statusText, xhdr) {
                }).fail(function (xhdr, statusText, errorText) {


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Tahir Naushad
Software Developer (Senior)
United Kingdom United Kingdom
Qualified and skilled professional with experience working as a Software Developer, Technical Lead and Architect. I have worked on windows, web and distributed applications using the latest set of technologies within the Microsoft .NET ecosystem. I have lead teams using agile methodologies and trained developers in writing well-designed and maintainable software applications.

Currently focusing on ASP.NET Core, C#, Azure, Angular and Domain Driven Design.

You may also be interested in...

Comments and Discussions

QuestionToken Validation Failed Pin
Member 1175557815-Nov-17 3:05
memberMember 1175557815-Nov-17 3:05 
AnswerRe: Token Validation Failed Pin
Member 1357207612-Dec-17 3:39
memberMember 1357207612-Dec-17 3:39 
QuestionMinor bug Pin
Liran Friedman6-Nov-17 2:29
memberLiran Friedman6-Nov-17 2:29 
QuestionGet User Id in MoviesController Pin
aldari21-Oct-17 22:55
memberaldari21-Oct-17 22:55 
AnswerRe: Get User Id in MoviesController Pin
aldari29-Oct-17 0:19
memberaldari29-Oct-17 0:19 
QuestionRefresh token Pin
black-byte14-Sep-17 0:09
memberblack-byte14-Sep-17 0:09 
AnswerRe: Refresh token Pin
Tahir Naushad14-Sep-17 2:19
memberTahir Naushad14-Sep-17 2:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02-2016 | 2.8.180321.1 | Last Updated 8 Sep 2017
Article Copyright 2017 by Tahir Naushad
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid