This example shows you how to use the Okta.AspNet
library to log in a user. The user's browser is first redirected to the Okta-hosted login page. After the user authenticates, they are redirected back to your application. ASP.NET MVC automatically populates HttpContext.User
with the information Okta sends back about the user.
This builds on the Okta sample by adding token refresh abilities using the solution provided at refresh_token.md. Notable changes:
- RefreshTokenMiddleware.cs
- Adding middleware in Startup.cs
By default Okta mints id_tokens with a 60 minute expiry time. This is the value ASP.NET uses to create a users session. In order for ASP.NET to refresh a users tokens, a users needs to be actively accessing the application and a decision of when to refresh tokens needs to be implemented. In this sample a refresh is done in the last 15 minutes of session lifetime. This can be modified as needed. There is also non-production ready sample to show how JS could actively send a heartbeat to the application to keep a session active if it is desired to allow long idle times by users.
Before running this sample, you will need the following:
- An Okta Developer Account, you can sign up for one at https://developer.okta.com/signup/.
- An Okta Application, configured for Web mode. This is done from the Okta Developer Console and you can find instructions here. When following the wizard, use the default properties. They are designed to work with our sample applications.
Clone this repo and replace the okta configuration placeholders in the Web.Config
with your configuration values from the Okta Developer Console.
You can see all the available configuration options in the okta-aspnet GitHub.
For step-by-step instructions, visit the Okta ASP.NET MVC quickstart. The quickstart will guide you through adding Okta login to your ASP.NET application.
Now start your server and navigate to https://localhost:44314 in your browser.
If you see a home page that allows you to login, then things are working! Clicking the Log in link will redirect you to the Okta hosted sign-in page.
You can login with the same account that you created when signing up for your Developer Org, or you can use a known username and password from your Okta Directory.
Notes: If you are currently using your Developer Console, you already have a Single Sign-On (SSO) session for your Org. You will be automatically logged into your application as the same user that is using the Developer Console. You may want to use an incognito tab to test the flow from a blank slate.
Because of recent changes in Set-Cookie behavior (SameSite) this code will only work properly if it's configured to use https. Check out Work with SameSite cookies in ASP.NET for more details.