Where is app.UseOpenIdConnectAuthentication() and OpenIdConnectMiddleware in ASP.NET Core 3? - asp.net-core

Context
I am trying to migrate an application which uses app.UseOpenIdConnectAuthentication() but this extension method not found in package Microsoft.AspNetCore.Authentication.OpenIdConnect
The actual source of this extension method uses the class OpenIdConnectMiddleware which also seems to be gone.
Question
How can I migrate this application?

Change your startup file to the example below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = "oidc";
options.DefaultSignInScheme = "Cookies";
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc-client";
options.ClientSecret = "secret-key";
options.ResponseType = "id_token token";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
});
}

Related

2 openid connect in asp.net core application

I've been trying to add second identity provider to my web app, but have a problem with the configuration.
The app has the folowing configuration
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = "cookie";
options.DefaultSignInScheme = "cookie";
options.DefaultChallengeScheme = "oidc";
options.DefaultSignOutScheme = "oidc";
})
.AddCookie("cookie")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = AppConfig.AuthorizationServerAdress;
options.ClientId = AppConfig.OpenidApp;
options.ClientSecret = AppConfig.OpenidAppSecret;
options.ResponseType = OpenIdConnectResponseType.Code;
options.ResponseMode = OpenIdConnectResponseMode.Query;
options.UsePkce = true;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
})
.AddCookie("cookie2")
.AddOpenIdConnect("oidc2", options =>
{
options.Authority = AppConfig.AuthorizationExternalServerAdress;
options.ClientId = AppConfig.OpenidExternalApp;
options.ClientSecret = AppConfig.OpenidExternalAppSecret;
options.ResponseType = OpenIdConnectResponseType.Code;
options.ResponseMode = OpenIdConnectResponseMode.Query;
options.UsePkce = true;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
});
It works by default with the first oidc provider, but if I use oidc2 to log in and then navigate to my app, I'll go to my default oidc provider. It means that the second provider will be ignored.
Can somebody help me with the configuration, please?
The problem is that both handlers will listen for the callback request from your identityprovider on URL /signin-oidc
So, to solve it, you need to make sure they are different, like:
.AddOpenIdConnect("oidc", options =>
{
//other options
options.CallbackPath = new PathString("/oidc/handler1");
}
.AddOpenIdConnect("oidc2", options =>
{
//other options
options.CallbackPath = new PathString("/oidc/handler2");
}
also, see OpenIdConnect: Manually handle Callback
But, in general I advice that your clients and apps only should trust one provider (token issuer) and let users choose how to authenticate through your primary provider, like in this picture:

ABP Framework API Scope

I cloned MicroserviceDemo solution, before run project PublicWebsite.Host, I commented below code in PublicWebSiteHostModule.cs, but why PublicWebsite.Host still can access PublicWebSiteGateway, ProductService and BloggingService? In my view, I think app only access to required scopes. (Other hand, comment or don't comment below code, PublicWebsite.Host still run correctly. Sorry for my English).
Thanks you!
context.Services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(365);
})
.AddOpenIdConnect("oidc", options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.ClientId = configuration["AuthServer:ClientId"];
options.ClientSecret = configuration["AuthServer:ClientSecret"];
options.RequireHttpsMetadata = false;
options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("role");
options.Scope.Add("email");
options.Scope.Add("phone");
//options.Scope.Add("PublicWebSiteGateway");
//options.Scope.Add("ProductService");
//options.Scope.Add("BloggingService");
options.ClaimActions.MapAbpClaimTypes();
});

MVC.NET core 2 custom login controller

