Wednesday 6 January 2016

Auth0 and 401 Unauthorized

Today was One of those days™ where things just didn’t work well, or rather at all. I’ve been working on an ASP.NET WebAPI that was working fine against Auth0, but needed to update it to use OWIN. It took a while to update everything and get the appropriate packages installed, and then I went through the code and ripped out the old and replaced with the new.

The API is called using a bearer token that is retrieved from Auth0 – example code below…

  var uri = ConfigurationManager.AppSettings["auth0:Domain"];
  var client = new HttpClient { BaseAddress = new Uri(uri) };
  var data = new LoginRequest
  {
    Username = model.Username,
    Password = model.Password,
    ClientId = ConfigurationManager.AppSettings["auth0:ClientId"],
    Connection = ConfigurationManager.AppSettings["auth0:Connection"],
    GrantType = "password",
    Scope = "openid"
  };

  var response = await client.PostAsJsonAsync<LoginRequest>("oauth/ro", data);

  if (response.IsSuccessStatusCode)
  {
    var result = await response.Content.ReadAsAsync<LoginResponse>();

    // Now use the response token...
  }

I’d written this code myself to call the Auth0 API as I couldn’t get the provided Auth0 code to work at all – the response I was getting back was always a null. The LoginRequest and LoginResponse objects simply mimicked the request and response data sent to and received from the Auth0 API that I was calling.

When I called this I received a token back – but then the problems started. Whenever I called my API, all I got back was a 401 Unauthorized response. It took me a long time to sort this, I even went to the bother of creating an entirely new solution with two web apps included, one to “login” to Auth0 and get a token, the other being the API I wished to call, so that I could raise a support incident with Auth0. I had a feeling that it must still be something I was doing wrong as I’ve used Auth0 for a while and to be fair it had previously been working fine until I did this upgrade.

It got to the point where I needed to get some help, and that came in the form of Reflector. I’m sure that Red-Gate should send me a free copy the number of times I’ve mentioned it in my blog. Not that I mind paying for it, it’s a fantastic tool. Anyhow, after some spelunking through the code I found that the Owin pipeline has a logging component, and also found out how to enable it. I added the following to my web.config (this was in the callee project)…

  <system.diagnostics>
    <switches>
      <add name="Microsoft.Owin" value="Verbose" />
    </switches>
  </system.diagnostics>

With that in place I then debugged my application and saw this in the debug output…

Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware Error: 0 : Authentication failed
System.IdentityModel.Tokens.SecurityTokenException: Issuer not known.
   at Microsoft.Owin.Security.Jwt.JwtFormat.Unprotect(String protectedText)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationTokenReceiveContext.DeserializeTicket(String protectedData)
   at Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationHandler.<AuthenticateCoreAsync>d__0.MoveNext()

Finally I had something to go on! I've worked a fair bit with JWT tokens over the last couple of years so happened to know that the issuer was one of the fields within the JWT, so then I knew that something was either not sending the right issuer, or when decoding the token on the API side the wrong issuer was being used. Now, just to be clear, I had made ZERO changes to my web.config between the old (non OWIN) version that worked, and this new version that didn't work. So I was suspicious to say the least.

So, I grabbed a copy of the token I was using and headed off to jwt.io which has a handy JWT decoder. You paste in the token and it will decode it for you, I saw this when I did mine…

HEADER:ALGORITHM & TOKEN TYPE

{
  "typ": "JWT",
  "alg": "HS256"
}

PAYLOAD:DATA

{
  "iss": "https://redacted.com/",
  "sub": "auth0|568bf53557c21c88287d9b03",
  "aud": "P7H7jdzZ4pSc9ifPU2XS7y03HXfcOYHG",
  "exp": 1452069269,
  "iat": 1452033269
}

The important part was that the issuer looked correct to me, so I then went looking at the API project to see what it was defined as there. In the web.config (which was simply copied from the Auth0 sample) I had this...

  <add key="auth0:ClientId" value="....." />
  <add key="auth0:ClientSecret" value="....." />
  <add key="auth0:Domain" value="redacted.com" />
  <add key="auth0:Connection" value="....." />

BINGO!

The auth0Domain value did not include the scheme or trailing slash, and this was being used by the Auth0 code as the issuer. With this knowledge I simply updated the web.config to https://redacted.com/ and sure enough my code started working again.

Hopefully this helps someone else, it took me quite a while to solve!

70 comments:

Unknown said...

Very good write-up. I definitely appreciate this morganskinner.com Blog . Continue the good work!
Devops Online Training

