Change the identity from Azure AD to identity of application and return new token

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












I use this code to change the identity coming from Azure AD in an identity usable by my application, then i generate a token for this identity and return it in the response headers.



Is this secure? and is it the good way? In particular, call the SignIn method of the AuthenticationManager and handle this in a middleware to generate a token.



Environment



Asp.net-WebAPI with OWIN



Code in startup.cs



  1. Add Azure AD middleware


  2. On validate identity, create a custom identity for the authentified user and signin with this identity



    app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions

    Audience = ConfigurationManager.AppSettings["ida:Audience"],
    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
    Provider = new OAuthBearerAuthenticationProvider()

    OnValidateIdentity = async context =>

    if(!context.IsValidated)
    return;

    var userManager = context.OwinContext.Get<UserManager>();
    string email = context.Ticket.Identity.GetClaimValue(System.Security.Claims.ClaimTypes.Email);
    User user = userManager.GetByEmail(email);

    if(user == null)

    // Create user


    // Create custom identity
    ClaimsIdentity identity = new ClaimsIdentity(AuthenticationTypes.My);
    identity.AddClaim(new Claim(My.ClaimTypes.UserId, user.Id.ToString(CultureInfo.InvariantCulture)));

    // Signal to middleware to treat my custom identity
    context.OwinContext.Authentication.SignIn(identity);

    // validate the identity
    AuthenticationTicket ticket = new AuthenticationTicket(identity, null);
    context.Validated(ticket);


    );



  3. Add a custom middleware to handle the signin with my custom identity to create a new token and return it to browser



    app.Use((context, next) =>

    if(context.Authentication.AuthenticationResponseGrant == null)
    return next();
    if(context.Authentication.AuthenticationResponseGrant.Identity.AuthenticationType != AuthenticationTypes.My)
    return next();

    // Create a token with the custom identity
    AuthenticationTicket ticket = new AuthenticationTicket(context.Authentication.AuthenticationResponseGrant.Identity, null);
    IDataProtector dataProtecter = app.CreateDataProtector(typeof(OAuthBearerAuthenticationMiddleware).Namespace, "Access_Token", "v1");
    TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtecter);
    string token = ticketDataFormat.Protect(ticket);
    context.Response.Headers.Add("access_token", new string token );
    return next();
    );



  4. Add a OAuth bearer authentication middleware to handle my custom token:



    app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions()

    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    AccessTokenFormat = null,
    );







