oauth
27 TopicsModern Authentication (Oauth/OIDC)
The Significance of OAuth 2.0 and OIDC in Contemporary Society. In today's digital landscape, securing user authentication and authorization is paramount. Modern authentication protocols like OAuth 2.0 and OpenID Connect (OIDC) have become the backbone of secure and seamless user experiences. This blog delves into the roles of OAuth 2.0 and OIDC, their request flows, troubleshooting scenarios and their significance in the modern world. Why Oauth 2.0? What problem does it solve? Let's compare Oauth to traditional Forms based Authentication. Aspect OAuth Forms Authentication Password Sharing Eliminates the need for password sharing, reducing credential theft risk. Requires users to share passwords, increasing the risk of credential theft. Access Control Provides granular access control, allowing users to grant specific access to applications. Limited access control, often granting full access once authenticated. Security Measures Enhanced security measures, creating a safer environment for authentication. Susceptible to phishing attacks and credential theft. User Experience Simplifies login processes, enhancing user experience. Can lead to user password fatigue and weak password practices. Credential Storage Does not require storing user credentials, reducing the risk of breaches. Requires secure storage of user credentials, which can be challenging. Session Hijacking Provides mechanisms to prevent session hijacking. Vulnerable to session hijacking, where attackers steal session cookies. OAuth 2.0 Overview OAuth 2.0 is an authorization framework that allows third-party applications to obtain limited access to user resources without exposing user credentials. It provides a secure way for users to grant access to their resources hosted on one site to another site without sharing their credentials. OAuth 2.0 Request Flow Here’s a simplified workflow: Authorization Request: The client application redirects the user to the authorization server, requesting authorization. User Authentication: The user authenticates with the authorization server. Authorization Grant: The authorization server redirects the user back to the client application with an authorization code. Token Request: The client application exchanges the authorization code for an access token by making a request to the token endpoint. Token Response: The authorization server returns the access token to the client application, which can then use it to access protected resources. Let’s take an Example to depict the above Authorization code flow. Consider a front-end .NET core application which is built to make a request to Auth server to secure the token. (i.e. Auth token) the token then will be redeemed to gain access token and passed on to an API to get simple weather details. 1. In program.cs we will have the following code. builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" }) .AddDownstreamApi("Weather", builder.Configuration.GetSection("Weather")) .AddInMemoryTokenCaches(); The above code configures the application to use Microsoft Identity for authentication, acquire tokens to call downstream APIs, and cache tokens in memory. AddMicrosoftIdentityWebApp This line Registers OIDC auth scheme. It reads the Azure AD settings from the AzureAd section of the configuration file (e.g., appsettings.json). This setup allows the application to authenticate users using Azure Active Directory. EnableTokenAcquisitionToCallDownstreamApi This line enables the application to acquire tokens to call downstream APIs. The user.read scope is specified, which allows the application to read the user's profile information. This is essential for accessing protected resources on behalf of the user. AddDownstreamApi This line configures a downstream API named "Weather". It reads the configuration settings for the Weather API from the Weather section of the configuration file. This setup allows the application to call the Weather API using the acquired tokens. AddInMemoryTokenCaches This line adds an in-memory token cache to the application. Token caching is crucial for improving performance and reducing the number of token requests. By storing tokens in memory, the application can reuse them for subsequent API calls without needing to re-authenticate the user. 2. In applicationsettings.json we will have the following. "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "Domain name", "TenantId": "Add tenant ID", "ClientId": "Add client ID", "CallbackPath": "/signin-oidc", "Scopes": "user.read", "ClientSecret": "", "ClientCertificates": [] }, In the home controller we can inject the IDownstreamApi field into home default constructor. private IDownstreamApi _downstreamApi; private const string ServiceName = "Weather"; public HomeController(ILogger<HomeController> logger, IDownstreamApi downstreamApi) { _logger = logger; _downstreamApi = downstreamApi; } 3. The following section makes an API call. public async Task<IActionResult> Privacy() { try { var value = await _downstreamApi.CallApiForUserAsync(ServiceName, options => { }); if (value == null) { return NotFound(new { error = "API response is null." }); } value.EnsureSuccessStatusCode(); // Throws if response is not successful string jsonContent = await value.Content.ReadAsStringAsync(); return Content(jsonContent, "application/json"); // Sends raw JSON as is } catch (HttpRequestException ex) { return StatusCode(500, new { error = "Error calling API", details = ex.Message }); } } The above code will make sure to capture the token by making call to Identity provider and forward the redeemed access token (i.e. Bearer token) to the backend Api. 4. Now let’s see the setup at the Web Api: In program.cs we will have the following code snippet. var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); Followed by Appsettings.json. "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "Domain name", "TenantId": “Add tenant id", "ClientId": "Add client id.", "CallbackPath": "/signin-oidc", "Scopes": "user.read", "ClientSecret": "", "ClientCertificates": [] }, In the controller we can have the following. namespace APIOauth.Controllers { [Authorize(AuthenticationSchemes = "Bearer")] [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; To drill down the request flow let’s capture a fiddler: Step 1: First 2 calls are made by the application to openid-configuration and Keys end points. The first step is crucial as the application requires Open id configuration to know what configuration it has and what are the supported types. Example: Claims supported; scopes_supported, token_endpoint_auth_methods_supported, response mode supported etc… Secondly the keys endpoint provides all the public keys which can later be used to Decrypt the token received. Step 2: Once we have the above config and keys the application now Redirects the user to identity provider with the following parameters. Points to be noted in the above screen is the response_type which is code (Authorization code) and the response_mode is Form_post. Step 3: The subsequent request is the Post requests which will have the Auth code in it. Step 4: In this step we will redeem the auth code with access token. Request is made by attaching the auth code along with following parameters. Response is received with an access token. Step 5: Now the final call is made to the Api along with the access token to get weather details. Request: Response: This completes the Oauth Authorization code flow. Let us now take a moment to gain a brief understanding of JWT tokens. JWTs are widely used for authentication and authorization in modern web applications due to their compact size and security features. They allow secure transmission of information between parties and can be easily verified and trusted. Structure A JWT consists of three parts separated by dots (.), which are: Header: Contains metadata about the type of token and the cryptographic algorithms used. Payload: Contains the claims. Claims are statements about an entity (typically, the user) and additional data. Signature: Ensures that the token wasn't altered. It is created by taking the encoded header, the encoded payload, a secret, the algorithm specified in the header, and signing that. Here is an example of a JWT: OpenID Connect. (OIDC) OIDC Overview OpenID Connect is an authentication layer built on top of OAuth 2.0. While OAuth 2.0 handles authorization, OIDC adds authentication, allowing applications to verify the identity of users and obtain basic profile information. This combination ensures both secure access and user identity verification. OIDC Request Flow OIDC extends the OAuth 2.0 authorization code flow by adding an ID token, which contains user identity information. Here’s a simplified workflow: Authorization Request: The client application redirects the user to the authorization server, requesting authorization and an ID token. User Authentication: The user authenticates with the authorization server. Authorization Grant: The authorization server redirects the user back to the client application with an authorization code. Token Request: The client application exchanges the authorization code for an access token and an ID token by making a request to the token endpoint. Token Response: The authorization server returns the access token and ID token to the client application. The ID token contains user identity information, which the client application can use to authenticate the user. Example: Consider .Net core application which is setup for user Authentication. Let’s see the workflow. Let’s capture a fiddler once again to see the authentication flow: Step 1: & Step 2: would remain same as we saw in Authorization code flow. Making a call to OpenID configuration & making a call to Keys Endpoint. Step 3: Response type here is “ID token” and not a Auth code as we saw in Authorization code flow. This is an implicit flow since we are not redeeming or exchanging an Auth code. Also, an Implicit flow doesn't need a client secret. Step 4: In a post request to browser, we will receive an ID token. This completes the implicit code flow which will result in getting the ID token to permit the user to the application. Common Troubleshooting Scenarios Implementing OAuth in ASP.NET Core can sometimes present challenges. Here are some common issues and how to address them: 1. Misconfigurations Misconfigurations can lead to authentication failures and security vulnerabilities. For example, loss of internet connection or incorrect settings in the OAuth configuration can disrupt the authentication process. One example which we have faced is servers placed in “DMZ” with no internet access. Server need to make an outbound call to login.microsoft.com or identity provider for getting the metadata for openId/Oauth. 2. Failures due to server farm setup. Loss of saving Data protection keys on different workers. Data protection is used to protect Cookies. For server farm the data protection keys should be persisted and shared. One common issue with data protection keys in OAuth flow is the synchronization of keys across different servers or instances. If the keys are not synchronized correctly, it can result in authentication failures and disrupt the OAuth flow. In memory token caches can also cause re-authentication since the user token might exist in other workers or get purged after a restart. 3. Token Expiration Token expiration can disrupt user sessions and require re-authentication, which can frustrate users. It's essential to implement token refresh functionality to enhance user experience and security. 4. Redirect URI Mismatches Redirect URI mismatches can prevent applications from receiving authorization cods, causing login failures. Ensure that the redirect URI specified in the identity provider’s settings matches the one in your application. 5. Scope Misconfigurations Improperly configured scopes can result in inadequate permissions and restrict access to necessary resources. It's crucial to define the correct scopes to ensure that applications have the necessary permissions to access resources. By understanding these common pitfalls and implementing best practices, developers can successfully integrate OAuth into their ASP.NET Core applications, ensuring a secure and seamless user experience. References: Call a web API from a web app - Microsoft identity platform | Microsoft Learn Microsoft identity platform and OAuth 2.0 authorization code flow - Microsoft identity platform | Microsoft Learn OpenID Connect (OIDC) on the Microsoft identity platform - Microsoft identity platform | Microsoft Learn I hope it helps!1.9KViews2likes1CommentEnabling OAuth in Azure DevOps Webhooks
Your message is well-written and clear. Here's a minor adjustment for improved flow: Hello Azure Support Team, I hope this message finds you well. Currently, we're encountering a 401 Unauthorized error when attempting to authenticate our Azure Function App with Azure AD on Azure DevOps (ADO) Webhooks. This issue arises because ADO Webhooks only support Basic Authentication. Consequently, we are requesting the addition of a feature that enables the usage of OAuth2 in ADO Webhooks. This addition would resolve authentication issues, particularly when our Function App is integrated with Azure AD. Currently, we are using Basic Authentication, but this does not align with our internal standard security measures. We hope that this feature will be added to ADO Webhooks.511Views1like1CommentEvolution with business account (oauth2)
Recently domainFactory migrated mail to Microsoft 365 business accounts. I used to use the Evolution mail client (Fedora Linux, flatpak version) for mail. Unfortunately I am not able to login to my account with Evolution. You can find my discussion here: https://gitlab.gnome.org/GNOME/evolution-data-server/-/issues/515#note_2384010 I also noticed that the login is no problem with a personal account. Does anybody have experience with this?784Views0likes5CommentsGet refresh token of Teams Desktop of the current user
The Teams client must store access and refresh tokens somewhere (probably encrypted in the local or session storage of the underlying browser) I am wondering, if there is a way to read those tokens, especially the refresh token that Teams uses to call its Apis in the background. If I open the Teams developer tools, I can not find the token in any of the requests. And Fiddler seems to block Teams and there is no easy way to sniff the traffic produced by the client- do you have any other idea? Why do I need this? I need this token to write a script that uses the unofficial Teams api (not the graph). I want to use this API to create a link to a certain SharePoint library in all my Teams (it used to be called "Add cloud storage") This option is not available in the Graph and therefore I have to use the unofficial Teams Api to create those references programmatically. Getting a token for it (via authorization code flow) seems only possible with the Teams client itself.638Views1like8CommentsAccount Hacked
Hello Community, My account has been hacked, copied and/or duplicated with some other account as I was originally Sids1 with this email for more than 6 months now and this has changed somehow. It's very concerning to me since I also found some other person named Siddhartha when I was logging into my account. I reported that to the Microsoft Account Team but have not received any replies yet. Please suggest anything that can be done to catch this hacker who is stealing my identity to and fro. Best Regards Siddhartha SharmaSolved869Views1like3CommentsEdge extensions -- chrome.identity API is not a good UX
I am developing an Edge extension that connects to a Google account. So far, I've managed to connect using `chrome.identity.launchWebAuthFlow()`, but the user experience is not good -- I am forced to reconnect every hour to retrieve a new access token. In Chrome this is not a problem because it supports `chrome.identity.getAuthToken()`, which handles token refresh automatically. Is there a solution where the user doesn't have to reconnect their Google account every hour?557Views0likes0CommentsExternal oAuth for bot/message extension app
I have created a bot/message extension app using teams toolkit in visual studio code in typescript language. I want to add authentication using oauth for GitHub. I have check a doc but it seems to be for a tab app. https://learn.microsoft.com/en-us/microsoftteams/platform/tabs/how-to/authentication/auth-oauth-provider Please help on how I can do oAuth authentication for the Github provider for bot/msg extension app then use the GitHub APIs.....614Views0likes3CommentsMissing session cookie (*****) in consent redirect request.
Hi, I've a message extension develop for MS Teams and I get this error in the OAuth 2.0 flow. The flow is: 1. Get sign in button in Message Extension 2. Go to our IdP screen and provide the email 3. Get a link in your e-mail address to continue with the authentication 4. Press the link and get this error. I don't see any docs regarding this error. I assume that some parameter is missing in the link generated. Can someone point any ideas on what is this or how to solve this issue?1KViews1like1Comment