Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set OWIN redirect uri

I am using OWIN to connect up to O365 via the Microsoft Graph API in an ASP.NET MVC app. Everything is setup in Startup.Auth.cs including the Redirect Uri value which currently comes from the web.config. Authentication is working correctly.

As I am using wildcards in the App Registration, the redirect uri can be a variety of values and te user is able authenticate to O365 from any number of pages in the app. Once authenticated I'd like them to be brought back to the page they were just on but because the redirect uri is already set, they are brought back to that page.

How can I modify the redirect uri, elsewhere in my code, after the OWIN identity context has been created?

Below is a snippet of the startup code.

   public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
            ....                
            app.UseOpenIdConnectAuthentication(
               new OpenIdConnectAuthenticationOptions
               {

                   ClientId = appId,
                   Authority = "https://login.microsoftonline.com/organizations/v2.0",
                   PostLogoutRedirectUri = redirectUri,
                   RedirectUri = redirectUri,
                   Notifications = new OpenIdConnectAuthenticationNotifications
                   {
                       AuthorizationCodeReceived = async (context) =>
                       {

                           Dictionary<string, string> data = new Dictionary<string, string>();
                           data.Add("client_id", appId);
                           data.Add("client_secret", appSecret);
                           data.Add("code", code);
                           data.Add("grant_type", "authorization_code");
                           data.Add("redirect_uri", redirectUri);
                           ...
like image 561
Douglas Anderson Avatar asked Jan 29 '23 01:01

Douglas Anderson


1 Answers

I had a similar situation. I tied into RedirectToIdentityProvider, to modify the RedirectUri before sending the request to the identity provider. Something like the following

Notifications = new OpenIdConnectAuthenticationNotifications()
  { 
    RedirectToIdentityProvider = async (context) =>
      {
        context.ProtocolMessage.RedirectUri = "Whatever_You_Want_Here";
      }
  }
like image 190
CaPorter Avatar answered Feb 06 '23 11:02

CaPorter