Exemplo n.º 1
0
        /// <summary>
        /// Event to handle Token Validation from ID provider
        /// </summary>
        /// <param name="n">The context for this notification</param>
        /// <param name="authorizationService">The service to use for authorization</param>
        /// <returns></returns>
        private static async Task OnSecurityTokenValidated(
            SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> n)
        {
            // get access and id tokens
            var accessToken = n.ProtocolMessage.AccessToken;
            var idToken     = n.ProtocolMessage.IdToken;

            // persist access token in cookie
            if (!String.IsNullOrEmpty(accessToken))
            {
                // add access token
                n.AuthenticationTicket.Identity.AddClaim(
                    new Claim("access_token", accessToken));

                // get user info from ID server
                var userClient = new UserInfoClient(KnownIdServer.UserInfoEndpoint, accessToken);
                var userInfo   = await userClient.GetAsync();

                // get claims from ticket
                n.AuthenticationTicket.Identity.AddClaims(userInfo.Claims.Select(c => new Claim(c.Item1, c.Item2)));

                // get username
                var username =
                    n.AuthenticationTicket.Identity.Claims.FirstOrDefault(
                        c => c.Type == "preferred_username");
            }

            // if we have an id token
            if (!String.IsNullOrEmpty(idToken))
            {
                // add to authentication ticket
                n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", idToken));
            }
        }
Exemplo n.º 2
0
        private static async Task SecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> n, string authority)
        {
            var idToken     = n.ProtocolMessage.IdToken;
            var claimsIdent = n.AuthenticationTicket.Identity;

            if (claimsIdent != null)
            {
                //If Implicit Flow
                if (n.ProtocolMessage.AccessToken != null)
                {
                    //Add userClaims from userInfoEndpoint
                    await AddUserClaimsAsync(claimsIdent, authority, n.ProtocolMessage.AccessToken);

                    //Add portal
                    //AddPortalGroupInfo(claimsIdent);

                    //Calculate AccessToken Expiration
                    int            expiresIn  = int.Parse(n.ProtocolMessage.ExpiresIn);
                    DateTimeOffset expiresUtc = DateTimeOffset.UtcNow.AddSeconds(expiresIn);

                    //Add access_token for DomSec Api call"
                    claimsIdent.AddOrUpdateClaim("access_token", n.ProtocolMessage.AccessToken);
                    claimsIdent.AddOrUpdateClaim("expires_at", expiresUtc.ToString());

                    //Add id_token for logout hint
                    claimsIdent.AddOrUpdateClaim("id_token", idToken);

                    //Add expiration to AuthenticationTicket
                    n.AuthenticationTicket.Properties.ExpiresUtc = expiresUtc;
                }
            }
        }
Exemplo n.º 3
0
        private static async Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            var protocolMessage = notification.ProtocolMessage;
            var idToken         = protocolMessage.IdToken;
            var accessToken     = protocolMessage.AccessToken;
            var identity        = CreateIdentity(notification.AuthenticationTicket);

            await AddUserInfoClaims(identity, notification.Options, accessToken);

            // Keep the id_token for logout
            identity.AddClaim(new Claim("id_token", idToken));

            // Add access token for API calls.  The value of this claim will be used as the
            // argument to the BearerCredentials constructor when specifying credentials as part
            // of the SendOptions passed to Bus.Send methods.  See example Bus.Send operation in
            // the TestMessageController.SendTestMessage method.
            identity.AddClaim(new Claim("access_token", accessToken));

            // Keep track of access token expiration
            int expiresInSeconds;

            if (int.TryParse(protocolMessage.ExpiresIn, out expiresInSeconds))
            {
                var expiresIn = TimeSpan.FromSeconds(expiresInSeconds);
                var expries   = DateTimeOffset.UtcNow.Add(expiresIn);
                identity.AddClaim(new Claim("expires", expries.ToString("O")));
            }

            notification.AuthenticationTicket = new AuthenticationTicket(identity, notification.AuthenticationTicket.Properties);
        }
        protected virtual string GetEpiUserId(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context, ClaimsIdentity identity)
        {
            var vippsInfo = _vippsLoginService.GetVippsUserInfo(identity);

            if (vippsInfo == null)
            {
                var message = "Could not retrieve Vipps UserInfo from the provided identity";
                Logger.Error($"Vipps.Login: {message}");
                throw new VippsLoginException(message);
            }

            // Get existing user identifier (by default Epi will use email address)
            var userId =
                // First check if we're linking to an existing account
                ByLinkAccount(context, vippsInfo) ??
                // If not, find user by vipps identifier (subject guid)
                BySubjectGuid(vippsInfo) ??
                // Or else search user by email/phone
                ByEmailOrPhoneNumber(vippsInfo);

            // New user
            if (string.IsNullOrWhiteSpace(userId))
            {
                userId = vippsInfo.Email;
            }

            return(userId);
        }
