Inheritance: System.Security.Principal.IPrincipal
Example #1
1
        public string PostLogin(FormDataCollection body)
        {
            string username = body.Get("username");
            string password = body.Get("password");

            using(var session = store.OpenSession())
            {
                var profile = session.Load<Profile>("profiles/" + username);
                if(profile.Password == password)
                {
                    var defaultPrincipal = new ClaimsPrincipal(
                        new ClaimsIdentity(new[] {new Claim(MyClaimTypes.ProfileKey, profile.Id)},
                            "Application" // this is important. if it's null or empty, IsAuthenticated will be false
                            ));
                    var principal = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.
                            ClaimsAuthenticationManager.Authenticate(
                                Request.RequestUri.AbsoluteUri, // this, or any other string can be available
                                                                // to your ClaimsAuthenticationManager
                                defaultPrincipal);
                    AuthenticationManager.EstablishSession(principal);
                    return "login ok";
                }
                return "login failed";
            }
        }
        public async Task<AuthorizeResponse> CreateCodeFlowResponseAsync(ValidatedAuthorizeRequest request, ClaimsPrincipal subject)
        {
            var code = new AuthorizationCode
            {
                Client = request.Client,
                Subject = subject,

                IsOpenId = request.IsOpenIdRequest,
                RequestedScopes = request.ValidatedScopes.GrantedScopes,
                RedirectUri = request.RedirectUri,

                WasConsentShown = request.WasConsentShown,
                RefreshTokenLifetime = request.Client.RefreshTokenLifetime
            };

            // store id token and access token and return authorization code
            var id = Guid.NewGuid().ToString("N");
            await _authorizationCodes.StoreAsync(id, code);

            return new AuthorizeResponse
            {
                RedirectUri = request.RedirectUri,
                Code = id,
                State = request.State
            };
        }
        public async Task UpdateConsentAsync(Client client, ClaimsPrincipal user, IEnumerable<string> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (user == null) throw new ArgumentNullException("user");

            if (client.AllowRememberConsent)
            {
                var subject = user.GetSubjectId();
                var clientId = client.ClientId;

                if (scopes != null && scopes.Any())
                {
                    var consent = new Consent
                    {
                        Subject = subject,
                        ClientId = clientId,
                        Scopes = scopes
                    };
                    await _store.UpdateAsync(consent);
                }
                else
                {
                    await _store.RevokeAsync(subject, clientId);
                }
            }
        }
        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
            {
                // Get the claims required to make further Graph API enquiries about the user
                //Claim nameIdClaim = incomingPrincipal.FindFirst(NameIdClaim);
                //if (nameIdClaim == null)
                //{
                //    throw new NotSupportedException("Name claim not available, role authentication is not supported");
                //}
                Claim nameClaim = incomingPrincipal.FindFirst(NameClaim);
                if (nameClaim == null)
                {
                    throw new NotSupportedException("Name claim not available, role authentication is not supported");
                }

                string userName = nameClaim.Value;
                //string currentUserObjectId = objectIdentifierClaim.Value;

                //load up the roles as RoleClaims
                TableUser user = new TableUser(userName);
                Task<IList<string>> t = _userStore.GetRolesAsync(user);
                t.RunSynchronously();
                IList<string> currentRoles = t.Result;
                foreach (string role in currentRoles)
                {
                    ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, _issuer));
                }
            }
            return base.Authenticate(resourceName, incomingPrincipal);
        }
 public bool Authorize(ClaimsPrincipal user, object resource, string policyName)
 {
     var policy = _options.GetPolicy(policyName);
     return (policy == null) 
         ? false 
         : this.Authorize(user, resource, policy);
 }
        public void Check_PoliciesCanMutateUsersClaims()
        {
            // Arrange
            var user = new ClaimsPrincipal(
                new ClaimsIdentity(new Claim[0], "Basic")
                );

            var policies = new IAuthorizationPolicy[] {
                new FakePolicy() {
                    ApplyAsyncAction = (context) => {
                        if (!context.Authorized)
                        {
                            context.UserClaims.Add(new Claim("Permission", "CanDeleteComments"));
                            context.Retry = true;
                        }
                    }
                }
            };

            var authorizationService = new DefaultAuthorizationService(policies);

            // Act
            var allowed = authorizationService.Authorize(new Claim("Permission", "CanDeleteComments"), user);

            // Assert
            Assert.True(allowed);
        }
