skoruba / IdentityServer4.Admin

The administration for the IdentityServer4 and Asp.Net Core Identity
MIT License
3.56k stars 1.15k forks source link

Use Skoruba in My MVC Simple Project #917

Open parlive opened 2 years ago

parlive commented 2 years ago

I want to add an MVC project to the Skoruba template as a new client. In the Sturtup settings of the Mvc project, I did the following: `public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); IdentityModelEventSource.ShowPII = true; services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; options.DefaultSignOutScheme = "oidc"; }) .AddCookie("Cookies", options => { options.AccessDeniedPath = "/Authorization/AccessDenied"; // set session lifetime options.ExpireTimeSpan = TimeSpan.FromHours(8); // sliding or absolute options.SlidingExpiration = false; // host prefixed cookie name options.Cookie.Name = "MVC"; // strict SameSite handling options.Cookie.SameSite = SameSiteMode.Strict; }) .AddOpenIdConnect("oidc", options => { options.SignInScheme = "Cookies"; options.Authority = Configuration["IDPBaseAddress"]; options.ClientId = Configuration["ClientId"]; options.ClientSecret = Configuration["ClientSecret"]; options.ResponseType = "code id_token"; options.ResponseMode = "query";

                options.RequireHttpsMetadata = false;
                options.CallbackPath = new PathString("/Home/");
                options.SignedOutCallbackPath = new PathString("/Home/");

                options.MapInboundClaims = true;

                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("roles");
                options.Scope.Add("PS.WebApi.Read");
                options.Scope.Add("offline_access");

                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;
                //options.UsePkce = true;
                //options.ClaimActions.MapJsonKey(claimType: "role", jsonKey: "role"); // for having 2 or more roles

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.GivenName,
                    RoleClaimType = JwtClaimTypes.Role
                };
            });
        //ServicePointManager.Expect100Continue = true;
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
        //                                       | SecurityProtocolType.Tls11
        //                                       | SecurityProtocolType.Tls12
        //                                       | SecurityProtocolType.Ssl3;
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "areas",
                pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
            );
            //.RequireAuthorization();

            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}"
            );
            //.RequireAuthorization();
        });

        //[HttpPost]
        //public IActionResult Logout()
        //{
        //    return SignOut("Cookies", "oidc");
        //}
    }

` My endpoint projects are as follows: Skoruba.IdentityServer4.Admin = https://localhost:44303 Skoruba.IdentityServer4.STS.Identity = https://localhost:44310 Skoruba.IdentityServer4.Admin.Api = https://localhost:44356 Mvc_Client_Project = https://localhost:44332