Exemplo n.º 5
0
        public static async Task GenerateUserIdentityAsync(
            SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            var identityUser = new ClaimsIdentity(
                notification.AuthenticationTicket.Identity.Claims,
                notification.AuthenticationTicket.Identity.AuthenticationType,
                ClaimTypes.Name,
                ClaimTypes.Role);

            var newIdentityUser = new ClaimsIdentity(identityUser.AuthenticationType,
                                                     ClaimTypes.GivenName, ClaimTypes.Role);

            newIdentityUser.AddClaim(identityUser.FindFirst(ClaimTypes.NameIdentifier));

            var emailClaim = identityUser.FindFirst(ClaimTypes.Email) ?? new Claim(ClaimTypes.Email, identityUser.FindFirst("name").Value);

            newIdentityUser.AddClaim(emailClaim);

            //Optionally add other claims
            var userInfoClient = new UserInfoClient(
                new Uri(notification.Options.Authority + "/connect/userinfo").ToString());

            var userInfo = await userInfoClient.GetAsync(notification.ProtocolMessage.AccessToken);

            newIdentityUser.AddClaims(userInfo.Claims.Select(t => new Claim(t.Type, t.Value)));

            notification.AuthenticationTicket = new AuthenticationTicket(newIdentityUser,
                                                                         notification.AuthenticationTicket.Properties);
        }
Exemplo n.º 6
0
        private Task SecurityTokenValidated(
            SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> arg)
        {
            id_token = arg.ProtocolMessage.IdToken;

            return(Task.FromResult(0));
        }
        // Check if we're trying to link an existing account
        protected virtual string ByLinkAccount(
            SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context,
            VippsUserInfo vippsUserInfo)
        {
            var props = context.AuthenticationTicket.Properties.Dictionary;

            if (props.ContainsKey(VippsConstants.LinkAccount) &&
                Guid.TryParse(props[VippsConstants.LinkAccount], out var linkAccountToken))
            {
                // Do not allow linking to multiple accounts
                string message;
                if (BySubjectGuid(vippsUserInfo) != null)
                {
                    message =
                        "This Vipps account is already linked to an account. Please remove the connection before making a new one.";
                    Logger.Error($"Vipps.Login: {message}");
                    throw new VippsLoginLinkAccountException(message, true);
                }

                var accountToLink = _vippsCommerceService.FindCustomerContactByLinkAccountToken(linkAccountToken);
                if (accountToLink == null)
                {
                    message = "Could not find account to link to.";
                    Logger.Error($"Vipps.Login: {message}");
                    throw new VippsLoginLinkAccountException(message);
                }

                return(GetLoginEmailFromContact(accountToLink));
            }

            return(null);
        }
Exemplo n.º 8
0
        private static Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> arg)
        {
            Claim c = arg.AuthenticationTicket.Identity.Claims.FirstOrDefault(d => d.Type == "preferred_username");

            Log.Info($"{c?.Value ?? "N/A"} logged in.");
            return(Task.FromResult(0));
        }
        CreateContext(
            string userInfoEndpoint = "https://user-info-endpoint",
            string scope            = "")
        {
            var configurationManager =
                A.Fake <IConfigurationManager <OpenIdConnectConfiguration> >();

            A.CallTo(() => configurationManager.GetConfigurationAsync(A <CancellationToken> ._))
            .Returns(new OpenIdConnectConfiguration
            {
                UserInfoEndpoint = "https://user-info-endpoint",
            });
            var options =
                new VippsOpenIdConnectAuthenticationOptions("clientId", "clientSecret", "authority")
            {
                ConfigurationManager = configurationManager,
                Scope = scope
            };
            var context =
                new SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(
                    A.Fake <IOwinContext>(), options)
            {
                AuthenticationTicket = new AuthenticationTicket(new ClaimsIdentity(), new AuthenticationProperties(
                                                                    new Dictionary <string, string>()
                {
                    { ".redirect", "https://test.url/redirect-url" }
                })),
                ProtocolMessage = A.Fake <OpenIdConnectMessage>()
            };

            return(context);
        }
