public async Task <ActionResult> Login(CookieLoginViewModel model)
        {
            var user = await this.userManager.AuthenticateUserWithPasswordAsync(model.Username, model.Password);

            if (user.Identity.IsAuthenticated)
            {
                var cookieIdentity = new SentinelIdentity(DefaultAuthenticationTypes.ApplicationCookie, user.Identity);

                this.Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                this.Authentication.SignIn(
                    new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.AddHours(1),
                    RedirectUri  = model.ReturnUrl
                },
                    cookieIdentity.ToClaimsIdentity());

                if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
                {
                    return(this.Redirect(model.ReturnUrl));
                }
            }

            return(this.View(model));
        }
示例#2
0
        public void ConvertToIdentity_WhenGivenValidJwt_ReturnsValidIdentity(string expectedAlgorithm, string expectedAudience, string expectedIssuer, long expectedValidFrom, long expectedExpires, string expectedSubject, string[] expectedRoles, string token)
        {
            var jwt            = new JsonWebToken(token);
            var cookieIdentity = new SentinelIdentity(DefaultAuthenticationTypes.ApplicationCookie, jwt);

            CollectionAssert.AreEquivalent(expectedRoles, cookieIdentity.Claims.Where(x => x.Type == "role").Select(x => x.Value).ToArray());
        }
示例#3
0
        /// <summary>Validates the refresh token.</summary>
        /// <param name="refreshTokens">The refresh tokens to validate against.</param>
        /// <param name="token">The token.</param>
        /// <returns>The token principal if valid, <c>null</c> otherwise.</returns>
        public async Task <TokenValidationResult <IRefreshToken> > ValidateRefreshToken(IEnumerable <IRefreshToken> refreshTokens, string token)
        {
            var entity = refreshTokens.FirstOrDefault(x => this.configuration.CryptoProvider.ValidateHash(token, x.Token));

            if (entity != null)
            {
                var identity = new SentinelIdentity(
                    AuthenticationType.OAuth,
                    new SentinelClaim(ClaimType.Name, entity.Subject),
                    new SentinelClaim(ClaimType.Client, entity.ClientId),
                    new SentinelClaim(ClaimType.RedirectUri, entity.RedirectUri));

                if (entity.Scope != null)
                {
                    identity.AddClaim(ClaimType.Scope, string.Join(" ", entity.Scope));
                }

                if (identity.IsAuthenticated)
                {
                    return(new TokenValidationResult <IRefreshToken>(new SentinelPrincipal(identity), entity));
                }
            }

            return(new TokenValidationResult <IRefreshToken>(SentinelPrincipal.Anonymous, null));
        }
示例#4
0
        public async Task <ActionResult> AuthorizeClient(OAuthAuthorizeViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(await Task.FromResult(this.View("Authorize", model)));
            }

            // Redirect user back to application with an error message if it rejects
            if (!model.Grant)
            {
                return(await Task.FromResult(this.Redirect($"{model.RedirectUri}?error=access_denied&error_description=User does not grant access&state={model.State}")));
            }

            // Redirect user if it is no longer authenticated
            if (!this.Authentication.User.Identity.IsAuthenticated)
            {
                this.Authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);

                return(await Task.FromResult(new HttpUnauthorizedResult()));
            }

            // Log in user with new authentication type
            var identity = new SentinelIdentity(OAuthDefaults.AuthenticationType, this.Authentication.User.Identity);

            this.Authentication.SignOut(OAuthDefaults.AuthenticationType);
            this.Authentication.SignIn(identity.ToClaimsIdentity());

            return(await Task.FromResult(new EmptyResult()));
        }
示例#5
0
        public void Serialize_WhenGivenValidIdentity_ShouldReturnCorrectJson()
        {
            var i = new SentinelIdentity(AuthenticationType.OAuth, new SentinelClaim(ClaimType.Name, "ovea"));

            var json = JsonConvert.SerializeObject(i);

            Console.WriteLine(json);

            Assert.AreEqual("{\"AuthenticationType\":\"OAuth\",\"Claims\":[{\"Type\":\"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name\",\"Alias\":null,\"Value\":\"ovea\"}],\"IsAuthenticated\":true,\"Name\":\"ovea\"}", json);
        }
        public virtual Task SignIn(AuthorizeViewModel model)
        {
            var oauthIdentity = new SentinelIdentity(OAuthDefaults.AuthenticationType, this.Authentication.User.Identity);

            this.Authentication.SignOut(OAuthDefaults.AuthenticationType);
            this.Authentication.SignIn(new AuthenticationProperties()
            {
                RedirectUri = model.RedirectUri
            }, oauthIdentity.ToClaimsIdentity());

            return(Task.FromResult <object>(null));
        }
 /// <summary>Process an individual request.</summary>
 /// <param name="context">The context.</param>
 /// <returns>A Task.</returns>
 public override async Task Invoke(IOwinContext context)
 {
     if (context.Authentication.User != null && context.Authentication.User.Identity.IsAuthenticated)
     {
         context.Response.ContentType = "application/json";
         var identity = new SentinelIdentity(context.Authentication.User.Identity);
         await context.Response.WriteAsync(JsonConvert.SerializeObject(identity.ToIdentityResponse()));
     }
     else
     {
         context.Response.StatusCode  = (int)HttpStatusCode.Unauthorized;
         context.Response.ContentType = "application/json";
         context.Response.Headers["WWW-Authenticate"] = string.Empty;
         await context.Response.WriteAsync(JsonConvert.SerializeObject(new ErrorResponse(ErrorCode.InvalidToken)));
     }
 }
        /// <summary>
        /// Creates an authorization code.
        /// </summary>
        /// <param name="context">The authentication context.</param>
        /// <returns/>
        public void CreateAuthorizationCode(AuthenticationTokenCreateContext context)
        {
            this.options.Logger.DebugFormat("Creating authorization code for client '{0}' and redirect uri '{1}'", context.Request.Query["client_id"], context.Request.Query["redirect_uri"]);

            var tcs = new TaskCompletionSource <string>();

            Task.Run(
                async() =>
            {
                try
                {
                    var identity = new SentinelIdentity(AuthenticationType.OAuth, context.Ticket.Identity.Claims.Select(x => new SentinelClaim(x.Type, x.Value)).ToArray());

                    // Overwrite client claim
                    identity.RemoveClaim(x => x.Type == ClaimType.Client);
                    identity.AddClaim(ClaimType.Client, context.Request.Query["client_id"]);

                    // Generate code
                    var createResult =
                        await
                        this.options.TokenManager.CreateAuthorizationCodeAsync(
                            new SentinelPrincipal(identity),
                            this.options.AuthorizationCodeLifetime,
                            context.Request.Query["redirect_uri"],
                            !string.IsNullOrEmpty(context.Request.Query["scope"])
                                    ? context.Request.Query["scope"].Split(' ')
                                    : null);

                    tcs.SetResult(createResult.Token);
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }).ConfigureAwait(false);

            context.SetToken(tcs.Task.Result);

            this.options.Logger.Debug("Created authorization code");
        }