nasreen basu said...
This comment has been removed by a blog administrator.
Unknown said...
This comment has been removed by the author.
Unknown said...

thank you for the post , good write up. keep posting related articles. you may also like this post devops online course

Unknown said...

First of all thanks Morgan

Very interesting post share "Random Wibblings". Coursecrown

immortal herbal beauty said...
This comment has been removed by the author.
immortal herbal beauty said...

Great Article.It is awesome .Thanks for sharing information. Immortal herbal Beauty

Unknown said...

Thanks for sharing very Informative blog for us, Check it once through Devops Online Training

Oliver Maurice said...

You need to check out this information about how to write an essay to know how to do it right and how to do it quick. Good luck

Unknown said...

mobilism download simcity buildit mod apk latest dead trigger mod apk offline

geektech said...

I would like to know if you have anyother blogs as well Dead Trigger 2 MOD Game

wamp institute said...
This comment has been removed by the author.
the hulchal said...

Great piece of content. This is really very useful for me. The amazing topic you described here. The writing style is very impressive and easy to understand. I usually find such a good content. I never comment on any article but this one something different. I can't stop to comment myself. last time I read some good post at timesera .Here i am sharing some posts which completely very amazing.

Junaid Khan said...

Thank You so much for this informative post. Thanks for sharing how you are doing it and I am sure a lot of people will be helped through the resource you shared.
Learn about Digital Marketing
Digital Marketing Ideas

Nathan William said...

The experts of this company always understand the students and their homework issues. So, they provide best primary homework help service in doing their assignment in numerous subjects. The service not only helps the students in resolving their issues of academic assignment, but also provides some time for meditation and relaxation. This company has become a renowned website in worldwide academic industry. It acts as the best homework help service provider, which provide solutions to the changing needs of the students around the world like USA, UK, Australia and Singapore many others. The experts of this company do not hide anything from you and always keep constant contact with you regarding your assignments. If experts face any issues during providing do my homework for me , it is immediately shared with you so that you can resolve the issues regarding your requirements.

Anu Shukla said...

Great Stuff!

Love your writing skills.
keep sharing stuff like this.

Hindi Panda

Unknown said...

thank you for this post this informational website desigining

geektech said...

I like the way you are Best Battery Booster Reviews Latest doing these things koplayer mac

Randi said...

hallo pecinta game android, ada game seru ini untuk kamu mainkan bersama teman-teman kamu. Yang pasti game yang berjudul dead trigger 2 ini tidak kalah serunya dari game yang lainnya. Kami telah menyediakan review tetang game ini dengan lengkap beserta link downloadnya. Kamu bisa download game dead trigger 2 ini secara gratis offline disini. Jika kamu penasaran tentang keseruan game dead trigger 2 andorid apk obb ini silahkan mampir ke blog android saya ya. Baca selengkapnya: https://downloadgameofflineapkmod.blogspot.com/2019/07/dead-trigger-2-offline-version-apk-obb.html

Prerna Mehta said...

I just like the helpful information you provide in your articles. I will bookmark your blog and take a look at once more here regularly.
I am somewhat certain I’ll be informed plenty of new stuff right here! Good luck for the following! tally classes

Deepak said...

Fine way of telling, and pleasant post. Nice info! Thanks a lot for sharing it, that’s truly has added a lot to our knowledge about this topic. Have a more successful day. Amazing write-up, always find something interesting.
personality development classes

Thanks

ankit said...
This comment has been removed by the author.
invincible01 said...

Amazing Article,Really useful information to all So, I hope you will share more information to be check and share here.


Inplant Training for cse
Inplant Training for IT
Inplant Training for ECE Students
Inplant Training for EEE Students
Inplant Training for Mechanical Students
Inplant Training for CIVIL Students
Inplant Training for Aeronautical Engineering Students
Inplant Training for ICE Students
Inplant Training for BIOMEDICAL Engineering Students
Inplant Training for BBA Students

KeiraDoltan said...

Complete Your Assignment From
Construction Management Assignment Help

Grace Ella said...

When you are uploading your next post? Auth0 and 401 Unauthorized post is very meaningful for me and it has solved my issue which I was facing in completing my projects. Dissertation Writing Service

john said...

If you were looking for exemplification topics but the results were disappointing, just check here.

Technogeekscs said...

Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuff like this.
Data Science
Selenium
ETL Testing
AWS
Python Online Classes

Jessica Jones said...