Exemplo n.º 10
0
        private async Task AddRoles(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> arg)
        {
            var context           = new Adal.AuthenticationContext("https://login.microsoftonline.com/" + tenant);
            var clientCredentials = new Adal.ClientCredential(GraphClientId, GraphClientSecret);
            var token             = await context.AcquireTokenAsync("https://graph.windows.net/", clientCredentials);

            var userId = arg.AuthenticationTicket.Identity.Claims
                         .First(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")
                         .Value;

            HttpClient http = new HttpClient();
            string     url  = "https://graph.windows.net/b2ctestdes.onmicrosoft.com/users/" + userId + "/memberOf?api-version=1.6";

            // Append the access token for the Graph API to the Authorization header of the request by using the Bearer scheme.
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
            HttpResponseMessage response = await http.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();

                dynamic groups = JObject.Parse(result);

                foreach (var group in groups.value)
                {
                    string groupName = group.displayName;

                    arg.AuthenticationTicket.Identity.AddClaim(
                        new Claim(ClaimTypes.Role, groupName));
                }
            }
        }
Exemplo n.º 11
0
        private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            // If you wanted to keep some local state in the app (like a db of signed up users),
            // you could use this notification to create the user record if it does not already
            // exist.
            List <Claim> myClaims        = notification.AuthenticationTicket.Identity.Claims.ToList();
            string       anOIDClaimValue = myClaims.FirstOrDefault(aClaim => aClaim.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;

            if (string.IsNullOrEmpty(anOIDClaimValue))
            {
                throw new ApplicationException("Missing OID claim!");
            }
            using (B2CContext aContext = new B2CContext()) {
                Applicant anInternalApplicant = aContext.Applicants.FirstOrDefault(aUser => aUser.ExternalID == anOIDClaimValue);
                if (anInternalApplicant == null)
                {
                    Applicant aNewApplicant = new Applicant {
                        ExternalID  = anOIDClaimValue,
                        FirstName   = myClaims.FirstOrDefault(aClaim => aClaim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname")?.Value,
                        LastName    = myClaims.FirstOrDefault(aClaim => aClaim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname")?.Value,
                        Gender      = myClaims.FirstOrDefault(aClaim => aClaim.Type == "extension_Gender")?.Value,
                        Ethnicity   = myClaims.FirstOrDefault(aClaim => aClaim.Type == "extension_Ethnicity")?.Value,
                        DateOfBirth = DateTime.Now.AddYears(-20)
                    };
                    aContext.Applicants.Add(aNewApplicant);
                    aContext.SaveChanges();
                }
            }
            return(Task.FromResult(0));
        }
        private async Task SecurityTokenValidated(SecurityTokenValidatedNotification <WsFederationMessage, WsFederationAuthenticationOptions> notification, IProviderCommitmentsLogger logger,
                                                  AuthenticationOrchestrator orchestrator, AccountOrchestrator accountOrchestrator)
        {
            logger.Info("SecurityTokenValidated notification called");

            var identity = notification.AuthenticationTicket.Identity;

            var id          = identity.Claims.FirstOrDefault(claim => claim.Type == (DasClaimTypes.Upn))?.Value;
            var displayName = identity.Claims.FirstOrDefault(claim => claim.Type == (DasClaimTypes.DisplayName))?.Value;
            var ukprn       = identity.Claims.FirstOrDefault(claim => claim.Type == (DasClaimTypes.Ukprn))?.Value;
            var email       = identity.Claims.FirstOrDefault(claim => claim.Type == (DasClaimTypes.Email))?.Value;

            long parsedUkprn;

            if (!long.TryParse(ukprn, out parsedUkprn))
            {
                logger.Info($"Unable to parse Ukprn \"{ukprn}\" from claims for user \"{id}\"");
                return;
            }

            var showReservations = await accountOrchestrator.ProviderHasPermission(parsedUkprn, Operation.CreateCohort);

            identity.AddClaim(new Claim(DasClaimTypes.ShowReservations, showReservations.ToString(), "bool"));
            identity.MapClaimToRoles();

            await orchestrator.SaveIdentityAttributes(id, parsedUkprn, displayName, email);
        }
Exemplo n.º 13
0
        private async Task SecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> securityTokenValidatedNotification)
        {
            var n = securityTokenValidatedNotification;

            var id = n.AuthenticationTicket.Identity;

            // we want to keep first name, last name, subject and roles
            var givenName  = id.FindFirst(IdentityServer3.Core.Constants.ClaimTypes.GivenName);
            var familyName = id.FindFirst(IdentityServer3.Core.Constants.ClaimTypes.FamilyName);
            var sub        = id.FindFirst(IdentityServer3.Core.Constants.ClaimTypes.Subject);
            var roles      = id.FindAll(IdentityServer3.Core.Constants.ClaimTypes.Role);
            var id2        = id.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");

            var name = id.FindFirst("preferred_username");

            // create new identity and set name and role claim type
            var nid = new ClaimsIdentity(
                id.AuthenticationType,
                IdentityServer3.Core.Constants.ClaimTypes.GivenName,
                IdentityServer3.Core.Constants.ClaimTypes.Role);


            if (givenName != null)
            {
                nid.AddClaim(givenName);
            }
            if (familyName != null)
            {
                nid.AddClaim(familyName);
            }
            if (sub != null)
            {
                nid.AddClaim(sub);
            }
            if (roles != null)
            {
                nid.AddClaims(roles);
            }

            nid.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", name?.Value ?? "UNKNOWN"));



            nid.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
                                   id2.Value));
            nid.AddClaim(
                new Claim(
                    "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                    "idsrv"));
            nid.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "BUBGO"));


            // add some other app specific claim
            nid.AddClaim(new Claim("app_specific", "some data"));
            nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
            n.AuthenticationTicket = new AuthenticationTicket(
                nid,
                n.AuthenticationTicket.Properties);
        }