Example #7
0
        /// <summary>
        /// Add an additional ClaimsIdentity to the ClaimsPrincipal in the "server.User" environment key
        /// </summary>
        /// <param name="identity"></param>
        public void AddUserIdentity(IIdentity identity)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }
            var newClaimsPrincipal = new ClaimsPrincipal(identity);

            IPrincipal existingPrincipal = _context.Request.User;
            if (existingPrincipal != null)
            {
                var existingClaimsPrincipal = existingPrincipal as ClaimsPrincipal;
                if (existingClaimsPrincipal == null)
                {
                    IIdentity existingIdentity = existingPrincipal.Identity;
                    if (existingIdentity.IsAuthenticated)
                    {
                        newClaimsPrincipal.AddIdentity(existingIdentity as ClaimsIdentity ?? new ClaimsIdentity(existingIdentity));
                    }
                }
                else
                {
                    foreach (var existingClaimsIdentity in existingClaimsPrincipal.Identities)
                    {
                        if (existingClaimsIdentity.IsAuthenticated)
                        {
                            newClaimsPrincipal.AddIdentity(existingClaimsIdentity);
                        }
                    }
                }
            }
            _context.Request.User = newClaimsPrincipal;
        }
        public ClaimsPrincipal Validate(string userName, string password)
        {
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
            var credentials = new ClientCredentials();
            credentials.UserName.UserName = userName;
            credentials.UserName.Password = password;

            GenericXmlSecurityToken genericToken;
            genericToken = WSTrustClient.Issue(
                new EndpointAddress(_address),
                new EndpointAddress(_realm),
                binding,
                credentials) as GenericXmlSecurityToken;

            var config = new SecurityTokenHandlerConfiguration();
            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(_realm));

            config.CertificateValidationMode = X509CertificateValidationMode.None;
            config.CertificateValidator = X509CertificateValidator.None;

            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(_issuerThumbprint, _address);
            config.IssuerNameRegistry = registry;

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);

            ClaimsPrincipal principal;
            var token = genericToken.ToSecurityToken();
            principal = new ClaimsPrincipal(handler.ValidateToken(token));

            Tracing.Information("Successfully requested token for user via WS-Trust");
            return FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate("ResourceOwnerPasswordValidation", principal);
        }
 internal static void GetClaimsPrincipalWithNoSub()
 {
     List<Claim> claims = new List<Claim>();
     ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer", "name", "role"));
     ClaimsPrincipal.Current.AddIdentity(principal.Identity as ClaimsIdentity);
     ClaimsPrincipal.ClaimsPrincipalSelector = () => principal;
 }
        /// <summary>
        /// Extracts the User details accessing the service as a unique id in the form
        /// of "{authprovider}:{uniqueId}" using ProviderCrednetials for the logged
        /// in user.
        /// </summary>
        /// <param name="principal">The principal accessing the service.</param>
        /// <param name="request">The HttpRequest used to access the service.</param>
        /// <returns>The unique user id.</returns>
        public async Task<string> GetCurrentUserRegistrationReferenceAsync(ClaimsPrincipal principal, HttpRequestMessage request)
        {
            string provider = principal?.FindFirst("http://schemas.microsoft.com/identity/claims/identityprovider").Value;

            ProviderCredentials creds = null;
            if (string.Equals(provider, "facebook", StringComparison.OrdinalIgnoreCase))
            {
                creds = await principal.GetAppServiceIdentityAsync<FacebookCredentials>(request);
            }
            else if (string.Equals(provider, "google", StringComparison.OrdinalIgnoreCase))
            {
                creds = await principal.GetAppServiceIdentityAsync<GoogleCredentials>(request);
            }
            else if (string.Equals(provider, "twitter", StringComparison.OrdinalIgnoreCase))
            {
                creds = await principal.GetAppServiceIdentityAsync<TwitterCredentials>(request);
            }
            else if (string.Equals(provider, "microsoftaccount", StringComparison.OrdinalIgnoreCase))
            {
                creds = await principal.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(request);
            }

            if (creds == null)
            {
                throw ServiceExceptions.UserNullException();
            }

            // Format user details in the desired form of {authprovider}:{uniqueId}
            string authProvider = creds.Provider;
            string uniqueId = creds.UserClaims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
            var uniqueUserName = $"{authProvider}:{uniqueId}";

            return uniqueUserName;
        }
        public virtual async Task<IEnumerable<Claim>> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, bool includeAllIdentityClaims, NameValueCollection request)
        {
            Logger.Debug("Getting claims for identity token");

            List<Claim> outputClaims = new List<Claim>(GetStandardSubjectClaims(subject));
            var additionalClaims = new List<string>();

            // fetch all identity claims that need to go into the id token
            foreach (var scope in scopes)
            {
                if (scope.IsOpenIdScope)
                {
                    foreach (var scopeClaim in scope.Claims)
                    {
                        if (includeAllIdentityClaims || scopeClaim.AlwaysIncludeInIdToken)
                        {
                            additionalClaims.Add(scopeClaim.Name);
                        }
                    }
                }
            }

            if (additionalClaims.Count > 0)
            {
                var claims = await _users.GetProfileDataAsync(subject.GetSubjectId(), additionalClaims);
                if (claims != null)
                {
                    outputClaims.AddRange(claims);
                }
            }

            return outputClaims;
        }
        /// <summary>
        /// Checks authorization for the given operation context based on default policy evaluation.
        /// </summary>
        /// <param name="operationContext">The <see cref="T:System.ServiceModel.OperationContext" /> for the current authorization request.</param>
        /// <returns>
        /// true if access is granted; otherwise, false. The default is true.
        /// </returns>
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            var retVal = base.CheckAccessCore(operationContext);

            SimpleWebToken token = null;

            if (retVal)
            {
                // Extract authorization data.
                var requestMessage = operationContext.RequestContext.RequestMessage;
                var httpDetails = requestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                var requestUri = WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.UriTemplateMatch != null ? WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri : requestMessage.Headers.To;

                token = ReadAuthToken(httpDetails);
                retVal = token != null && IsValidToken(token, requestUri);
            }

            var securityContext = ServiceSecurityContext.Anonymous;
            ClaimsPrincipal principal = new GenericPrincipal(new GenericIdentity(String.Empty), new string[0]);
            var identity = principal.Identity;

            if (retVal)
            {
                var claims = token.Claims.Select(keyValuePair => new Claim(keyValuePair.Key, keyValuePair.Value));
                identity = new ClaimsIdentity(claims, "OAUTH-SWT");
                principal = new ClaimsPrincipal(identity);
                Thread.CurrentPrincipal = principal;
            }
            securityContext.AuthorizationContext.Properties["Principal"] = principal;
            securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { identity };
            operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;

            return retVal;
            //return true;
        }
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {  
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction(nameof(HomeController.Index), "Home");
            }

            ViewData["ReturnUrl"] = returnUrl;

            if (!ModelState.IsValid || model.UserName != model.Password) {
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
            }

            var claims = new List<Claim>() {
                new Claim(ClaimTypes.Name, model.UserName),
                new Claim(ClaimTypes.Role, "User"),
                new Claim(ClaimTypes.Country, "USA" ),
                new Claim("Event", "South Florida Code Camp 2016")
            };

            if (model.UserName.Equals("admin", StringComparison.OrdinalIgnoreCase)) {
                claims.Add(new Claim(ClaimTypes.Role, "Administrator"));
            }

            var identity = new ClaimsIdentity(claims, "local", ClaimTypes.Name, ClaimTypes.Role);
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.Authentication.SignInAsync("Cookies", principal);

            return RedirectToLocal(returnUrl);
        }
        public void Configuration(IAppBuilder app)
        {
           
            // token validation
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = Constants.IdentityServerUri,
                RequiredScopes = new[] { "apiAccess" }
            });

            // add app local claims per request
            app.UseClaimsTransformation(incoming =>
            {
                // either add claims to incoming, or create new principal
                var appPrincipal = new ClaimsPrincipal(incoming);
                incoming.Identities.First().AddClaim(new Claim("appSpecific", "some_value"));

                return Task.FromResult(appPrincipal);
            });

            app.UseCors(CorsOptions.AllowAll);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            // web api configuration
            app.UseWebApi(config);
        }
        public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType, out TokenResponse response)
        {
            SecurityToken token = null;
            response = new TokenResponse { TokenType = tokenType };

            var result = TryIssueToken(appliesTo, principal, tokenType, out token);
            if (result == false)
            {
                return false;
            }

            var ts = token.ValidTo.Subtract(DateTime.UtcNow);
            response.ExpiresIn = (int)ts.TotalSeconds;

            if (tokenType == TokenTypes.JsonWebToken || tokenType == TokenTypes.SimpleWebToken)
            {
                var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[tokenType];
                response.AccessToken = handler.WriteToken(token);
            }
            else
            {
                var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
                var sb = new StringBuilder(128);
                handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);

                response.AccessToken = sb.ToString();
            }

            return result;
        }
        public async Task<IActionResult> Unauthorized(string returnUrl = null)
        {
            const string Issuer = "https://contoso.com";
            
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, "barry", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim("EmployeeId", "123", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.DateOfBirth, "1970-06-08", ClaimValueTypes.Date));
            claims.Add(new Claim("BadgeNumber", "123456", ClaimValueTypes.String, Issuer));
            //claims.Add(new Claim("TemporaryBadgeExpiry", DateTime.Now.AddDays(1).ToString(), ClaimValueTypes.String, Issuer));
            //claims.Add(new Claim("TemporaryBadgeExpiry", DateTime.Now.AddDays(-1).ToString(), ClaimValueTypes.String, Issuer));
            var userIdentity = new ClaimsIdentity("SuperSecureLogin");
            userIdentity.AddClaims(claims);

            var userPrincipal = new ClaimsPrincipal(userIdentity);

            await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

            return RedirectToLocal(returnUrl);
        }
        public virtual IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>(from c in principal.Claims select c);

            var nameIdClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
            if (nameIdClaim == null)
            {
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userName));
            }

            // email address
            var membership = Membership.FindUsersByName(userName)[userName];
            if (membership != null)
            {
                string email = membership.Email;
                if (!String.IsNullOrEmpty(email))
                {
                    claims.Add(new Claim(ClaimTypes.Email, email));
                }
            }

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            claims.AddRange(GetProfileClaims(userName));

            return claims;
        }
        ClaimsPrincipal Transform(ClaimsPrincipal incomingPrincipal)
        {
            // todo... this is where we would put in any extra claim information
            incomingPrincipal.Identities.FirstOrDefault().AddClaim(new Claim(ClaimTypes.Role, "Admin"));

            return incomingPrincipal;
        }
        public ClaimsPrincipal ValidateUser(string token)
        {
            try
            {
                var decodedtoken = JsonWebToken.DecodeToObject(token, secretKey) as Dictionary<string, object>;
                if (decodedtoken == null)
                    return null;

                DateTime expiry = DateTime.Parse(decodedtoken["Expires"].ToString());
                if (expiry < DateTime.UtcNow) return null;

                var claims = new List<Claim>();

                if (decodedtoken.ContainsKey("Claims"))
                {
                    foreach (Dictionary<string, object> kvp in ((ArrayList) decodedtoken["Claims"]))
                    {
                        claims.Add(new Claim(kvp["Type"].ToString(), kvp["Value"].ToString()));
                    }
                }

                var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Token"));

                return claimsPrincipal;
            }
            catch (Exception)
            {
                return null;
            }
        }
        public IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>(from c in principal.Claims select c);

            // email address
            string email = Membership.FindUsersByName(userName)[userName].Email;
            if (!String.IsNullOrEmpty(email))
            {
                claims.Add(new Claim(ClaimTypes.Email, email));
            }

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            if (ProfileManager.Enabled)
            {
                var profile = ProfileBase.Create(userName, true);
                if (profile != null)
                {
                    foreach (SettingsProperty prop in ProfileBase.Properties)
                    {
                        string value = profile.GetPropertyValue(prop.Name).ToString();
                        if (!String.IsNullOrWhiteSpace(value))
                        {
                            claims.Add(new Claim(ProfileClaimPrefix + prop.Name.ToLowerInvariant(), value));
                        }
                    }
                }
            }

            return claims;
        }
        public void Check_ApplyCanMutateCheckedClaims()
        {
            // Arrange
            var user = new ClaimsPrincipal(
                new ClaimsIdentity( new Claim[] { new Claim("Permission", "CanDeleteComments") }, "Basic")
                );

            var policies = new IAuthorizationPolicy[] {
                new FakePolicy() {
                    ApplyAsyncAction = (context) => {
                        // for instance, if user owns the comment
                        if(!context.Claims.Any(claim => claim.Type == "Permission" && claim.Value == "CanDeleteComments"))
                        {
                            context.Claims.Add(new Claim("Permission", "CanDeleteComments"));
                            context.Retry = true;
                        }
                    }
                }
            };

            var authorizationService = new DefaultAuthorizationService(policies);

            // Act
            var allowed = authorizationService.Authorize(Enumerable.Empty<Claim>(), user);

            // Assert
            Assert.True(allowed);
        }