Thank you for sharing such a very valuable content information. Its really helpful and informative for every visitor's. I hope more posts from you share with us and, Thank you so much like this data share with us. university assignment help australia -
australia assignment -
auditing assignment

Selenium Training in Pune said...

That's really impressive and helpful information you have given, very valuable content.
We are also into education and you also can take advantage of really awesome job oriented courses

Huongkv said...

Aivivu chuyên vé máy bay, tham khảo:

kinh nghiệm mua vé máy bay đi Mỹ giá rẻ

vé máy bay từ mỹ về việt nam 2021

giá vé máy bay đi Los Angesles

chuyến bay từ canada về việt nam

Anonymous said...
This comment has been removed by the author.
Anonymous said...

If you were Finding Quality Air duct Service or Commercial air duct Service Then I will highly recommended you Air Duct Cleaning Service Littleton

Anonymous said...

If you were Finding Quality Air duct Service or Commercial air duct Service Then I will highly recommended you Air Duct Cleaning Service Littleton

Anonymous said...

Our pest controller team provide Quality of work with Excellent Results of pest control If you Worry about Pest then Visit : pest control service in austin tx

Anonymous said...

We have opened our local office in Boston, MA , comprising of skilled members to take care of all your gutter We provide gutter cleaning services or repairing, and maintenance tasks related to gutters.

Anonymous said...

We are fully licensed & insured committed to our client’s satisfaction. Our team provide Best ever gutter cleaning services

Anonymous said...
This comment has been removed by the author.
Anonymous said...
This comment has been removed by the author.
Anonymous said...

If you are searching for a garage door opener & Motor installation and replacement, at that point, your search finishes here. Visit : https://samedaygaragedoorservicesga.com/garage-door-repair-woodstock/

Anonymous said...

There Should be running of water coming from your Toilet or water come out on the floor or toilet bowl a long time after Flush. We were here to provide you this type of problem solution we will provide you Toilet Installation and Repair

Anonymous said...

We are proud to customize the project according to your needs. We are working with many big corporates for all their roofing repair and installation needs and maintenance due to our specialized methods.we provide you COMMERCIAL ROOFING SERVICES IN MARYSVILLE

Anonymous said...

The extraordinarily trained technicians at Hiwire Technology can provide you with an extensive range of system customizations, installations, repairs, reviews, and solutions. We provide High Quality Wire of system installations and repair in cucamonga.

Anonymous said...

We provideelectrical installation in Durham , NC our team provide excellent results

Anonymous said...

Gem stone is a part of jewelry we have fantastic designs of rings or gems. we provide Aqeeq Rings For Men

Technogeekscs said...

Wow, it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
Python Training Institutes in Pune
Best Training Institute for AWS in Pune
Data Science Course in Pune

Job King said...

Beste Online Casino Anbieter
Das Angebot von Online Spielbanken ist nicht nur unfassbar groß, es wächst weiterhin stetig an. Regelmäßig kommen neue Anbieter dazu. Die Auswahl wird damit zwar besser, aber gleichzeitig auch immer schwieriger.

Der Wettbewerb unter den Echtgeld Casinos macht sich klar in den umfangreichen Bonus-Paketen bemerkbar. Ein attraktiver Willkommensbonus ist für viele Spieler der ausschlaggebende Grund, sich bei einem Online Casino zu registrieren. Dabei wird häufig ausgeblendet, dass beim Online Casino Spielen auch nach dem Willkommensbonus Spannung und Qualität gefragt wird. Wer dauerhaft zufrieden sein möchte, sollte sich an unsere sorgfältig zusammengestellte Liste der besten Online Casinos halten.

https://gutcasinos.com/

bestpressurecooker said...

Brawl Stars Mod Apk
A mí me encanta el turismo gastronómico, es delicioso y se aprende mucho, además de disfrutar de todo lo que lleva un viaje. Es una experiencia fabulosa. Muy recomendada!

bestpressurecooker said...

Brawl Stars Mod Apk
if you have stress for your assignment, hire our professional writers.

mohit said...

Thank you for sharing blog with us! Good luck!

bishopmarkus said...

Everyone understands how challenging it is to have a baby in your life, and so our objective is to help you parents feel more confident and prepared. As well create the most memorable experience for yourselves and your baby. You can find us here https://mamasarecool.com/

Whether you are still planning, or have already started this journey, our site will help shorten your time on worries and research by combining it all into one convenient place for you.

Our mission is to help give the best and safest experience to your child in their young years. Furthermore, to find and provide advice on related topics and reviews on products, which go in efforts of helping your family have a remarkable adventure.