Exemplo n.º 14
0
        private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            // If you wanted to keep some local state in the app (like a db of signed up users),
            // you could use this notification to create the user record if it does not already
            // exist.

            return(Task.FromResult(0));
        }
Exemplo n.º 15
0
        private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            // Verify the user signing in is a business user, not a consumer user.
            string[] issuer   = context.AuthenticationTicket.Identity.FindFirst("iss").Value.Split('/');
            string   tenantId = issuer[(issuer.Length - 2)];

            return(Task.FromResult(0));
        }
 private static void StripSchemeFromReturnUrl(SecurityTokenValidatedNotification <WsFederationMessage, WsFederationAuthenticationOptions> args)
 {
     try
     {
         var uri = new Uri(args.AuthenticationTicket.Properties.RedirectUri);
         args.AuthenticationTicket.Properties.RedirectUri = String.Concat(uri.PathAndQuery, uri.Fragment);
     }
     catch (Exception) { }
 }
Exemplo n.º 17
0
        /// <summary>
        /// Invoked after the security token has passed validation and a ClaimsIdentity has been generated.
        /// </summary>
        /// <param name="notification">Notification context</param>
        /// <returns>OWIN OpenId Connect Response</returns>
        private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            // For Logout Request Okta requires idTokenHint so must maintain state for id_token
            // This should NOT be added to user's principal claims. For DEMO purposes only.
            // Okta REQUIRED parameter: A valid ID token with a subject matching the current session.
            notification.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim("id_token", notification.ProtocolMessage.IdToken));

            return(Task.FromResult(0));
        }
 internal static async Task SecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
 {
     Helpers.ThrowIfConditionFailed(() => context.AuthenticationTicket != null, "context.AuthenticationTicket is null.");
     Helpers.ThrowIfConditionFailed(() => context.AuthenticationTicket.Principal != null, "context.AuthenticationTicket.Principal is null.");
     Helpers.ThrowIfConditionFailed(() => context.AuthenticationTicket.Principal.Identity != null, "context.AuthenticationTicket.Principal.Identity is null.");
     Helpers.ThrowIfConditionFailed(() => !string.IsNullOrWhiteSpace(context.AuthenticationTicket.Principal.Identity.Name), "context.AuthenticationTicket.Principal.Identity.Name is null.");
     notificationsFired.Add(nameof(SecurityTokenValidated));
     await Task.FromResult(0);
 }
 internal static async Task SecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
 {
     Helpers.ThrowIfConditionFailed(() => context.AuthenticationTicket != null, "context.AuthenticationTicket is null.");
     Helpers.ThrowIfConditionFailed(() => context.AuthenticationTicket.Principal != null, "context.AuthenticationTicket.Principal is null.");
     Helpers.ThrowIfConditionFailed(() => context.AuthenticationTicket.Principal.Identity != null, "context.AuthenticationTicket.Principal.Identity is null.");
     Helpers.ThrowIfConditionFailed(() => !string.IsNullOrWhiteSpace(context.AuthenticationTicket.Principal.Identity.Name), "context.AuthenticationTicket.Principal.Identity.Name is null.");
     notificationsFired.Add(nameof(SecurityTokenValidated));
     await Task.FromResult(0);
 }
        private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <WsFederationMessage, WsFederationAuthenticationOptions> notification)
        {
            _logger.Debug("SecurityTokenValidated");

            try
            {
                _logger.Debug("Authentication Properties", new Dictionary <string, object>
                {
                    {
                        "claims",
                        JsonConvert.SerializeObject(
                            notification.AuthenticationTicket.Identity.Claims.Select(x => new { x.Value, x.ValueType, x.Type }))
                    },
                    {
                        "authentication-type",
                        notification.AuthenticationTicket.Identity.AuthenticationType
                    },
                    { "role-type", notification.AuthenticationTicket.Identity.RoleClaimType }
                });

                const string serviceClaimType = "http://service/service";

                if (notification.AuthenticationTicket.Identity.HasClaim(serviceClaimType, _rolesSettings.Tier2Claim))
                {
                    _logger.Debug("Adding Tier2 Role");
                    notification.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Role, _rolesSettings.T2Role));

                    _logger.Debug("Adding ConsoleUser Role");
                    notification.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Role, _rolesSettings.ConsoleUserRole));
                }
                else if (notification.AuthenticationTicket.Identity.HasClaim(serviceClaimType, _rolesSettings.GroupClaim))
                {
                    _logger.Debug("Adding ConsoleUser Role");
                    notification.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Role, _rolesSettings.ConsoleUserRole));
                }
                else
                {
                    throw new SecurityTokenValidationException();
                }

                var firstName = notification.AuthenticationTicket.Identity.Claims.SingleOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                var lastName  = notification.AuthenticationTicket.Identity.Claims.SingleOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
                var userEmail = notification.AuthenticationTicket.Identity.Claims.Single(x => x.Type == ClaimTypes.Upn).Value;

                notification.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Email, userEmail));
                notification.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Name, $"{firstName} {lastName}"));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "IDAMS Authentication Callback Error");
            }

            _logger.Debug("End of callback");

            return(Task.FromResult(0));
        }