Example #22
0
 public static ClaimsPrincipal CreateWithUserId(long authorId)
 {
     var claim = new Claim(ToBeImplementedClaims.IdClaim, authorId.ToString());
     var identity = new ClaimsIdentity(Enumerable.Repeat(claim, 1));
     var claimsprincipal = new ClaimsPrincipal(identity);
     return claimsprincipal;
 }
        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += (sender, e) =>
            {
                HttpContext httpContext = ((HttpApplication)sender).Context;

                dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
                    new HttpContextWrapper(httpContext),
                    rawSignedRequest =>
                    {
                        FacebookConfiguration config = GlobalFacebookConfiguration.Configuration;
                        FacebookClient client = config.ClientProvider.CreateClient();
                        return client.ParseSignedRequest(rawSignedRequest);
                    });

                if (signedRequest != null)
                {
                    string userId = signedRequest.user_id;
                    if (!String.IsNullOrEmpty(userId))
                    {
                        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) }));
                        Thread.CurrentPrincipal = principal;
                        httpContext.User = principal;
                    }
                }
            };
        }
Example #24
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
        {
            loggerfactory.AddConsole(LogLevel.Information);

            app.UseCookieAuthentication(options =>
            {
                options.AutomaticAuthenticate = true;
            });

            app.Run(async context =>
            {
                if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                {
                    var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") }, CookieAuthenticationDefaults.AuthenticationScheme));
                    await context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);

                    context.Response.ContentType = "text/plain";
                    await context.Response.WriteAsync("Hello First timer");
                    return;
                }

                context.Response.ContentType = "text/plain";
                await context.Response.WriteAsync("Hello old timer");
            });
        }
 public Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
 {
     var policy = _options.GetPolicy(policyName);
     return (policy == null)
         ? Task.FromResult(false)
         : this.AuthorizeAsync(user, resource, policy);
 }
