Integrate Google OpenID with Swagger in .NET 6 - asp.net

I want to authenticate in my application using Google OpenID. I added authentication in Swagger, but after successfully redirection, login and redirection back to my Swagger, requests are only send access_token in header, but not id_token which is supposed to include e.g. user email (I used https://www.googleapis.com/auth/userinfo.email scope). Is there an option to get this id_token to correctly authenticate in .NET app? I'm using implicit flow right now. There is my Swagger configuration:
services.AddSwaggerGen(c =>
{
c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
},
Scheme = "oauth2",
Name = "authorization",
In = ParameterLocation.Header
},
new List <string> ()
}
});
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Implicit= new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri($"https://accounts.google.com/o/oauth2/auth"),
TokenUrl = new Uri($"https://oauth2.googleapis.com/token"),
Scopes = new Dictionary<string, string>
{
{
$"https://www.googleapis.com/auth/userinfo.email",
"Get email"
}
}
}
}
});
The request looks following:
Request with access_token
I read that there is a possibility to change default authorization parameter in Swagger. So after adding following configuration:
Extensions = new Dictionary<string, IOpenApiExtension>
{
{
"x-tokenName", new OpenApiString("id_token")
}
}
result was still inappropriate:
Request with id_token

Related

Swagger OAuth, how to send bearer token in a different header than "Authorization"

I have an API with authorization code flow authentication and I have configured swagger to use that as a security definition and it works fine.
Now I need swagger to send the bearer token in a different header as well, besides "Authorization", e.g. "X-Forwarded-Authorization". Is there a way to do that?
My current security configuration:
setup.AddSecurityDefinition(
"oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("..."),
TokenUrl = new Uri("..."),
Scopes = { }
}
},
});
You can configure swagger when adding service collection like this;
services.AddSwaggerGen(options =>
{
//...other configurations
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field!",
Name = "X-Forwarded-Authorization",
Type = SecuritySchemeType.ApiKey
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}, Array.Empty<string>()
}
});
//...other configurations
});

Firebase google auth in Swagger (Swashbuckle.AspNetCore)