Exemplo n.º 21
0
        private Task SecurityTokenValidatedNotification(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            var token = notification.ProtocolMessage.IdToken;

            if (!string.IsNullOrEmpty(token))
            {
                notification.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim("id_token", token));
            }
            return(Task.FromResult(0));
        }
Exemplo n.º 22
0
        private static Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <WsFederationMessage, WsFederationAuthenticationOptions> notification)
        {
            Logger.Debug("SecurityTokenValidated");


            var claimsIdentity = notification.AuthenticationTicket.Identity;

            Logger.Debug("Authentication Properties", new Dictionary <string, object>
            {
                { "claims", JsonConvert.SerializeObject(claimsIdentity.Claims.Select(x => new { x.Value, x.ValueType, x.Type })) },
                { "authentication-type", claimsIdentity.AuthenticationType },
                { "role-type", claimsIdentity.RoleClaimType }
            });

            if (notification.AuthenticationTicket.Identity.HasClaim(serviceClaimType, ServiceClaimTier2Role))
            {
                Logger.Debug("Adding Tier2 Role");
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, Tier2User));

                Logger.Debug("Adding ConsoleUser Role");
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, ConsoleUser));
            }
            else if (notification.AuthenticationTicket.Identity.HasClaim(serviceClaimType, ServiceClaimTier1Role))
            {
                Logger.Debug("Adding Tier1 Role");
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, Tier1User));

                Logger.Debug("Adding ConsoleUser Role");
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, ConsoleUser));
            }
            else
            {
                throw new SecurityTokenValidationException("Service Claim Type not available to identify the Role");
            }

            var firstName = claimsIdentity.Claims.SingleOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
            var lastName  = claimsIdentity.Claims.SingleOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
            var userEmail = claimsIdentity.Claims.Single(x => x.Type == ClaimTypes.Upn).Value;

            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, $"{firstName} {lastName}"));

            if (!string.IsNullOrEmpty(userEmail))
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, userEmail));
                claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userEmail));
            }
            else
            {
                throw new SecurityTokenValidationException("Upn not available in the claims to identify UserEmail");
            }

            Logger.Debug("End of callback");
            return(Task.FromResult(0));
        }
        private Task OnSecurityTokenValidatedAsync(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            // Make sure that the user didn't sign in with a personal Microsoft account
            if (notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value == "9188040d-6c67-4c5b-b112-36a304b66dad")
            {
                notification.HandleResponse();
                notification.Response.Redirect("/Account/UserMismatch");
            }

            return(Task.FromResult(0));
        }