Example #26
0
        private static CommandResult ProcessResponse(IOptions options, Saml2Response samlResponse)
        {
            var principal = new ClaimsPrincipal(samlResponse.GetClaims(options));

            principal = options.SPOptions.SystemIdentityModelIdentityConfiguration
                .ClaimsAuthenticationManager.Authenticate(null, principal);

            var requestState = samlResponse.GetRequestState(options);

            if(requestState == null && options.SPOptions.ReturnUrl == null)
            {
                throw new ConfigurationErrorsException(MissingReturnUrlMessage);
            }

            return new CommandResult()
            {
                HttpStatusCode = HttpStatusCode.SeeOther,
                Location = requestState?.ReturnUrl ?? options.SPOptions.ReturnUrl,
                Principal = principal,
                RelayData =
                    requestState == null
                    ? null
                    : requestState.RelayData
            };
        }
        public async Task<bool> RequiresConsentAsync(Client client, ClaimsPrincipal user, IEnumerable<string> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (user == null) throw new ArgumentNullException("user");

            if (!client.RequireConsent)
            {
                return false;
            }

            // TODO: validate that this is a correct statement
            if (!client.AllowRememberConsent)
            {
                return true;
            }

            if (scopes == null || !scopes.Any())
            {
                return false;
            }
            
            var consent = await _store.LoadAsync(user.GetSubjectId(), client.ClientId);
            if (consent != null && consent.Scopes != null)
            {
                var intersect = scopes.Intersect(consent.Scopes);
                return !(scopes.Count() == intersect.Count());
            }

            return true;
        }
 public virtual void Authenticated(ClaimsPrincipal principal, IDictionary<string, string> properties, IDictionary<string, object> description)
 {
     Accepted = true;
     Principal = principal;
     Properties = properties;
     Description = description;
 }
Example #29
0
 public ActionResult Authorize()
 {
     var claims = new ClaimsPrincipal(User).Claims.ToArray();
     var identity = new ClaimsIdentity(claims, "Bearer");
     AuthenticationManager.SignIn(identity);
     return new EmptyResult();
 }
Example #30
0
        public async Task ExecuteResultAsync_InvokesSignInAsyncOnConfiguredScheme()
        {
            // Arrange
            var principal = new ClaimsPrincipal();
            var authProperties = new AuthenticationProperties();
            var authenticationManager = new Mock<AuthenticationManager>();
            authenticationManager
                .Setup(c => c.SignInAsync("Scheme1", principal, authProperties))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.RequestServices).Returns(CreateServices());
            httpContext.Setup(c => c.Authentication).Returns(authenticationManager.Object);
            var result = new SignInResult("Scheme1", principal, authProperties);
            var routeData = new RouteData();

            var actionContext = new ActionContext(
                httpContext.Object,
                routeData,
                new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            authenticationManager.Verify();
        }