Find me @

Sunday, August 13, 2017

Weekly link roll (weekly)

  • tags: reactjs calendar

  • tags: regex

  • tags: http2

  • tags: react-native

  • tags: react-native

  • "Skip to content GOBLINCODING "Imagine a goblin, coding…cooking up software design and development spells…" Research AntSim Introduction AntSim in Action Downloads References Playground Open Source XML Mill Overview Features Screenshots Downloads Qt Chart Widget Usage and Documentation Limitations Features Screenshots Downloads Blog About Contact POSTED ON JULY 3, 2016 BY WILLIAM HALLATT Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part I       23 Votes Introduction If you’d like to see an example of how you can issue JWT tokens with ASP.NET Core 1 and automatically control access to bearers through the simple application of an [Authorize] attribute (specifically focusing on claims-based authorisation using ASP.NET Core MVC’s policy features) in a Web API project, then you are in the right place! This post is the first part of this epic endeavour and will address the “Issuing” aspects of the problem, which entails:  Initial Setup – this will focus on the “scaffolding” that will be used both by the ‘token server’ side as well as the ‘resource server’ side of the example solution Issuing a JSON Web Token – which focuses on just that as well as how you can validate that it all works. Options and Configuration Adding the Controller Testing the JWT Controller What to expect in Part II Links If you’re here because you require something that goes the distance with refresh tokens and proper identity management built in, I suggest you have a look at this tutorial by Sean Walsh on how to set up OpenIddict in ASP.NET Core. Requirements An installation of the ASP.NET Core RTM (v 1.0.0) for your platform (I am on Windows 10 and using Visual Studio 2015 with Update 3 and ASP.NET Core Tools Preview 2.  Having said that, I’ve tested and confirmed that all the code and dependencies listed here also compiles and runs on Ubuntu 16.04). The source code for this demo so that you may see where the individual pieces I refer to in the gists below fit into the whole. Assumed That you know what JSON Web Tokens are That you know how to create a Web API project with ASP.NET Core MVC That you know where the ASP.NET documentation is for anything not specifically mentioned that might be new to you (also feel free to ask in the comments) Initial Setup The example solution has the token server as well as the resource server in the same solution.  Since we require authentication on the resource side, best practice is to lock down everything and only open up the controllers and methods that you require.  In other words, instead of allowing anonymous access by default and closing down the controllers that require authentication, we require authentication by default and open up the controllers that are allowed to be accessed anonymously.  We do this by replacing the MVC service configuration in the ConfigureServices method in Startup.cs with the following: public void ConfigureServices(IServiceCollection services) { // .......... // Make authentication compulsory across the board (i.e. shut // down EVERYTHING unless explicitly opened up). services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); // .......... } view rawConfigureServicesMVCDefaultAuth.cs hosted with by GitHub Next we add a basic ApplicationUser model: public class ApplicationUser { public string UserName { get; set; } public string Password { get; set; } } view rawApplicationUser.cs hosted with by GitHub We will also require some way to configure our tokens and the way we do this is through the JwtIssuerOptions class that will allow us to set some of the JWT registered claim values as well as provide some additional functionality we require when signing the tokens we generate using Microsoft.IdentityModel.Tokens; using System; using System.Threading.Tasks; namespace WebApiJwtAuthDemo.Options { public class JwtIssuerOptions { ///

    /// "iss" (Issuer) Claim /// /// The "iss" (issuer) claim identifies the principal that issued the /// JWT. The processing of this claim is generally application specific. /// The "iss" value is a case-sensitive string containing a StringOrURI /// value. Use of this claim is OPTIONAL. public string Issuer { get; set; } /// /// "sub" (Subject) Claim /// /// The "sub" (subject) claim identifies the principal that is the /// subject of the JWT. The claims in a JWT are normally statements /// about the subject. The subject value MUST either be scoped to be /// locally unique in the context of the issuer or be globally unique. /// The processing of this claim is generally application specific. The /// "sub" value is a case-sensitive string containing a StringOrURI /// value. Use of this claim is OPTIONAL. public string Subject { get; set; } /// /// "aud" (Audience) Claim /// /// The "aud" (audience) claim identifies the recipients that the JWT is /// intended for. Each principal intended to process the JWT MUST /// identify itself with a value in the audience claim. If the principal /// processing the claim does not identify itself with a value in the /// "aud" claim when this claim is present, then the JWT MUST be /// rejected. In the general case, the "aud" value is an array of case- /// sensitive strings, each containing a StringOrURI value. In the /// special case when the JWT has one audience, the "aud" value MAY be a /// single case-sensitive string containing a StringOrURI value. The /// interpretation of audience values is generally application specific. /// Use of this claim is OPTIONAL. public string Audience { get; set; } /// /// "nbf" (Not Before) Claim (default is UTC NOW) /// /// The "nbf" (not before) claim identifies the time before which the JWT /// MUST NOT be accepted for processing. The processing of the "nbf" /// claim requires that the current date/time MUST be after or equal to /// the not-before date/time listed in the "nbf" claim. Implementers MAY /// provide for some small leeway, usually no more than a few minutes, to /// account for clock skew. Its value MUST be a number containing a /// NumericDate value. Use of this claim is OPTIONAL. public DateTime NotBefore => DateTime.UtcNow; /// /// "iat" (Issued At) Claim (default is UTC NOW) /// /// The "iat" (issued at) claim identifies the time at which the JWT was /// issued. This claim can be used to determine the age of the JWT. Its /// value MUST be a number containing a NumericDate value. Use of this /// claim is OPTIONAL. public DateTime IssuedAt => DateTime.UtcNow; /// /// Set the timespan the token will be valid for (default is 5 min/300 seconds) /// public TimeSpan ValidFor { get; set; } = TimeSpan.FromMinutes(5); /// /// "exp" (Expiration Time) Claim (returns IssuedAt + ValidFor) /// /// The "exp" (expiration time) claim identifies the expiration time on /// or after which the JWT MUST NOT be accepted for processing. The /// processing of the "exp" claim requires that the current date/time /// MUST be before the expiration date/time listed in the "exp" claim. /// Implementers MAY provide for some small leeway, usually no more than /// a few minutes, to account for clock skew. Its value MUST be a number /// containing a NumericDate value. Use of this claim is OPTIONAL. public DateTime Expiration => IssuedAt.Add(ValidFor); /// /// "jti" (JWT ID) Claim (default ID is a GUID) /// /// The "jti" (JWT ID) claim provides a unique identifier for the JWT. /// The identifier value MUST be assigned in a manner that ensures that /// there is a negligible probability that the same value will be /// accidentally assigned to a different data object; if the application /// uses multiple issuers, collisions MUST be prevented among values /// produced by different issuers as well. The "jti" claim can be used /// to prevent the JWT from being replayed. The "jti" value is a case- /// sensitive string. Use of this claim is OPTIONAL. public Func> JtiGenerator => () => Task.FromResult(Guid.NewGuid().ToString()); /// /// The signing key to use when generating tokens. /// public SigningCredentials SigningCredentials { get; set; } } } view rawJwtIssuerOptions.cs hosted with by GitHub Issuing a JSON Web Token Options and Configuration Before we create the JwtController, we need to configure the JwtIssuerOptions and set it up for injection. The first thing we do is to add some configuration settings to appsettings.json, this file should have been created for us by VS as part of the scaffolding and we add a simple JwtIssuerOptions configuration section to it (lines 2 – 5) { "JwtIssuerOptions": { "Issuer": "SuperAwesomeTokenServer", "Audience": "http://localhost:1783/" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } view rawappsettings.json hosted with by GitHub NB! Take care that the ‘Audience’ value matches the ‘applicationUrl’ under ‘iisSettings’ -> ‘iisExpress’ in your ‘launchSettings.json’ file (under ‘Properties’ when you view your project in the VS Solution Explorer pane). The next thing we do is to tell the app that we want to make use of options.  This is a single call to AddOptions on the services instance in the ConfigureServices method in Startup.cs (line 8) and the last part of the JwtIssuerOptions setup is to initialise an instance and make it available to the ASP.NET dependency injection system (lines 13 – 21 below). private const string SecretKey = "needtogetthisfromenvironment"; private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey)); // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddOptions(); // .......... // Get options from app settings var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions)); // Configure JwtIssuerOptions services.Configure(options => { options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)]; options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)]; options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256); }); } view rawConfigureJwtIssuerOptions.cs hosted with by GitHub Pay particular attention to the first two lines.  It is very, very important that you retrieve the SecretKey from some secure location such as Environment Settings and NOT like I did it here! The only reason I did it this way is to make the example easier to write and follow. Note: you will notice that I use the nameof() expression extensively in the above setup.  I heartily recommend it! Adding the Controller Which finally brings us to the JwtController that will serve up the JSON Web Tokens for us using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using WebApiJwtAuthDemo.Models; using WebApiJwtAuthDemo.Options; namespace WebApiJwtAuthDemo.Controllers { [Route("api/[controller]")] public class JwtController : Controller { private readonly JwtIssuerOptions _jwtOptions; private readonly ILogger _logger; private readonly JsonSerializerSettings _serializerSettings; public JwtController(IOptions jwtOptions, ILoggerFactory loggerFactory) { _jwtOptions = jwtOptions.Value; ThrowIfInvalidOptions(_jwtOptions); _logger = loggerFactory.CreateLogger(); _serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented }; } [HttpPost] [AllowAnonymous] public async Task Get([FromForm] ApplicationUser applicationUser) { var identity = await GetClaimsIdentity(applicationUser); if (identity == null) { _logger.LogInformation($"Invalid username ({applicationUser.UserName}) or password ({applicationUser.Password})"); return BadRequest("Invalid credentials"); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, applicationUser.UserName), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), identity.FindFirst("DisneyCharacter") }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); // Serialize and return the response var response = new { access_token = encodedJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return new OkObjectResult(json); } private static void ThrowIfInvalidOptions(JwtIssuerOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); if (options.ValidFor <= TimeSpan.Zero) { throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(JwtIssuerOptions.ValidFor)); } if (options.SigningCredentials == null) { throw new ArgumentNullException(nameof(JwtIssuerOptions.SigningCredentials)); } if (options.JtiGenerator == null) { throw new ArgumentNullException(nameof(JwtIssuerOptions.JtiGenerator)); } } /// Date converted to seconds since Unix epoch (Jan 1, 1970, midnight UTC). private static long ToUnixEpochDate(DateTime date) => (long)Math.Round((date.ToUniversalTime() - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)) .TotalSeconds); /// /// IMAGINE BIG RED WARNING SIGNS HERE! /// You'd want to retrieve claims through your claims provider /// in whatever way suits you, the below is purely for demo purposes! /// private static Task GetClaimsIdentity(ApplicationUser user) { if (user.UserName == "MickeyMouse" && user.Password == "MickeyMouseIsBoss123") { return Task.FromResult(new ClaimsIdentity( new GenericIdentity(user.UserName, "Token"), new[] { new Claim("DisneyCharacter", "IAmMickey") })); } if (user.UserName == "NotMickeyMouse" && user.Password == "MickeyMouseIsBoss123") { return Task.FromResult(new ClaimsIdentity( new GenericIdentity(user.UserName, "Token"), new Claim[] { })); } // Credentials are invalid, or account doesn't exist return Task.FromResult(null); } } } view rawJwtController.cs hosted with by GitHub Line 16: sets up the route to match the controller name Lines 23 – 24: sets up the controller via a basic constructor, notice how the JwtIssuerOptions are injected via the IOptions interface (I refer you again to the options and configuration documentation) Lines 36 – 95: this is where our JWT is generated. Ideally we should have refactored this code for greater modularity, but I find examples easier to follow when everything is kept together so the purists among you must please bear with me. Line 37: remember how we locked down access to only authenticated users in the very beginning? In order for this controller method to be accessible from the outside, we now have to explicitly allow for anonymous access. Line 38: model binding in ASP.NET Core requires that we explicitly bind to the part of the POST that we are interested in, since we are POST-ing a ‘x-www-form-urlencoded’ form, we bind to the form. Lines 40, 106 – 127: once again for the sake of example simplicity, I hard code information you’d normally retrieve from your data store in plain sight.  Two basic identities are possible in this example with the primary difference being that one has the ‘DisneyCharacter’ claim whereas the other does not. Lines 47 – 55: add the claims Lines 56 – 74: create the JwtSecurityToken, encode it and send it back to the caller as JSON (for interest’s sake, the JwtSecurityToken lives in System.IdentityModel.Tokens.Jwt, which comes with the NETStandard libraries, i.e. no additional package needs to be installed in order to use it) Testing the JWT Controller For the testing and validation part, you’ll need to have some way to send requests to the application.  I am particular to Postman and will be using it throughout. Fire up the example solution/your application If you are using the example solution, the application’s URL is http://localhost:1783/ (configured in launchSettings.json) Start up Postman Configure a POST to http://localhost:1783/api/jwt with ‘x-www-form-urlencoded’ selected under Body. Provide two key/values for the form, ‘username’ as ‘MickeyMouse’ and ‘password’ as ‘MickeyMouseIsBoss123’ (remember these values are hard coded in the GetClaimsIdentity method on the JwtController) Click ‘Send’ and wait (if you are running your solution through VS in Debug mode, you can put some breakpoints into the code to trace the process flow).  If everything was set up correctly, you should receive some JSON in the response body that looks similar to the below: And that’s it, a basic, but functional, JSON Web Token Server.  Exciting times! (if, for whatever reason, you failed and can’t figure out what is going on, feel free to ask in the comments) Cheers! (If you got this far and liked what you read, consider following me @thewillhallatt if you would like to be notified of future articles) What to Expect in Part II Part II addresses automatically controlling access to JWT bearers through the [Authorize] attribute (utilising JwtBearer authentication middleware), specifically focusing on user claims using ASP.NET Core MVC’s policy features in a Web API project. Links Token Authentication in ASP.NET Core (without this blog post by Nate Barbettini, this multi-part tutorial of mine would not have been possible) Supported Token and Claim Types (although aimed at Azure and ADAuth specifically, the first part is a useful, general overview of tokens ASP.NET Core Authorization Lab Share this: TwitterPinterestFacebook20RedditMore Related ASP.NET Core policy-based authorisation using JSON Web Tokens In "ASP.NET Core" Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II In "ASP.NET Core" Mocking multipart/form-data HttpRequestMessage for testing ASP.NET ApiController In "Testing" CATEGORIESASP.NET CORE TAGSAUTHENTICATION, AUTHORISATION, JWT, WEBAPI 57 Replies to “Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part I” Mariusz JULY 5, 2016 AT 21:49  0 0 Rate This Great article ! This is what i was looking for thx! Reply William Hallatt JULY 7, 2016 AT 20:13  1 0 Rate This You’re most welcome Mariusz! In case you’re interested, I just published Part II: https://goblincoding.com/2016/07/07/issuing-and-authenticating-jwt-tokens-in-asp-net-core-webapi-part-ii/ Reply Mariusz JULY 9, 2016 AT 11:14  1 0 Rate This god damn you’re the best ! It is very helpful Pingback: The week in .NET – 7/12/2016 | Tech News Pingback: ASP.NET Core policy-based authorisation using JSON Web Tokens – goblincoding Prashant SEPTEMBER 30, 2016 AT 17:54  0 0 Rate This The name and password field of applicationUser is alwayd null. Can you please help me find the cause for that? Reply William Hallatt OCTOBER 3, 2016 AT 18:31  0 0 Rate This I can’t possibly know why that is happening without knowing the context within which you are asking your question Reply Sam Ellis DECEMBER 22, 2016 AT 00:22  0 0 Rate This I think your problem is that you’re entering the username and password as post parameters rather than in the body. The Get() method signature requires them in the body. So for example if you’re using Postman, don’t enter the parameters in in the key/value pair section just below the URL, enter them under the body section after selecting x-www-form-urlencoded. You can change the method signature to accept parameters or other options as you see fit, but that’s how the example is given. Reply Prashant SEPTEMBER 30, 2016 AT 21:20  0 0 Rate This Instead of using -www-form-urlencoded, I want to use application/json. the value of username and password becomes null. I found on the net that .net core by default accepts json. Why is it not working in my case? Reply William Hallatt OCTOBER 3, 2016 AT 18:32  0 0 Rate This I don’t know what your case is, so I just don’t know mate, sorry Reply Sebastian Nyberg FEBRUARY 1, 2017 AT 14:35  0 0 Rate This Change [FromForm] to [FromBody]: public async Task Get([FromBody] ApplicationUser applicationUser) Reply Sampath OCTOBER 11, 2016 AT 05:55  0 0 Rate This Perfect! Thanks. I could start real thing without an issue. Reply William Hallatt OCTOBER 11, 2016 AT 18:54  0 0 Rate This Excellent! Reply Julien OCTOBER 12, 2016 AT 21:18  0 0 Rate This Excellent post, thank you, really appreciated your work on this. FYI: The JwtController’s action is marked as ‘HttpPost’´ but named ‘Get’. Reply William Hallatt OCTOBER 13, 2016 AT 19:32  0 0 Rate This Glad I could help and thanks for pointing that out, I’m going to have to fix it! Reply Forb.Jok OCTOBER 13, 2016 AT 10:43  3 0 Rate This Maybe I messed something up, but when I set it up in my project following this tutorial (with ASP.NET Core 1.0.1), it seems like the controller’s JwtIssuerOptions instance isn’t being recreated for each call, so it retains the same IssuedAt and Expiration dates. This means that after a while it will start issuing already-expired tokens. Reply William Hallatt OCTOBER 13, 2016 AT 19:37  0 1 Rate This Hi there! That is very likely, I never went further than testing the concepts, so please don’t use any of the code in the sample for production! I created this tutorial as part of the process I had to go through to understand how this all fits together, but I honestly cannot envision a scenario where I would actually “roll-my-own” (the risks are just too great). There are a number of very good, production-ready libraries out there that I would rather use (e.g. IdentityServer). Cheers, William. Reply AK OCTOBER 19, 2016 AT 11:13  1 0 Rate This I just discovered the same issue. Fixed it by changing the properties in the options class like this: IssuedAt => DateTime.UtcNow, do this for all properties that must be dynamic. Reply Avishek OCTOBER 17, 2016 AT 07:59  0 0 Rate This Great post! Can you please explain what changes we need to make to send JWTs as cookies instead of authorization bearer ? Reply William Hallatt OCTOBER 17, 2016 AT 20:25  0 0 Rate This Hi Avishek, do you mean how to store a JWT in a cookie? You can look at the cookie auth examples on the actual asp.net site: https://docs.asp.net/en/latest/security/index.html Reply Ba Sy Pham OCTOBER 24, 2016 AT 09:35  0 0 Rate This Nice Article !!! Very clearly and helpful. Thanks. Reply Alin Ciocan OCTOBER 27, 2016 AT 06:56  0 0 Rate This Thank you very much for this tutorial and also for Part 1. Reply William Hallatt OCTOBER 28, 2016 AT 15:29  0 0 Rate This You’re most welcome Alin Reply mowali OCTOBER 27, 2016 AT 21:35  0 0 Rate This I’ve gotten reading as far as only Initial Setup, but I already love your way of writing and clear style! Reply William Hallatt OCTOBER 28, 2016 AT 15:29  0 0 Rate This Reply Fredrik Ljung OCTOBER 28, 2016 AT 10:40  0 0 Rate This Very helpful, thanks! I have a question though: Are there any issues with using a randomly generated string as the key for symmetric encryption? I was thinking since the jwt’s are short lived, making them invalid at server restart won’t be an issue? Are there any security issues of using a randomly generated string as encryption key instead of grabbing it from an environment variable? Reply William Hallatt OCTOBER 28, 2016 AT 15:32  1 0 Rate This Hi Fredrik, I don’t know if I am qualified to give a trustworthy answer to that question and I have never previously considered doing that. Having said that, as I am sitting here, I cannot immediately think of a downside to having a key that re-generates itself each time the server gets bounced. Your biggest “risk” would be in invalidating user’s access, but the worst that would happen in that case would be that the user will be required to log in again…I guess there is also a small risk of transactions failing due to some unforeseen circumstances. Anyhow, don’t take my word for it, we might both be wrong! Reply caesar NOVEMBER 4, 2016 AT 05:06  1 0 Rate This Hi, I have just used your work as a template in my project, it is working well but after the token expires and I sent a request for a new token and used the new token for the succeeding request, it always return error 401 and upon inspecting the result it have a message of token already expired, can you point me where to look at? Thanks Reply William Hallatt NOVEMBER 7, 2016 AT 17:49  0 0 Rate This Hi Caesar, I am sorry but I have absolutely no idea. Please do NOT use my code for anything resembling production, it is not safe enough, rather look at something like IdentityServer4. Cheers! Reply Dominik MARCH 22, 2017 AT 04:18  0 0 Rate This Hi, Did you solve this problem? Reply saransh DECEMBER 16, 2016 AT 09:41  0 0 Rate This Thanks a lot you make this super easy :). Reply bharatrm DECEMBER 24, 2016 AT 07:37  0 0 Rate This Awesome! Just what I was looking for. I searched and searched for ways to implement Token authentication and I finally got the right article. Reply Colin Nagle JANUARY 10, 2017 AT 13:19  0 0 Rate This Thanks for the article, exactly what I needed after diving down a bunch of rabbit holes. Reply Pingback: Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part I – goblincoding | ASP.NET Core Dung Nguyen JANUARY 24, 2017 AT 06:49  0 0 Rate This Hi William Hallatt! It’s very simple to understand! But when I use https://jwt.io/ to check my token (eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJNaWNrZXlNb3VzZSIsImp0aSI6IjlkODBiYjMwLTZiMTktNDQ1OS05ZGQxLWZlOTQ0YjhkMzBkNCIsImlhdCI6MTQ4NTIzMTg2MiwiRGlzbmV5Q2hhcmFjdGVyIjoiSUFtTWlja2V5IiwibmJmIjoxNDg1MjMxODYxLCJleHAiOjE0ODUyMzIxNjEsImlzcyI6IlN1cGVyQXdlc29tZVRva2VuU2VydmVyIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDoyNTUxMy8ifQ.aIVCsOKzBrDVZJmw7BpaNDw9Dhgnh2kNAB9_W-7Bm10)=> it return “Invalid Signature” Could you explain it? Thanks you so much! Reply William Hallatt JANUARY 24, 2017 AT 07:02  0 0 Rate This In order to validate the signature, you must also provide the signature key you used to sign your JWT with. Reply Dung Nguyen JANUARY 24, 2017 AT 09:23  0 0 Rate This How I do this? Could you help me? Thanks you! afshar JANUARY 24, 2017 AT 16:50  0 0 Rate This Many thanks for your solution. I have used it in my project but User.Identity.Name is null. How can I correct this? I have created a completed question here: http://stackoverflow.com/questions/41830898/usejwtbearerauthentication-does-not-get-user-identity-name-populated thanks a lot Reply afsharm JANUARY 24, 2017 AT 16:52  0 0 Rate This Hi, I followed same way you described in this helpful post but user name is always null. I have created a SO entry here: http://stackoverflow.com/questions/41830898/usejwtbearerauthentication-does-not-get-user-identity-name-populated Would you please help me find a solution for this? Thanks in advance. Reply William Hallatt JANUARY 26, 2017 AT 19:14  1 0 Rate This Hi Afshar, I see the StackOverflow question was answered, glad you figured it out! Reply Luis FEBRUARY 6, 2017 AT 16:06  1 0 Rate This Just so you know, I had some trouble using this sample when I tried to get the ApplicationUser inside an [Authorize] method, just figured out that if you want to use ._userManager.GetUserAsync(HttpContext.User) you need to set the JwtRegisteredClaimNames.Sub to applicationUser.Id instead of applicationUser.UserName Reply William Hallatt FEBRUARY 6, 2017 AT 16:49  0 0 Rate This Thanks for the contribution! Reply Ali Kolahdoozan FEBRUARY 19, 2017 AT 19:19  0 0 Rate This Hi, Can you upload a full working source code?. Reply William Hallatt FEBRUARY 20, 2017 AT 07:06  0 0 Rate This Everything you need is already in the repo. Can you not access GitHub? Reply Francois Hattingh MARCH 18, 2017 AT 23:21  0 0 Rate This Great article. Just one more RED FLAG to add. Don’t leak passwords to your log file. Reply Foobar APRIL 10, 2017 AT 22:23  0 0 Rate This The built in DI seems to make “IOptions jwtOptions” singleton. That leads to this next line being the same for the entire lifetime of the application: public DateTime IssuedAt { get; set; } = DateTime.UtcNow; How do i register IOptions as Transient() in Startup.cs? Alternate solution is to return IssuedAt as follows: public DateTime IssuedAt { get { return DateTime.UtcNow; } } Reply William Hallatt APRIL 15, 2017 AT 11:51  0 0 Rate This Hi Foobar, I suspect that the service collection does indeed only create a single instance of that object, but that has nothing to do with your problem as “singleton” is not the same as “static”. Your problem stems from the fact that you are only setting the value once. public DateTime IssuedAt { get; set; } = DateTime.UtcNow That is code that initialises an auto-property, so unless you set it again somewhere else, it won’t change (Note: Have a look at the code in my repo where I use an expression body as I have no setter requirement). Reply Foobar APRIL 16, 2017 AT 00:05  0 0 Rate This Yeah, I took it from this blog post. The code differs from this post and the repo check line 65 above. William Hallatt APRIL 17, 2017 AT 10:47  0 0 Rate This Aah, that explains a lot! Thanks for catching the mistake and sorry about the confusion Pingback: For me to remember: .NET Core and JWT – Adam Hathcock, the blog jyx MAY 26, 2017 AT 12:37  0 0 Rate This how can i use it ?? request the webapi Reply William Hallatt MAY 27, 2017 AT 10:34  0 0 Rate This Not sure what you are referring to. How can you use what? Reply Linda JUNE 7, 2017 AT 21:00  0 0 Rate This Hi William, I am planning to use EF Core to pass through the username and password to get a user authenticated by a stored procedure in my database. I plan on creating a Data Layer Project that will access my database models. Do you have a sample of how I can do this? private static Task GetClaimsIdentity(ApplicationUser user) { if (user.UserName == “MickeyMouse” && user.Password == “MickeyMouseIsBoss123”) { return Task.FromResult(new ClaimsIdentity(new GenericIdentity(user.UserName, “Token”), new[] { new Claim(“DisneyCharacter”, “IAmMickey”) })); } if (user.UserName == “NotMickeyMouse” && user.Password == “NotMickeyMouseIsBoss123”) { return Task.FromResult(new ClaimsIdentity(new GenericIdentity(user.UserName, “Token”), new Claim[] { })); } // Credentials are invalid, or account doesn’t exist return Task.FromResult(null); } Linda Reply William Hallatt JUNE 8, 2017 AT 16:54  0 0 Rate This Hi Linda, I’m sorry, but I don’t have anything at hand at the moment, I’d have to dig around myself to figure that out! Reply Linda JUNE 7, 2017 AT 21:10  0 0 Rate This Do you have a guide on how to publish this WebAPI into production? Reply William Hallatt JUNE 8, 2017 AT 16:55  0 0 Rate This Hi again Linda, I don’t have a guide, we’re currently publishing to Azure which is pretty much as painless as it gets, so depending on your setup, the following might be of use to you: https://docs.microsoft.com/en-us/aspnet/core/publishing/ Reply sagar bhosale JUNE 10, 2017 AT 01:36  0 0 Rate This Great Post! how can we implement refresh/renew token in this demo application? we are not using any third party auth server like identity server etc. Reply Leave a Reply Post navigation Previous Post PREVIOUS Mocking DependencyResolverNext Post NEXT Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II CONNECT View @thewillhallatt’s profile on TwitterView williamhallatt’s profile on LinkedInView williamhallatt’s profile on GitHub RECENT POSTS ASP.NET Core policy-based authorisation using JSON Web Tokens Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part I Mocking DependencyResolver Adding Docker Terminal to cmder on Windows FOLLOW BLOG VIA EMAIL Enter your email address to follow this blog and receive notifications of new posts by email. LinkedIn GitHub Twitter Create a free website or blog at WordPress.com."

    tags: jwt

  • tags: 3d holographic display content ebook

  • tags: 3d holographic display

  • tags: react-native

  • tags: react-native timeclock

  • tags: react-native

  • tags: react-native

  • tags: react-native

  • tags: react-native

Posted from Diigo. The rest of my favorite links are here.

No comments:

Post a Comment