Change the identity from Azure AD to identity of application and return new token
Clash 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
- Add Azure AD middleware
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);
);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();
);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,
);
c# authentication asp.net-web-api owin
add a comment |Â
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
- Add Azure AD middleware
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);
);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();
);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,
);
c# authentication asp.net-web-api owin
add a comment |Â
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
- Add Azure AD middleware
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);
);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();
);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,
);
c# authentication asp.net-web-api owin
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
- Add Azure AD middleware
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);
);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();
);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,
);
c# authentication asp.net-web-api owin
asked Jun 21 at 9:17
Troopers
1111
1111
add a comment |Â
add a comment |Â
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password