简体   繁体   中英

Using WebApi to authenticate with ADFS

We are trying to create following scenario:

Html page sends ajax request to WebApi asking wheter user has certain user role or not. WebApi checks from ADFS if user is logged in (if not, WebApi authenticates user). WebApi then reads user roles from ADFS and returns true/false to html page.

What we have so far:

Ajax sends Get-request to WebApi. In WebApi we have Authorize-tag, which correctly sends user to ADFS-authentication. However, after authentication ADFS returns html-page containing saml information to client instead of WebApi. So now we create another ajax request (post this time) which has received html-page as data. WebApi then parses this and returns either true/false based on user roles in SAML-response.

Questions:

  1. Currently used mechanism seems clunky. Is this mechanism correct or is there a better way to do this?

  2. If we use method above, is there a possibility that user edits received html-page and gives himself roles that he doesn't really have?

  3. Even if above mechanism is correct, we are still having cors-error when WebApi redirects to authentication. Cors is enabled in WebApi's Startup.cs. How do we get rid of this?

Codes:

Ajax:

var uri = 'api/user';
$(document).ready(function () {
        $.ajax({
        url: uri,
        type: "Get",
        success: function (data) {
            $.ajax({
                url: uri,
                type: "POST",
                data: data,
                success: function (value) {
                    if (value == true) {
                            $('#userData').text('You have correct role.');
                    }
                    else {
                            $('#userData').text('You don't have correct role.');
                    }
                },
                error: function (jqXHR, textStatus, err) {
                        window.location.href = "NotLoggedIn.html";
                }
            })
        },
        error: function (jqXHR, textStatus, err) {
                window.location.href = "NotLoggedIn.html";
        }
    });
});

Startup.Auth.cs:

public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

    app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
    {
            MetadataAddress = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"],
            Wtrealm = ConfigurationManager.AppSettings["ida:Audience"],

    });
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
            AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
    });
}

UserController:

namespace SSOWebApiSample.Controllers{
    [RoutePrefix("api/user")]
    public class UserController : ApiController
    {
            [HttpGet]
            [Route("")]
            [Authorize]
            public IHttpActionResult GetUser()
            {
                    return Ok();
            }

            [HttpPost]
            [Route("")]
            public async Task<IHttpActionResult> PostUser()
            {
                    bool isAdditionalInfoAllowedUser = false;
                    string result = await Request.Content.ReadAsStringAsync();
                    //Parse result here
                    return Ok(isAdditionalInfoAllowedUser);
            }
    }
}

AdalJS will clean this up nicely. Please refer to the following:

  1. To Do application adapted from Azure AD to ADFS
  2. Azure AD sample with CORS
  3. Enabling Cross-Origin Requests in ASP.NET Web API 2

To make successful CORS Web API calls with ADFS authentication, I found needed to set instance, tenant, clientId, and endpoints members when calling adalAuthenticationService.init() in my Angular app's Config. See sample two for endpoints example, but replace GUID with URL.

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