Masonethan said...

One of the best reading articles which has some useful information for do my coursework and also for those who have limited knowledge about this, So thank you and keep it up with this excellent masterpiece.

bishopmarkus said...

Liberty Wallet
Your Safety Hardware Cryptocurrency Wallet
https://liberty-wallet.com/

While the concept of Bitcoin may be new to some, this well-known cryptocurrency has been around for more than a decade. Bitcoin (BTC) is one of many digital currencies that have become fairly common investment holdings among tech-savvy households.

Proponents of cryptocurrencies argue that digital currencies are easier and safer, and come with better privacy, than traditional currencies.

Bitcoin wallets store a collection of bitcoin private keys. Typically, the wallet is password- or otherwise protected from unauthorized access. A Bitcoin wallet is controlled solely by its owner, not distributed and shared like blockchain technology.

Unknown said...

amazing content like Immigration SG

vola said...
This comment has been removed by the author.
Unknown said...

cover coin hangi borsada
ray coin hangi borsada
celo coin hangi borsada
srm coin hangi borsada
xec coin hangi borsada
celr coin hangi borsada
sngls coin hangi borsada
mbox coin hangi borsada
sxp coin hangi borsada

Anonymous said...

10 Essential tips for a trip to japan

pangoleen said...

https://quizterra.com/
Create, publish and monetize interactive content on your website. Quizterra is a functional quiz making software with great designs, wide functionality and free embed

Eunus Khan said...

I really like an individual's posting layout, superb info, thanks meant for posting: Ve had. บาคารา

EZaccounting said...


Nice article, good content are shared. Thanks for sharing the article.
Psg grant software
Accounting software Singapore
Ez accounting

Safi said...

Thank you for sharing such a decent post..PSL 2022

Kaylee Brown said...
This comment has been removed by the author.
jhon wicky said...

Nice website. Love it. This is really nice colourist logo

PSW550 said...

ดาวน์โหลด PG ให้คุณสามารถเล่นได้บนสมาร์ทโฟน ให้คุณสามารถเล่นได้อย่างมากมาย ทั้งสล็อตออนไลน์ คาสิโนออนไลน์ อาเขต หรือแม้กระทั่งบิงโก กับเกมการเล่นที่เข้าใจง่าย เล่นได้หลากหลายระบบทั้งแอนดรอย และไอโอเอส

slot said...

ปลอดภัยในทุกๆการเดินทาง กับเกมสล็อต PG เล่นได้ทันทีผ่านโทรศัพท์มือถือ ไม่ว่าจะเป็นรุ่นเก่า หรือรุ่นใหม่ ตอบโจทย์การเลนที่แปลกใหม่ เล่นง่าย จายจริง ดาวน์โหลด PGSLOT มีให้เลือกเล่นหลากหลาย ทั้งสล็อตออนไลน์ คาสิโนออนไลน์ อาเขต และบิงโก

Smith Williams said...

The growing incidence of chronic fatal diseases including cancer, CVD among all is one of the key factors driving the demand of the microtome market globally. Due to this, the expenditure on laboratory setup is increasing continuously by the government as well as private players, which will augment the micrometer market.

Also Read: robotics technology market
glucuronolactone market

newin said...

บทสรุปวิดิโอสล็อตทำเงินออนไลน์ Pirate Pays โอกาสการทำเงินที่มีโอกาสได้รัเงินรางวัลที่แตกง่าย ไม่มีความยากและซับซ้อนในการเล่นอย่างแน่นอน ไม่มีสดุดตลอดการทำเงินอย่างแน่นอนการันตีโอกาสการได้รับเงินรางวัล

veerapriya said...

บาคาร่าออนไลน์ กับสิ่งที่คุณควรจะทำความเข้าใจสำหรับในการเล่นเกมมีอะไรบ้าง
เกมพนันออนไลน์มีหลายเกมมากมาย แต่ละเกมนั้นมีความต่างกันไปในเรื่องของข้อตกลงการเล่น ซึ่งไม่ว่าคุณจะเล่นเกมใดๆก็ตาม คุณจำเป็นต้องทำความเข้าใจสิ่งที่เกี่ยวโยงกับตัวเกมอย่างรอบด้าน เพื่อคุณนั้นเล่นเกมได้อย่างมีคุณภาพ สนองตอบต่อความปรารถนาของคุณได้ และก็ในวันนี้พวกเราจะมาเอ๋ยถึงเกมบาคาร่าออนไลน์ กันว่าคุณควรจะทำความเข้าใจเรื่องอะไรบ้าง เพื่อเอาชนะพนันได้ ยืนยันเลยว่า คุณจะสุขสบายสำหรับเพื่อการเล่นมากขึ้นแน่ๆ

