简体   繁体   中英

Integrating ASP.NET code to Active Directory or LDAP after deploying on Bluemix

I'm working on an ASP.Net project, which needs to be deployed after completion on PaaS, which needs to be BlueMix (It wasn't my choice, It was an order).
In addition I need to use an:

Active Directory or LDAP to the User Authentication and Authorization, integrated with the ASP.Net Project.

The Issues Here Are :
I have found an integration to the Active Directory or SSO Services using only Java or Node.js, but in my case I am using ASP.Net 我发现只使用Java或Node.js集成到Active Directory或SSO服务,但在我的情况下,我使用的是ASP.Net
I want a solution for how the integration can be done on top of the PaaS between the Active Directory and ASP.Net application. 我想要一个解决方案,了解如何在Active Directory和ASP.Net应用程序之间的PaaS之上完成集成。

Depending on which version of ADFS you're using, you should be able to use either OAuth or OIDC middleware to connect from an ASP.NET Core application (assuming you're using ASP.NET Core because you're using Bluemix). If you're using at least ADFS 3.0 (Windows Server 2012+), you can use ASP.NET Core's generic OAuth middleware to connect.

First, create a configuration file to store your ADFS server settings, or modify an existing configuration file (such as appsettings.json).

Sample "adfs-settings.json" file:

{
  "ADFS": {
    "ClientId": "Your ClientId as set on ADFS server",
    "ResourceUrl": "url of this application (ex: http://mywebapp.mybluemix.net)",
    "ServerUrl": "url of ADFS (ex: https://dc.your.domain)"
  }
}

If you created a new file, such as "adfs-settings.json", for your ADFS configuration, add it to your Configuration object in the constructor of your Startup.cs file.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("adfs-settings.json");
    Configuration = builder.Build();
}

In your Configure method of Startup.cs create an OAuthOptions object:

var options = new OAuthOptions();
options.AutomaticChallenge = true;
options.AuthenticationScheme = "ADFS";

Specify the ClientId that you created when configuring this application on your ADFS server by reading it from your Configuration object. The generic OAuth middleware also requires that you provide a ClientSecret here even though that value is not actually used by ADFS 3.0.

options.ClientId = Configuration["ADFS:ClientId"];
options.ClientSecret = "ADFS 3.0 does not support confidential client, but OAuth middleware requires it";

Set the callback url which the ADFS server will redirect to in your application.

options.CallbackPath = new PathString("/signin-adfs");

Now configure the OAuthEvents . OnRedirectToAuthorizationEndpoint defines parameters which are passed to the ADFS authorization endpoint when the application determines that a user needs to be authorized. This will require at least a resource parameter which points to the url of your application. OnCreatingTicket is triggered when the ADFS server has finished authorizing a client and returns a JWT token containing claims data to your application. In this method you'll need to process adding roles and claims to the HttpContext object.

options.Events = new OAuthEvents {
    OnRedirectToAuthorizationEndpoint = context =>
    {
        var parameter = new Dictionary<string, string>
            {
                ["resource"] = Configuration["ADFS:ResourceUrl"]
            };
        var query = QueryHelpers.AddQueryString(context.RedirectUri, parameter);
        context.Response.Redirect(query);
        return Task.CompletedTask;
    },
    OnCreatingTicket = context => {
        JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
        JwtSecurityToken validatedToken = tokenHandler.ReadJwtToken(context.AccessToken);
        IEnumerable<Claim> a = validatedToken.Claims;

        foreach (var claim in a)
        {
            // role claim needs to be mapped to http://schemas.microsoft.com/ws/2008/06/identity/claims/role
            // for IsInRole() to work properly
            if (claim.Type == "role")
            {
                context.Identity.AddClaim(new Claim(ClaimTypes.Role, claim.Value));
            }
            else if (claim.Type == "unique_name")
            {
                // map name to Identity.Name
                context.Identity.AddClaim(new Claim(context.Identity.NameClaimType, claim.Value));
            }
            else
            {
                // this is optional, if you want any other specific claims from Active Directory
                // this will also include some information about the jwt token such as the issue
                // and expire times
                context.Identity.AddClaim(new Claim(claim.Type, claim.Value));
            }
        }

        return Task.CompletedTask;
        }
    };

Next, set the ClaimsIssuer to the ADFS url and set the SignInScheme to CookieAuthenticationDefaults.AuthenticationScheme and configure the AuthorizationEndpoint and TokenEndpoint to the proper endpoints on your ADFS server.

    options.ClaimsIssuer = Configuration["ADFS:ServerUrl"];
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.AuthorizationEndpoint = Configuration["ADFS:ServerUrl"] + "/adfs/oauth2/authorize/";
    options.TokenEndpoint = Configuration["ADFS:ServerUrl"] + "/adfs/oauth2/token/";

Finally, add the OAuth middleware using the options you've just created:

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOAuthAuthentication(options);

Now you should be able to apply the [Authorize] attribute to any controller or action which requires authorization with ADFS. For a complete sample application see this GitHub repo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM