Click here to Skip to main content
15,114,470 members
Articles / Web Development / ASP.NET / ASP.NET Core
Technical Blog
Posted 8 Sep 2017

Tagged as

Stats

66.5K views
17 bookmarked

ASP.NET Core 2.0 Bearer Authentication

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
8 Sep 2017CPOL1 min read
How to implement bearer authentication in ASP.NET Core 2.0. Continue reading...

Problem

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

Solution

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

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .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 ")
                        };
                    });

            services.AddMvc();
        }

        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env)
        {
            app.UseAuthentication();

            app.UseMvcWithDefaultRoute();
        }

Add a class to create signing key:

C#
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:

C#
[Authorize]
    [Route("movies")]
    public class MoviesController : Controller
    {
        [HttpGet]
        public IActionResult Get()
        {
            var dict = new Dictionary<string, string>();

            HttpContext.User.Claims.ToList()
               .ForEach(item => dict.Add(item.Type, item.Value));

            return Ok(dict);
        }
    }

Discussion

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.

Middleware

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:

C#
options.Events = new JwtBearerEvents
                        {
                            OnAuthenticationFailed = context =>
                            {
                                Console.WriteLine("OnAuthenticationFailed: " + 
                                    context.Exception.Message);
                                return Task.CompletedTask;
                            },
                            OnTokenValidated = context =>
                            {
                                Console.WriteLine("OnTokenValidated: " + 
                                    context.SecurityToken);
                                return Task.CompletedTask;
                            }
                        };

Token

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:

C#
// in JwtTokenBuilder.cs
        public JwtToken Build()
        {
            EnsureArguments();

            var claims = new List<Claim>
            {
              new Claim(JwtRegisteredClaimNames.Sub, this.subject),
              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            }
            .Union(this.claims.Select(item => 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(
                                        		this.securityKey,
                                        		SecurityAlgorithms.HmacSha256));

            return new JwtToken(token);
        }

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

C#
[Route("token")]
    [AllowAnonymous]
    public class TokenController : Controller
    {
        [HttpPost]
        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")
                                .AddIssuer("Fiver.Security.Bearer")
                                .AddAudience("Fiver.Security.Bearer")
                                .AddClaim("MembershipId", "111")
                                .AddExpiry(1)
                                .Build();

            return Ok(token.Value);
        }
    }

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

Image 1

Using the token, you could access the API:

Image 2

jQuery

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

C#
public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseStaticFiles();
            ...
        }

Create a controller to return a view:

C#
public class JQueryController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

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

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

    <script src="~/js/jquery.min.js"></script>
</head>
<body>
    <div>
        <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>
    </div>
    <script>
        $(function () {
            $("#GetToken").click(function () {
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Create", "Token")',
                    data: JSON.stringify({ "Username": "james", "Password": "bond" }),
                    contentType: "application/json"
                }).done(function (data, statusText, xhdr) {
                    $("#token").text(data);
                }).fail(function (xhdr, statusText, errorText) {
                    $("#token").text(errorText);
                });
            });

            $("#UseToken").click(function () {
                $.ajax({
                    method: 'GET',
                    url: '@Url.Action("Get", "Movies")',
                    beforeSend: function (xhdr) {
                        xhdr.setRequestHeader(
                           "Authorization", "Bearer " + $("#token").text());
                    }
                }).done(function (data, statusText, xhdr) {
                    $("#result").text(JSON.stringify(data));
                }).fail(function (xhdr, statusText, errorText) {
                    $("#result").text(JSON.stringify(xhdr));
                });
            });
        });
    </script>
</body>
</html>

License

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

Share

About the Author


Comments and Discussions

 
Question.net queries Pin
Member 139983254-Jan-19 20:52
MemberMember 139983254-Jan-19 20:52 
QuestionHow to get a bearer token to call a Web Api method from AJAX? Pin
Jaime Stuardo - Chile4-Dec-18 15:03
MemberJaime Stuardo - Chile4-Dec-18 15:03 
Hello... I need to call the Web Api method ChangePassword, but when I cal it, a forbidden error is raised, so I think I need a bearer token to be sent together with the request.

Do you know how to do it?

This is how I am calling the API:

JavaScript
$("#btnCambiar").on("click", function (event) {
        event.preventDefault();

        runWaitMe('#changeform', "Cambiando Contraseña...");

        var data = {
            OldPassword: $('#OldPassword').val(),
            NewPassword: $('#NewPassword').val(),
            ConfirmPassword: $('#ConfirmPassword').val(),
        };

        $.ajax({
            type: 'POST',
            url: "/api/Account/ChangePassword",
            data: JSON.stringify(data),
            contentType: 'application/json; charset=utf-8'
        })
            .done(function (data) {
                if (data.indexOf('ERROR: ') == -1)
                    swal({
                        type: 'success',
                        title: 'Éxito',
                        html: 'La contraseña fue cambiada exitosamente.'
                    });
                else
                    swal({
                        type: 'error',
                        title: 'Ups...',
                        html: data.substr(7)
                    });
            })
            .fail(function (jqXHR) {
                swal({
                    type: 'error',
                    title: 'Ups...',
                    text: 'Debe llenar todos los campos del formulario en forma correcta.'
                });
            })
            .always(function () {
                hideWaitMe('#changeform');
            });
    });


Thanks
Jaime
QuestionToken Validation Failed Pin
Member 1175557815-Nov-17 4:05
MemberMember 1175557815-Nov-17 4:05 
AnswerRe: Token Validation Failed Pin
Member 1357207612-Dec-17 4:39
MemberMember 1357207612-Dec-17 4:39 
QuestionMinor bug Pin
Liran Friedman6-Nov-17 3:29
MemberLiran Friedman6-Nov-17 3:29 
QuestionGet User Id in MoviesController Pin
aldari21-Oct-17 23:55
Memberaldari21-Oct-17 23:55 
AnswerRe: Get User Id in MoviesController Pin
aldari29-Oct-17 1:19
Memberaldari29-Oct-17 1:19 
QuestionRefresh token Pin
black-byte14-Sep-17 1:09
Memberblack-byte14-Sep-17 1:09 
AnswerRe: Refresh token Pin
User 104326414-Sep-17 3:19
MemberUser 104326414-Sep-17 3: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.