Is it possible to create a custom login form in the MVC "client" (.net core 2)
by issuing a token from auth server (Identity server 4) and set the token/credentials to the MVC pipeline for authorization?
Auth server:
new Client{
ClientId = "MVC",
ClientName = "MVC",
RequireClientSecret = true,
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets = {
new Secret("secret".Sha256())
},
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"roles",
configuration["AUTHENTICATION_SCOPE:SCOPE_ID"],
},
AllowOfflineAccess = true,
AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true,
AccessTokenType = AccessTokenType.Reference,
AccessTokenLifetime = int.Parse(configuration["AccessTokenLifetime"]),
AbsoluteRefreshTokenLifetime = int.Parse(configuration["AbsoluteRefreshTokenLifetime"])}
MVC Client:
Startup.cs
public void ConfigureServices(IServiceCollection services){
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "...";
options.RequireHttpsMetadata = false;
options.GetClaimsFromUserInfoEndpoint = true;
options.ClientId = "MVC";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
}).AddCookie(options =>
{
options.LoginPath = new PathString("/Account/Login/");
options.LogoutPath = new PathString("/Account/Logout/");
options.AccessDeniedPath = new PathString("/Account/Login/");
});}
AccountController.cs
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel vm, string button){
if (!ModelState.IsValid)
return View(vm);
//HOW TO CONTINUE FROM HERE?
//Issue token from auth server and set it in the HttpContext.Authentication?}

ASP.NET Authorize Filter Denies Access for User in Specified Role

In my ASP.NET Core 2.0 Application, I am stuck with an issue an Admin logged in User cannot access controller I used the Authorize Filter on [Authorize(Policy="AdminAlone")].
I confirmed that the user is in the "Administrators" role and added the policy in startup.cs but it redirects to an AccessDenied view when I try to access the controller.
I saw a similar problem on this link, but the solution didn't help me
Startup Class in MVC Client - ConfigureServices
services.AddMvc();
services.AddSession();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthorization(options =>
{
options.AddPolicy("AdminAlone", policy => policy.RequireRole("Administrators"));
});
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie("Cookies")
.AddOpenIdConnect("Bearer", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvcWeb";
options.ClientSecret = "spring12345";
options.ResponseType = OidcConstants.ResponseTypes.CodeIdToken;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("NuB.HospitalSearch");
options.Scope.Add("offline_access");
});
Web API ConfigureServices
var jwtSecurityTokenHandler = new JwtSecurityTokenHandler
{
InboundClaimTypeMap = new Dictionary<string, string>()
};
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(option =>
{
option.Audience = "NuB.HospitalSearch";
option.Authority = "http://localhost:5000";
option.RequireHttpsMetadata = false;
option.SecurityTokenValidators.Clear();
option.SecurityTokenValidators.Add(jwtSecurityTokenHandler);
option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateAudience = true,
ValidAudience = "NuB.HospitalSearch",
ValidateIssuer = true
};
});
You may try the following. Inside your AddOpenIdConnect configuration add
options.TokenValidationParameters = new TokenValidationParameters {
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role
};
In fact, this property defines the types and definitions required for validating a token. Please refer to this post from Dominick Baier for a more detailed explanation.

Cannot use CookieAuthenticaton and openidConnect Authentication in asp.net core 2.0

I have upgraded my project to asp.net core. But now my CookieAuthnetication and OpenIdConnectionAuthentication methods are not working. They have become obsolete.
Startup.cs Configure method
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = "http://localhost:5000",
RequireHttpsMetadata = false,
ClientId = "integapay.client",
ClientSecret = "mySecret",
ResponseType = "code id_token",
Scope = { "openid", "profile", "api.public", "offline_access" },
GetClaimsFromUserInfoEndpoint = true,
SaveTokens = true
});
They moved it into the Conifguration Service Part
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options => SetOpenIdConnectOptions(options));
}
private void SetOpenIdConnectOptions(OpenIdConnectOptions options)
{
options.Authority = Configuration["auth:oidc:authority"];
options.ClientId = Configuration["auth:oidc:clientid"];
options.RequireHttpsMetadata = false;
options.ClientSecret = Configuration["auth:oidc:clientSecret"];
options.SignInScheme = "Cookies";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.ResponseType = "code id_token";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("api_back");
options.Scope.Add("offline_access");
}
In the Configure call you only have to call
app.UseAuthentication();
Hope this helps. :)