Azure Вход в систему единого входа с ApplicationId и Tenant Id не возвращает успешный вывод заявки - PullRequest
0 голосов
/ 24 января 2020
public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app) {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions() {                
            CookieDomain = ".xxx.com"
        });

        var notifications = new OpenIdConnectAuthenticationNotifications {
            AuthenticationFailed = OnAuthenticationFailed
        };
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions {
                ClientId = SystemSettings.ClientId, //This is the client Id of the central Multi-tenant Azure AD application
                    Authority = SystemSettings.Authority,
                PostLogoutRedirectUri = SystemSettings.PostLogoutRedirectUri,
                Notifications = notifications,
                //ProtocolValidator = new OpenIdConnectProtocolValidator() { RequireNonce = false},
                UseTokenLifetime = false,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() {
                    ValidIssuers = SystemSettings.ValidIssuers                        
                }
            });
        }
    }

Для входа в систему единого входа мы вызываем контекст OWIN:

HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = string.IsNullOrWhiteSpace(returnUrl) ? "/account/authenticated" : string.Format("/account/authenticated?companyCode={0}&returnUrl={1}", companyCode, HttpUtility.UrlEncode(returnUrl)) },
                            OpenIdConnectAuthenticationDefaults.AuthenticationType);
                    return null;

После успешного входа в систему единого входа я перенаправляю на следующие детали маршрута:

[Route("account/authenticated")]
[AllowAnonymous]
public ActionResult Authenticated(string returnUrl, string companyCode) {
       FileLogger.Log($"System.Web.HttpContext.Current.Request.IsAuthenticated: {System.Web.HttpContext.Current.Request.IsAuthenticated}");
        var identity = (ClaimsIdentity)Thread.CurrentPrincipal.Identity;
        var claims = JsonConvert.SerializeObject(identity?.Claims?.ToList(), new JsonSerializerSettings() {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        });
        FileLogger.Log($"claims: {claims}");
        if (System.Web.HttpContext.Current.Request.IsAuthenticated) {
            var token = AuthorizationService.AuthorizeUser();
            FileLogger.Log($"AuthorizationService.AuthorizeUser() returns: {token}");
            if (!string.IsNullOrWhiteSpace(token)) {
                ViewBag.ClientCode = companyCode;
                ViewBag.Token = token;
                ViewBag.ReturnUrl = returnUrl;
                return View();
            }
            return null;
        }
        var currentClaimsPrincipal = ClaimsPrincipal.Current;
        if (currentClaimsPrincipal != null && currentClaimsPrincipal.Claims != null) {
            var myClaimsPrincipal = new ClaimsIdentity(currentClaimsPrincipal.Claims);
        }
        return null;
    }

Но вывод заявки не приходит, и я получаю ложную аутентификацию и никаких претензий:

Личность:

{System.Security.Principal.GenericIdentity}
    Actor: null
    AuthenticationType: ""
    BootstrapContext: null
    Claims: {System.Security.Claims.ClaimsIdentity.<get_Claims>d__51}
    CustomSerializationData: null
    IsAuthenticated: false
    Label: null
    Name: ""
    NameClaimType: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
    RoleClaimType: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"

Ответы [ 2 ]

0 голосов
/ 03 февраля 2020

Я решил это, обновив пакеты OWIN и добавив ссылки ниже: https://dotnetcodetips.com/Tip/91/Azure-OWIN-website-login-gets-stuck-on-a-never-ending-redirect-loop.

0 голосов
/ 27 января 2020

Насколько я знал, мы можем использовать следующий код для получения утверждений после завершения Azure AD auth

var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
/*
 The token's claim "aud" is  the application's client ID. For more deatils, please refer to https://docs.microsoft.com/en-us/azure/architecture/multitenant-identity/claims.

*/
 foreach (var claim in userClaims.Claims) {

                // get app id
            }          

            // TenantId is the unique Tenant Id - which represents an organization in Azure AD
            ViewBag.TenantId = userClaims?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...