share|improve this question

























    up vote
    2
    down vote

    favorite












    I use this code to change the identity coming from Azure AD in an identity usable by my application, then i generate a token for this identity and return it in the response headers.



    Is this secure? and is it the good way? In particular, call the SignIn method of the AuthenticationManager and handle this in a middleware to generate a token.



    Environment



    Asp.net-WebAPI with OWIN



    Code in startup.cs



    1. Add Azure AD middleware


    2. On validate identity, create a custom identity for the authentified user and signin with this identity



      app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions

      Audience = ConfigurationManager.AppSettings["ida:Audience"],
      Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
      Provider = new OAuthBearerAuthenticationProvider()

      OnValidateIdentity = async context =>

      if(!context.IsValidated)
      return;

      var userManager = context.OwinContext.Get<UserManager>();
      string email = context.Ticket.Identity.GetClaimValue(System.Security.Claims.ClaimTypes.Email);
      User user = userManager.GetByEmail(email);

      if(user == null)

      // Create user


      // Create custom identity
      ClaimsIdentity identity = new ClaimsIdentity(AuthenticationTypes.My);
      identity.AddClaim(new Claim(My.ClaimTypes.UserId, user.Id.ToString(CultureInfo.InvariantCulture)));

      // Signal to middleware to treat my custom identity
      context.OwinContext.Authentication.SignIn(identity);

      // validate the identity
      AuthenticationTicket ticket = new AuthenticationTicket(identity, null);
      context.Validated(ticket);


      );



    3. Add a custom middleware to handle the signin with my custom identity to create a new token and return it to browser



      app.Use((context, next) =>

      if(context.Authentication.AuthenticationResponseGrant == null)
      return next();
      if(context.Authentication.AuthenticationResponseGrant.Identity.AuthenticationType != AuthenticationTypes.My)
      return next();

      // Create a token with the custom identity
      AuthenticationTicket ticket = new AuthenticationTicket(context.Authentication.AuthenticationResponseGrant.Identity, null);
      IDataProtector dataProtecter = app.CreateDataProtector(typeof(OAuthBearerAuthenticationMiddleware).Namespace, "Access_Token", "v1");
      TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtecter);
      string token = ticketDataFormat.Protect(ticket);
      context.Response.Headers.Add("access_token", new string token );
      return next();
      );



    4. Add a OAuth bearer authentication middleware to handle my custom token:



      app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions()

      TokenEndpointPath = new PathString("/token"),
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
      AccessTokenFormat = null,
      );







    share|improve this question





















      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I use this code to change the identity coming from Azure AD in an identity usable by my application, then i generate a token for this identity and return it in the response headers.



      Is this secure? and is it the good way? In particular, call the SignIn method of the AuthenticationManager and handle this in a middleware to generate a token.



      Environment



      Asp.net-WebAPI with OWIN



      Code in startup.cs



      1. Add Azure AD middleware


      2. On validate identity, create a custom identity for the authentified user and signin with this identity



        app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions

        Audience = ConfigurationManager.AppSettings["ida:Audience"],
        Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
        Provider = new OAuthBearerAuthenticationProvider()

        OnValidateIdentity = async context =>

        if(!context.IsValidated)
        return;

        var userManager = context.OwinContext.Get<UserManager>();
        string email = context.Ticket.Identity.GetClaimValue(System.Security.Claims.ClaimTypes.Email);
        User user = userManager.GetByEmail(email);

        if(user == null)

        // Create user


        // Create custom identity
        ClaimsIdentity identity = new ClaimsIdentity(AuthenticationTypes.My);
        identity.AddClaim(new Claim(My.ClaimTypes.UserId, user.Id.ToString(CultureInfo.InvariantCulture)));

        // Signal to middleware to treat my custom identity
        context.OwinContext.Authentication.SignIn(identity);

        // validate the identity
        AuthenticationTicket ticket = new AuthenticationTicket(identity, null);
        context.Validated(ticket);


        );



      3. Add a custom middleware to handle the signin with my custom identity to create a new token and return it to browser



        app.Use((context, next) =>

        if(context.Authentication.AuthenticationResponseGrant == null)
        return next();
        if(context.Authentication.AuthenticationResponseGrant.Identity.AuthenticationType != AuthenticationTypes.My)
        return next();

        // Create a token with the custom identity
        AuthenticationTicket ticket = new AuthenticationTicket(context.Authentication.AuthenticationResponseGrant.Identity, null);
        IDataProtector dataProtecter = app.CreateDataProtector(typeof(OAuthBearerAuthenticationMiddleware).Namespace, "Access_Token", "v1");
        TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtecter);
        string token = ticketDataFormat.Protect(ticket);
        context.Response.Headers.Add("access_token", new string token );
        return next();
        );



      4. Add a OAuth bearer authentication middleware to handle my custom token:



        app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions()

        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        AccessTokenFormat = null,
        );







      share|improve this question











      I use this code to change the identity coming from Azure AD in an identity usable by my application, then i generate a token for this identity and return it in the response headers.



      Is this secure? and is it the good way? In particular, call the SignIn method of the AuthenticationManager and handle this in a middleware to generate a token.



      Environment



      Asp.net-WebAPI with OWIN



      Code in startup.cs



      1. Add Azure AD middleware


      2. On validate identity, create a custom identity for the authentified user and signin with this identity



        app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions

        Audience = ConfigurationManager.AppSettings["ida:Audience"],
        Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
        Provider = new OAuthBearerAuthenticationProvider()

        OnValidateIdentity = async context =>

        if(!context.IsValidated)
        return;

        var userManager = context.OwinContext.Get<UserManager>();
        string email = context.Ticket.Identity.GetClaimValue(System.Security.Claims.ClaimTypes.Email);
        User user = userManager.GetByEmail(email);

        if(user == null)

        // Create user


        // Create custom identity
        ClaimsIdentity identity = new ClaimsIdentity(AuthenticationTypes.My);
        identity.AddClaim(new Claim(My.ClaimTypes.UserId, user.Id.ToString(CultureInfo.InvariantCulture)));

        // Signal to middleware to treat my custom identity
        context.OwinContext.Authentication.SignIn(identity);

        // validate the identity
        AuthenticationTicket ticket = new AuthenticationTicket(identity, null);
        context.Validated(ticket);


        );



      3. Add a custom middleware to handle the signin with my custom identity to create a new token and return it to browser



        app.Use((context, next) =>

        if(context.Authentication.AuthenticationResponseGrant == null)
        return next();
        if(context.Authentication.AuthenticationResponseGrant.Identity.AuthenticationType != AuthenticationTypes.My)
        return next();

        // Create a token with the custom identity
        AuthenticationTicket ticket = new AuthenticationTicket(context.Authentication.AuthenticationResponseGrant.Identity, null);
        IDataProtector dataProtecter = app.CreateDataProtector(typeof(OAuthBearerAuthenticationMiddleware).Namespace, "Access_Token", "v1");
        TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtecter);
        string token = ticketDataFormat.Protect(ticket);
        context.Response.Headers.Add("access_token", new string token );
        return next();
        );



      4. Add a OAuth bearer authentication middleware to handle my custom token:



        app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions()

        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        AccessTokenFormat = null,
        );









      share|improve this question










      share|improve this question




      share|improve this question









      asked Jun 21 at 9:17









      Troopers

      1111




      1111

























          active

          oldest

          votes











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196960%2fchange-the-identity-from-azure-ad-to-identity-of-application-and-return-new-toke%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes










           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196960%2fchange-the-identity-from-azure-ad-to-identity-of-application-and-return-new-toke%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Greedy Best First Search implementation in Rust

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          C++11 CLH Lock Implementation