Configure My Project MVC Settings (appsettings.json): "WebApiBaseAddress": "https://localhost:44356", "IDPBaseAddress": "https://localhost:44310", "ClientId": "Mvc_ClientId", "ClientSecret": "WebMvc" Contents of the Identityserverdata.json file: ` { "IdentityServerData": { "IdentityResources": [ { "Name": "roles", "Enabled": true, "DisplayName": "Roles", "UserClaims": [ "role" ] }, { "Name": "openid", "Enabled": true, "Required": true, "DisplayName": "Your user identifier", "UserClaims": [ "sub" ] }, { "Name": "profile", "Enabled": true, "DisplayName": "User profile", "Description": "Your user profile information (first name, last name, etc.)", "Emphasize": true, "UserClaims": [ "name", "family_name", "given_name", "middle_name", "nickname", "preferred_username", "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale", "updated_at" ] }, { "Name": "email", "Enabled": true, "DisplayName": "Your email address", "Emphasize": true, "UserClaims": [ "email", "email_verified" ] }, { "Name": "address", "Enabled": true, "DisplayName": "Your address", "Emphasize": true, "UserClaims": [ "address" ] } ], "ApiScopes": [ { "Name": "Idp_Admin_ClientId_api", "DisplayName": "Idp_Admin_ClientId_api", "Required": true, "UserClaims": [ "role", "name" ] }, { "Name": "WebApi.Read", "DisplayName": "WebApi Read", "Required": true, "UserClaims": [ "role", "WebApi.Read" ] }, { "Name": "WebApi.Write", "DisplayName": "WebApi Write", "Required": true, "UserClaims": [ "role", "WebApi.Write" ] } ], "ApiResources": [ { "Name": "Idp_Admin_ClientId_api", "Scopes": [ "Idp_Admin_ClientId_api" ] }, { "Name": "WebApi", "Scopes": [ "WebApi.Read", "WebApi.Write" ] } ], "Clients": [ { "ClientId": "Idp_Admin_ClientId", "ClientName": "Idp_Admin_ClientId", "ClientUri": "https://localhost:44303", "AllowedGrantTypes": [ "authorization_code" ], "RequirePkce": true, "ClientSecrets": [ { "Value": "Idp_Admin_ClientSecret" } ], "RedirectUris": [ "https://localhost:44303/signin-oidc" ], "FrontChannelLogoutUri": "https://localhost:44303/signout-oidc", "PostLogoutRedirectUris": [ "https://localhost:44303/signout-callback-oidc" ], "AllowedCorsOrigins": [ "https://localhost:44303" ], "AllowedScopes": [ "openid", "email", "profile", "roles" ] }, { "ClientId": "Idp_Admin_ClientId_api_swaggerui", "ClientName": "Idp_Admin_ClientId_api_swaggerui", "AllowedGrantTypes": [ "authorization_code" ], "RequireClientSecret": false, "RequirePkce": true, "RedirectUris": [ "https://localhost:44302/swagger/oauth2-redirect.html" ], "AllowedScopes": [ "Idp_Admin_ClientId_api" ], "AllowedCorsOrigins": [ "https://localhost:44302" ] }, //WebApi { "ClientId": "WebApi_ClientId", "ClientName": "WebApi_ClientId", "ClientUri": "https://localhost:44365", "AllowedGrantTypes": [ "authorization_code" ], "RequirePkce": true, "ClientSecrets": [ { "Value": "WebApi" } ], "RedirectUris": [ "https://localhost:44303/signin-oidc" ], "FrontChannelLogoutUri": "https://localhost:44303/signout-oidc", "PostLogoutRedirectUris": [ "https://localhost:44303/signout-callback-oidc" ], "AllowedCorsOrigins": [ "https://localhost:44303", "https://localhost:44310" ], "AllowedScopes": [ "openid", "email", "profile", "roles" ] }, //Mvc { "ClientId": "Mvc_ClientId", "ClientName": "Mvc_ClientId", "ClientUri": "https://localhost:44332", "AllowedGrantTypes": [ "hybrid" ], //"RequirePkce": true, "AllowPlainTextPkce": false, "ClientSecrets": [ { "Value": "WebMvc" } ],

      "RedirectUris": [
        "https://localhost:44332/signin-oidc"
      ],
      "FrontChannelLogoutUri": "https://localhost:44332/signout-oidc",
      "PostLogoutRedirectUris": [
        "https://localhost:44332/signout-callback-oidc"
      ],
      "AllowedCorsOrigins": [
        "https://localhost:44332",
        "https://localhost:44310"
      ],
      "AllowedScopes": [
        "openid",
        "email",
        "profile",
        "roles",
        "address",
        "PS.webApi"
      ],
      "AllowAccessTokensViaBrowser": true,
      "RequireConsent": false,
      "AllowOfflineAccess": true
      //"UpdateAccessTokenClaimsOnRefresh": true
    }
  ]
}

} `

Home controller in My MVC project: ` public class HomeController : Controller { private readonly ILogger _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Default()
    {
        return View();
    }
    public IActionResult Index()
    {
        return View();
    }

    [Authorize]
    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

But finally, after running and referring to the address https://localhost:44332/home/privacy , which is decorated with attributes [Authorize] ` I have the following error:

It should be noted that the property is RequireHttpsMetadata = false

error-7fb20a123b074056b697ed8c870aa99b

vbjay commented 2 years ago

See https://demoids.vbjaysolutions.com/admin and login using a google or github account. You can view the configuration. Look at the oidc client. Need to add good redirect urls to the client that match where you point your client to use. If they don't match....you won't be allowed to use just any redirect url.