บาคาร่า เป็นอย่างไร
บาคาร่า เกมไพ่ออนไลน์ยอดนิยมเป็นอย่างมาก ไม่ว่าจะเล่นในบ่อน หรือ จะเล่นในเว็บไซต์พนันออนไลน์ก็ตาม ส่วนมากแล้วจะใช้ไพ่หลายสำรับสำหรับในการเล่น รวมทั้งมีกฎข้อตกลงการเล่นที่คล้ายกับไพ่ป๊อก ทำความเข้าใจได้ง่ายๆ ทำให้ผู้คนจำนวนมากเลือกที่จะเล่นเกมนี้กัน

สิ่งที่คุณจะต้องศึกษาสำหรับในการเล่น บาคาร่าออนไลน์ มีอะไรบ้าง
• กฎข้อตกลงการเล่นบาคาร่าออนไลน์ ถึงแม้ บาคาร่าจะเป็นเกมที่รู้เรื่องได้ง่าย และก็ ทุกคนรู้จักดีกับการเล่นกันมาแล้ว แม้กระนั้นกฎสำหรับในการเล่นแบบออนไลน์ อาจมีความไม่เหมือนกันบ้าง รวมทั้งเรื่องข้อตกลงพิเศษต่างๆของเกมก็เป็นสิ่งหนึ่งที่คุณจะต้องทำความเข้าใจ
• วิธีการเล่น บาคาร่าเป็นอีกเกมหนึ่งที่คุณสามารถใช้วิธีการเล่นเพื่อเอาชนะพนันได้ เพียงแต่ว่าจำต้องเลือกใช้ให้ตรงกับเหตุการณ์สำหรับการเล่นเพียงเท่านั้น
• จะต้องรู้เรื่องก่อนว่า ไพ่แบบไหนดีกว่า แบบไหนเสียเปรียบ ด้วยเหตุว่าส่วนมากแล้ว ทุกเว็บไซต์จะมีโต๊ะบาคาร่าหลายโต๊ะอยู่แล้ว หากคุณเห็นว่าเล่นอย่างนี้จะเสียเปรียบ คุณสามารถแปลงโต๊ะได้เลย ทำให้ท่านเหนือกว่าสำหรับเพื่อการเล่นเยอะขึ้น
• บาคาร่าออนไลน์ มีหลายห้องหลายโต๊ะมากมาย หากคุณนั้นมีความคิดว่า เล่นแล้วมิได้ดังใจ หรือจะแพ้พนัน คุณสามารถแปลงโต๊ะสำหรับเพื่อการเล่นได้เลย ทำให้ท่านนั้นสามารถลงพนันได้อย่างมีคุณภาพ สนองตอบต่อสิ่งที่มีความต้องการของคุณได้
• บาคาร่า เล่นแล้วมั่งมีได้ใช่หรือไม่

บาคาร่าออนไลน์ เล่นแล้วร่ำรวยได้แน่ๆ เพียงแต่ว่าจะต้องกำหนดแผนการเล่นให้ดี เพื่อคุณนั้นได้โอกาสที่จะชนะพนันเยอะที่สุด แม้กระนั้นอย่างไรก็แล้วแต่ คุณต้องรู้เรื่องก่อนว่า บาคาร่า เป็นเกมพนันที่มีการเสี่ยงสูง หากคุณไม่ระวังสำหรับในการเล่น หรือ ลงเงินแบบไม่ระวัง คุณอาจจะแพ้พนันได้

ทั้งสิ้นนี้เป็นเรื่องราวของ บาคาร่า ที่คุณต้องทำความเข้าใจ แล้วคุณจะสามารถเล่นบาคาร่าได้อย่างมีคุณภาพด้วย รับประกันว่าคุณจะแฮปปี้สำหรับเพื่อการเล่นบาคาร่าแน่ๆ

aayat said...

Thanks for the blog post buddy! Keep them coming...
Resume Builder

Helen said...

Vitamin & Supplement Product Reviews. Explore reviews of top vitamins and supplements to find what you need to meet your health goals. https://www.hfrreviews.com/category/reviews/. Explore reviews of top vitamins and supplements to find what you need to meet your health goals.

Angel17 said...

What an awesome post. I find this so interesting! https://www.appliancerepairsherwood.com/dishwasher-repair