Exemplo n.º 24
0
        private async Task OnSecurityTokenValidated(
            SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            var issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;

            if (!issuer.StartsWith(this.issuerPrefix, StringComparison.OrdinalIgnoreCase))
            {
                throw new System.IdentityModel.Tokens.SecurityTokenValidationException();
            }

            await Task.CompletedTask;
        }
Exemplo n.º 25
0
        static Task SecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage,
                                                                               OpenIdConnectAuthenticationOptions> notification)
        {
            var token = notification.ProtocolMessage.AccessToken;

            if (!string.IsNullOrEmpty(token))
            {
                notification.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", token));
            }

            return(Task.FromResult(true));
        }
        private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            // Verify the user signing in is a business user, not a consumer user.
            string[] issuer   = context.AuthenticationTicket.Identity.FindFirst(Globals.IssuerClaim).Value.Split('/');
            string   tenantId = issuer[(issuer.Length - 2)];

            if (tenantId == Globals.ConsumerTenantId)
            {
                throw new SecurityTokenValidationException("Consumer accounts are not supported for the Group Manager App.  Please log in with your work account.");
            }

            return(Task.FromResult(0));
        }
Exemplo n.º 27
0
        // We need to update these values each time we receive a new token, so the SingleSignOut
        // javascript has access to the correct values.
        public async static Task SecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            // Get Tenant-Specific Metadata (Authorization Endpoint), needed for making prompt=none request in RedirectToIdentityProvider
            OpenIdConnectAuthenticationOptions tenantSpecificOptions = new OpenIdConnectAuthenticationOptions();

            tenantSpecificOptions.Authority            = AADInstance + notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            tenantSpecificOptions.ConfigurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(tenantSpecificOptions.Authority + "/.well-known/openid-configuration");
            OpenIdConnectConfiguration tenantSpecificConfig = await tenantSpecificOptions.ConfigurationManager.GetConfigurationAsync(notification.Request.CallCancelled);

            notification.AuthenticationTicket.Identity.AddClaim(new Claim("issEndpoint", tenantSpecificConfig.AuthorizationEndpoint, ClaimValueTypes.String, "WebApp-Distributed-SignOut-DotNet"));

            CheckSessionIFrame = notification.AuthenticationTicket.Properties.Dictionary[OpenIdConnectSessionProperties.CheckSessionIFrame];
            return;
        }
Exemplo n.º 28
0
        private static Task SecurityTokenValidated(SecurityTokenValidatedNotification <HttpContext, OAuthBearerAuthenticationOptions> notification)
        {
            List <Claim> claims =
                new List <Claim>
            {
                new Claim(ClaimTypes.Email, "*****@*****.**"),
                new Claim(ClaimsIdentity.DefaultNameClaimType, "bob"),
            };

            notification.AuthenticationTicket = new AuthenticationTicket(new ClaimsIdentity(claims, notification.Options.AuthenticationType), new Http.Security.AuthenticationProperties());
            notification.HandleResponse();

            return(Task.FromResult <object>(null));
        }