Trying to implement firebase google authentication in the swagger
onboard: asp.net core 5, Swashbuckle.AspNetCore 6.3.1,
In fairbase console > authentication > Sign-in method > authentication via google is enabled
On ServiceConfigure method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyApi", Version = "v1" });
c.UseInlineDefinitionsForEnums();
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
//email and password authentication - works fine
Password = new OpenApiOAuthFlow
{
TokenUrl = new Uri("/api/v1/auth/password", UriKind.Relative), //here my backend endpoint
Extensions = new Dictionary<string, IOpenApiExtension>
{
{ "returnSecureToken", new OpenApiBoolean(true) },
},
},
//try add google auth - troble here
Implicit = new OpenApiOAuthFlow()
{
//Not sure about the endpoints. Its not work with 404 err
AuthorizationUrl = new Uri("https://securetoken.google.com/MY-PROJECT-FIREBASE-NAME"),
TokenUrl = new Uri("https://securetoken.google.com/MY-PROJECT-FIREBASE-NAME"),
Scopes = new Dictionary<string, string>
{
{ "profile", "profile" },
}
}
}
});
c.OperationFilter<AuthorizeCheckOperationFilter>();
});
class filter:
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var requiredScopes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.OfType<AuthorizeAttribute>()
.Select(attr => attr.Policy)
.Distinct();
if (requiredScopes.Any())
{
var oAuthScheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
};
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[ oAuthScheme ] = requiredScopes.ToList()
}
};
}
}
}
in Configure method:
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyApi v1");
What endpoints for AuthorizationUrl / TokenUrl should call?
Any additinal options for swagger?
I`m new in Firebase. M.b. need aditional adjustments in firebase console?
I would be very appreciate for a code sample.
I found a good repo for you. This simple is .NET 5 WebApi project base with the following features implemented:
Swagger with Firebase login
Serilog Logging to Amazon CloudWatch
Encrypted fields in AppSettings
Soft Delete and Audit Columns
Multitenancy support
Data Seeding
Localization
code sample:clean-base-api

'Invalid token' when using webapi thru Swagger authenticated by Azure AD

I try to use AAD authentification on my WebApi (dotnet core 3.1) from swagger (Swashbuckle) client.
In my Startup class, I've configured like follow:
// Configure authentication
services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
my settings for AzureAd:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "xxxx-xxxxx1b",
"Domain": "myoffice.onmicrosoft.com",
"TenantId": "xxxxx-xxxxa5",
"Scope": "api://xxxxxxxx-abc3cff48f1b/Full.Access",
"ScopeDescription": "Full Access"
},
...
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Type = SecuritySchemeType.OAuth2,
In = ParameterLocation.Header,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow
{
TokenUrl = new Uri($"Configuration["AzureAd:Instance"]}/{Configuration["AzureAd:TenantId"]}/oauth2/v2.0/token"),
AuthorizationUrl = new Uri($"{Configuration["AzureAd:Instance"]}/{Configuration["AzureAd:TenantId"]}/oauth2/v2.0/authorize"),
Scopes =
{
{
Configuration["AzureAd:Scope"],Configuration["AzureAd:ScopeDescription"]
}
}
}
}
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
And in my Configure method:
app.UseSwaggerUI(c =>
{
c.RoutePrefix = string.Empty;
c.SwaggerEndpoint($"/swagger/{ApiVersion}/swagger.json", ApiName);
c.OAuthClientId(Configuration["AzureAd:ClientId"]);
c.OAuthScopeSeparator(" ");
});
Swagger corectly log to AAD using my credential and when I use a route protected by [Authorize] the token is correcly sent to the API by I receive a 401 error with the following message:
www-authenticate: Bearer error="invalid_token"error_description="The issuer 'https://login.microsoftonline.com/{tenantid}/v2.0' is invalid"
The url https://login.microsoftonline.com/{tenantid}/v2.0 is in the token in the iss section.
What is wrong?
According to your error and your code, you do not tell your application the ValidIssuer. So you get the error. Please add the following code in the method ConfigureServices of startup.cs file
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuers = new[] {
},
});
For example
Configure Azure AD for your web API. For more details, please refer to the document
a. Create Azure AD web api application
b. Expose API
c. Configure code
config file
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",
"TenantId": "<your tenant id>"
},
Add following code in the Stratup.cs
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
options.Authority += "/v2.0";
options.TokenValidationParameters = new TokenValidationParameters
{
/**
* with the single-tenant application, you can configure your issuers
* with the multiple-tenant application, please set ValidateIssuer as false to disable issuer validation
*/
ValidIssuers = new[] {
$"https://sts.windows.net/{Configuration["AzureAD:TenantId"]}/",
$"https://login.microsoftonline.com/{Configuration["AzureAD:TenantId"]}/v2.0"
},
ValidAudiences = new[]
{
options.Audience,
$"api://{options.Audience}"
}
};
});
Configure swagger. For more details, please refer to the blog.
a. Create Azure Web application
b. Configure API permissions. Regarding how to configure, you can refer to the document
c. code
Install SDK
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
config file
"Swagger": {
"ClientId": ""
},
Add the following code to Startup.cs in the ConfigureServices method:
services.AddSwaggerGen(o =>
{
// Setup our document's basic info
o.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Protected Api",
Version = "1.0"
});
// Define that the API requires OAuth 2 tokens
o.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Implicit = new OpenApiOAuthFlow
{
Scopes = new Dictionary<string, string>
{
{ "api://872ebcec-c24a-4399-835a-201cdaf7d68b/user_impersonation","allow user to access api"}
},
AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{Configuration["AzureAD:TenantId"]}/oauth2/v2.0/authorize"),
TokenUrl = new Uri($"https://login.microsoftonline.com/{Configuration["AzureAD:TenantId"]}/oauth2/v2.0/token")
}
}
});
o.AddSecurityRequirement(new OpenApiSecurityRequirement{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference{
Id = "oauth2",
Type = ReferenceType.SecurityScheme
}
},new List<string>()
}
});
});
Add the following code to the Configure method:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.OAuthClientId(Configuration["Swagger:ClientId"]);
c.OAuthScopeSeparator(" ");
c.OAuthAppName("Protected Api");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
Test

PostLogoutRedirectUri always null in identity Server 4 with SPA (Angular 7 OIDC client)

Using the facebook login authentication in angular app with identity server 4. On logout method PostLogoutRedirectUri , ClientName, LogoutId is always null.
private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId)
{
// get context information (client name, post logout redirect URI and iframe for federated signout)
var logout = await _interaction.GetLogoutContextAsync(logoutId);
var vm = new LoggedOutViewModel
{
AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut,
PostLogoutRedirectUri = logout?.PostLogoutRedirectUri,
ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName,
SignOutIframeUrl = logout?.SignOutIFrameUrl,
LogoutId = logoutId
};
if (User?.Identity.IsAuthenticated == true)
{
var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value;
if (idp != null && idp != IdentityServer4.IdentityServerConstants.LocalIdentityProvider)
{
var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp);
if (providerSupportsSignout)
{
if (vm.LogoutId == null)
{
// if there's no current logout context, we need to create one
// this captures necessary info from the current logged in user
// before we signout and redirect away to the external IdP for signout
vm.LogoutId = await _interaction.CreateLogoutContextAsync();
}
vm.ExternalAuthenticationScheme = idp;
}
}
}
return vm;
}
Angular oidc clident code
logout(): Promise<any> {
return this._userManager.signoutRedirect();
}
Client setup
public IEnumerable<Client> GetClients()
{
var client = new List<Client>
{
new Client
{
ClientId = ConstantValue.ClientId,
ClientName = ConstantValue.ClientName,
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
RedirectUris = { string.Format("{0}/{1}", Configuration["IdentityServerUrls:ClientUrl"], "assets/oidc-login-redirect.html"), string.Format("{0}/{1}", Configuration["IdentityServerUrls:ClientUrl"], "assets/silent-redirect.html") },
PostLogoutRedirectUris = { string.Format("{0}?{1}", Configuration["IdentityServerUrls:ClientUrl"] , "postLogout=true") },
AllowedCorsOrigins = { Configuration["IdentityServerUrls: ClientUrl"] },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
ConstantValue.ClientDashApi
},
IdentityTokenLifetime=120,
AccessTokenLifetime=120
},
};
return client;
}
logoutId is always null. I am successfully able to login to facebook return to the callback method. But redirect uri is always null.
Reference
IdentityServer4 PostLogoutRedirectUri null
This may not be your issue, but it was my issue when I got the same error as you so I am posting my own experience here.
I was following along in a Pluralsight video that was constructing an Angular app using IdentityServer4 as the STS Server, and it directed me to set the post_logout_redirect_uri in the configuration for my UserManager in the AuthService I was constructing, like so:
var config = {
authority: 'http://localhost:4242/',
client_id: 'spa-client',
redirect_uri: `${Constants.clientRoot}assets/oidc-login-redirect.html`,
scope: 'openid projects-api profile',
response_type: 'id_token token',
post_logout_redirect_uri: `${Constants.clientRoot}`,
userStore: new WebStorageStateStore({ store: window.localStorage })
}
this._userManager = new UserManager(config);
An old issue at the github repo https://github.com/IdentityServer/IdentityServer4/issues/396 discussed the fact that this is set automatically now and doesn't need to be set explicitly (see the end of the thread). Once I removed that from the configuration I no longer had the issue where logoutId was null in the AccountController's Logout method:
/// <summary>
/// Show logout page
/// </summary>
[HttpGet]
public async Task<IActionResult> Logout(string logoutId)
So this was the correct setup for the config for me:
var config = {
authority: 'http://localhost:4242/',
client_id: 'spa-client',
redirect_uri: `${Constants.clientRoot}assets/oidc-login-redirect.html`,
scope: 'openid projects-api profile',
response_type: 'id_token token',
userStore: new WebStorageStateStore({ store: window.localStorage })
}
this._userManager = new UserManager(config);
I had a similar issue and for a few hours I was lost. In my case the value/url I had in angular for post_logout_redirect_uri (in the UserManagerSettings) was different than the value/url I had in my IdentityServer4 in the field PostLogoutRedirectUris of the Client configuration. I messed up the routes. It's a silly mistake but sometimes you miss the simple things.

.NET Web API 2 OWIN Bearer Token Authentication

I'm implementing a Web API 2 service architecture in my .NET web application. The client consuming the requests is pure javascript, no mvc/asp.net. I'm using OWIN to try to enable token authentication per this article OWIN Bearer Token Authentication with Web API Sample. I seem to be missing something with the authentication step after its authorized.
My login looks like:
[HttpPost]
[AllowAnonymous]
[Route("api/account/login")]
public HttpResponseMessage Login(LoginBindingModel login)
{
// todo: add auth
if (login.UserName == "a#a.com" && login.Password == "a")
{
var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, login.UserName));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
UserName = login.UserName,
AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)
}, Configuration.Formatters.JsonFormatter)
};
}
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
It returns
{
accessToken: "TsJW9rh1ZgU9CjVWZd_3a855Gmjy6vbkit4yQ8EcBNU1-pSzNA_-_iLuKP3Uw88rSUmjQ7HotkLc78ADh3UHA3o7zd2Ne2PZilG4t3KdldjjO41GEQubG2NsM3ZBHW7uZI8VMDSGEce8rYuqj1XQbZzVv90zjOs4nFngCHHeN3PowR6cDUd8yr3VBLdZnXOYjiiuCF3_XlHGgrxUogkBSQ",
userName: "a#a.com"
}
Then I try to set the HTTP header Bearer on further requests in AngularJS like:
$http.defaults.headers.common.Bearer = response.accessToken;
to a API like:
[HttpGet]
[Route("api/account/profile")]
[Authorize]
public HttpResponseMessage Profile()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
UserName = User.Identity.Name
}, Configuration.Formatters.JsonFormatter)
};
}
but no matter what I do this service is 'unauthorized'. Am I missing something here?
Resolved by setting header 'Authorization' with Bearer + token like:
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token.accessToken;
You can configure it with your angular application module. So authorization token will be set as header for every http request.
var app = angular.module("app", ["ngRoute"]);
app.run(function ($http) {
$http.defaults.headers.common.Authorization = 'Bearer ' + token.accessToken;
});

Resources