Exemplo n.º 29
0
        public void SetToken(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> n)
        {
            var givenNameClaim = n.AuthenticationTicket
                                 .Identity.FindFirst(IdentityModel.JwtClaimTypes.GivenName);

            var familyNameClaim = n.AuthenticationTicket
                                  .Identity.FindFirst(IdentityModel.JwtClaimTypes.FamilyName);

            var emailClaim = n.AuthenticationTicket
                             .Identity.FindFirst(IdentityModel.JwtClaimTypes.Email);

            var subClaim = n.AuthenticationTicket
                           .Identity.FindFirst(IdentityModel.JwtClaimTypes.Subject);

            var nameClaim = new Claim(IdentityModel.JwtClaimTypes.Name,
                                      string.Format("{0}/{1}", Constants.NotesIssuerUri, subClaim.Value));

            var newClaimsIdentity = new ClaimsIdentity(
                n.AuthenticationTicket.Identity.AuthenticationType,
                IdentityModel.JwtClaimTypes.Name,
                IdentityModel.JwtClaimTypes.Role);

            newClaimsIdentity.AddClaim(nameClaim);

            if (givenNameClaim != null)
            {
                newClaimsIdentity.AddClaim(givenNameClaim);
            }

            if (familyNameClaim != null)
            {
                newClaimsIdentity.AddClaim(familyNameClaim);
            }

            if (emailClaim != null)
            {
                newClaimsIdentity.AddClaim(emailClaim);
                var roles = GetUserRoles(emailClaim.Value);
                foreach (var role in roles)
                {
                    newClaimsIdentity.AddClaim(new Claim(IdentityModel.JwtClaimTypes.Role, role));
                }
            }

            newClaimsIdentity.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

            n.AuthenticationTicket = new AuthenticationTicket(newClaimsIdentity,
                                                              n.AuthenticationTicket.Properties);
        }
Exemplo n.º 30
0
 private async Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
 {
     if (string.IsNullOrEmpty(notification.ProtocolMessage.State))
     {
         string             tenant   = notification.AuthenticationTicket.Identity.FindFirst(IssuerClaimType).Value.Split('/')[3];
         ViewDataDictionary settings = new ViewDataDictionary
         {
             { "tenant", tenant },
             { "client_id", notification.AuthenticationTicket.Identity.FindFirst(AudClaimType).Value },
             { "sign_up_policy", notification.AuthenticationTicket.Identity.HasClaim(NewUserClaimType, "true") ? notification.AuthenticationTicket.Identity.FindFirst(AcrClaimType).Value : null },
             { "sign_in_policy", null },
             { "edit_profile_policy", null },
         };
         HttpContext.Current.Session.Add("b2c_settings", settings);
     }
 }
Exemplo n.º 31
0
        private async Task OnSecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> arg)
        {
            var userIdentity = arg.AuthenticationTicket.Identity as ClaimsIdentity;

            if (userIdentity != null)
            {
                var emailAddress      = userIdentity.GetEmailAddress();
                var _submitterService = new SubmitterService();
                var submitter         = await _submitterService.GetSubmitterByMicrosoftAccountAsync(emailAddress);

                if (submitter != null)
                {
                    userIdentity.AddClaims(SubmitterClaims.GenerateClaims(submitter));
                }
            }
        }
        private static Task SecurityTokenValidated(SecurityTokenValidatedNotification<HttpContext, OAuthBearerAuthenticationOptions> notification)
        {
            List<Claim> claims =
                new List<Claim>
                {
                    new Claim(ClaimTypes.Email, "*****@*****.**"),
                    new Claim(ClaimsIdentity.DefaultNameClaimType, "bob"),
                };

            notification.AuthenticationTicket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, notification.Options.AuthenticationScheme)), new Http.Authentication.AuthenticationProperties(), notification.Options.AuthenticationScheme);
            notification.HandleResponse();

            return Task.FromResult<object>(null);
        }