protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
            bool shouldSignin = signin != null;
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
            bool shouldSignout = signout != null;

            if (!(shouldSignin || shouldSignout))
            {
                return;
            }

            AuthenticationTicket model = await AuthenticateAsync();

            try
            {
                if (shouldSignin)
                {
                }
            }
            catch
            {
                throw;
            }
        }
        public void SignIn_SetsKey()
        {
            IOwinContext context = new OwinContext();

            context.Authentication.SignIn(new ClaimsIdentity("foo"), new ClaimsIdentity("bar"));
            AuthenticationResponseGrant grant = context.Authentication.AuthenticationResponseGrant;

            Assert.Equal("foo", grant.Principal.Identities.First().AuthenticationType);
            Assert.Equal("bar", grant.Principal.Identities.Skip(1).First().AuthenticationType);
            Assert.NotNull(grant.Properties);
        }
 public StubOwinMiddleware(
     int statusCode,
     AuthenticationResponseChallenge challenge = null,
     AuthenticationResponseRevoke revoke       = null,
     AuthenticationResponseGrant grant         = null)
     : base(null)
 {
     this.statusCode = statusCode;
     this.challenge  = challenge;
     this.revoke     = revoke;
     this.grant      = grant;
 }
        public void SignInAndSignOut_Deduplicates()
        {
            IOwinContext context = new OwinContext();

            context.Authentication.SignIn(new ClaimsIdentity("foo"), new ClaimsIdentity("bar"));
            context.Authentication.SignOut("foo");

            AuthenticationResponseGrant grant = context.Authentication.AuthenticationResponseGrant;

            Assert.Equal("bar", grant.Principal.Identities.First().AuthenticationType);

            Assert.Equal(new[] { "foo" }, context.Get <string[]>("security.SignOut"));
            Assert.NotNull(grant.Properties);
        }
Example #5
0
        protected override async Task ApplyResponseGrantAsync()
        {
            // only successful results of an authorize request are altered
            if (_clientContext == null ||
                _authorizeEndpointRequest == null ||
                Response.StatusCode != 200)
            {
                return;
            }

            // only apply with signin of matching authentication type
            AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);

            if (signin == null)
            {
                return;
            }


            DateTimeOffset currentUtc = Options.SystemClock.UtcNow;

            signin.Properties.IssuedUtc  = currentUtc;
            signin.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);

            // associate client_id with access token
            signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId;

            var accessTokenContext = new AuthenticationTokenCreateContext(
                Context,
                Options.AccessTokenFormat,
                new AuthenticationTicket(signin.Identity, signin.Properties));

            await Options.AccessTokenProvider.CreateAsync(accessTokenContext);

            string accessToken = accessTokenContext.Token;

            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = accessTokenContext.SerializeTicket();
            }

            DateTimeOffset?accessTokenExpiresUtc = accessTokenContext.Ticket.Properties.ExpiresUtc;

            var authResponseContext = new OAuthAuthenticatedTokenContext(
                Context,
                accessToken);

            await Options.Provider.Authenticated(authResponseContext);
        }
        /// <summary>
        /// Signs in a user by username and password + confirms the identity.
        /// </summary>
        /// <typeparam name="TUser"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="signInManager"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="isPersistent"></param>
        /// <param name="shouldLockout"></param>
        /// <returns></returns>
        public static async Task <SignInStatus> PasswordSignInAndConfirmAsync <TUser, TKey>(this SignInManager <TUser, TKey> signInManager, string userName, string password, bool isPersistent, bool shouldLockout)
            where TUser : class, IUser <TKey>
            where TKey : IEquatable <TKey>, IConvertible
        {
            SignInStatus status = await signInManager.PasswordSignInAsync(userName, password, isPersistent, shouldLockout);

            if (status == SignInStatus.Success)
            {
                // We have to override the existing grant with a new one, as we are adding
                // a new claim
                TUser user = await signInManager.UserManager.FindByNameAsync(userName);

                string userIdString = signInManager.ConvertIdToString(user.Id);
                AuthenticationResponseGrant grant = signInManager.AuthenticationManager.AuthenticationResponseGrant;
                grant.Identity.AddClaim(new Claim(DoubleConfirmIdentityConstants.ClaimType, userIdString));
                signInManager.AuthenticationManager.SignIn(grant.Properties, grant.Identity);
            }
            return(status);
        }
Example #7
0
        public async Task GivenNextMiddlewareGrantsAuth_ItDropsForceSslCookie(string protocol, bool secure)
        {
            // Arrange
            var context = Fakes.CreateOwinContext();
            var next    = Fakes.CreateOwinMiddleware();
            var app     = new AppBuilder();
            var grant   = new AuthenticationResponseGrant(new ClaimsIdentity(), new AuthenticationProperties());

            next.Setup(n => n.Invoke(context))
            .Returns <IOwinContext>(c =>
            {
                c.Authentication.AuthenticationResponseGrant = grant;
                return(Task.FromResult <object>(null));
            });
            context.Request
            .SetUrl(protocol + "://nuget.local/foo/bar/baz?qux=qooz");
            var middleware = new ForceSslWhenAuthenticatedMiddleware(next.Object, app, "ForceSSL", 443);

            // Act
            await middleware.Invoke(context);

            // Assert
            OwinAssert.SetsCookie(context.Response, "ForceSSL", "true", secure);
        }
Example #8
0
        /// <summary>
        /// Find response signin details for a specific authentication middleware
        /// </summary>
        /// <param name="authenticationType">The authentication type to look for</param>
        /// <returns>The information instructing the middleware how it should behave</returns>
        public AuthenticationResponseGrant LookupSignin(string authenticationType)
        {
            if (authenticationType == null)
            {
                throw new ArgumentNullException("authenticationType");
            }

            AuthenticationResponseGrant grant = _response.AuthenticationResponseGrant;

            if (grant == null)
            {
                return(null);
            }

            foreach (var claimsIdentity in grant.Principal.Identities)
            {
                if (string.Equals(authenticationType, claimsIdentity.AuthenticationType, StringComparison.Ordinal))
                {
                    return(new AuthenticationResponseGrant(claimsIdentity, grant.Extra ?? new Dictionary <string, string>(StringComparer.Ordinal)));
                }
            }

            return(null);
        }
Example #9
0
        /// <summary>
        /// Find response sign-in details for a specific authentication middleware
        /// </summary>
        /// <param name="authenticationType">The authentication type to look for</param>
        /// <returns>The information instructing the middleware how it should behave</returns>
        public AuthenticationResponseGrant LookupSignIn(string authenticationType)
        {
            if (authenticationType == null)
            {
                throw new ArgumentNullException("authenticationType");
            }

            AuthenticationResponseGrant grant = _context.Authentication.AuthenticationResponseGrant;

            if (grant == null)
            {
                return(null);
            }

            foreach (var claimsIdentity in grant.Principal.Identities)
            {
                if (string.Equals(authenticationType, claimsIdentity.AuthenticationType, StringComparison.Ordinal))
                {
                    return(new AuthenticationResponseGrant(claimsIdentity, grant.Properties ?? new AuthenticationProperties()));
                }
            }

            return(null);
        }
Example #10
0
        public async Task <ActionResult> Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.Login, model.Password);

                if (user != null)
                {
                    ClaimsIdentity claim = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                    var authResponseGrant = new AuthenticationResponseGrant(claim, new AuthenticationProperties());
                    var userPrincipal     = new ClaimsPrincipal(authResponseGrant.Identity);
                    if (userPrincipal.IsInRole("admin"))
                    {
                        AuthenticationManager.SignOut();
                        AuthenticationManager.SignIn(new AuthenticationProperties {
                            IsPersistent = true
                        }, claim);
                        return(RedirectToAction("Index", "Admin"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "You have no permissions to sign in");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "No admin found");
                }
            }
            if (User.Identity.IsAuthenticated)
            {
                AuthenticationManager.SignOut();
            }
            return(View(model));
        }
Example #11
0
 public void Grant(ClaimsIdentity identity, IDictionary <string, string> extra)
 {
     AuthenticationResponseGrant = new AuthenticationResponseGrant(identity, extra);
 }
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
            bool shouldSignin = signin != null;
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
            bool shouldSignout = signout != null;

            if (shouldSignin || shouldSignout || _shouldRenew)
            {
                var cookieOptions = new CookieOptions
                {
                    Domain   = Options.CookieDomain,
                    HttpOnly = Options.CookieHttpOnly,
                    Path     = Options.CookiePath ?? "/",
                };
                if (Options.CookieSecure == CookieSecureOption.SameAsRequest)
                {
                    cookieOptions.Secure = Request.IsSecure;
                }
                else
                {
                    cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always;
                }

                if (shouldSignin)
                {
                    var context = new CookieResponseSignInContext(
                        Context,
                        Options,
                        Options.AuthenticationType,
                        signin.Identity,
                        signin.Properties);

                    DateTimeOffset issuedUtc  = Options.SystemClock.UtcNow;
                    DateTimeOffset expiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);

                    context.Properties.IssuedUtc  = issuedUtc;
                    context.Properties.ExpiresUtc = expiresUtc;

                    Options.Provider.ResponseSignIn(context);

                    if (context.Properties.IsPersistent)
                    {
                        cookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime;
                    }

                    var    model       = new AuthenticationTicket(context.Identity, context.Properties);
                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    Response.Cookies.Append(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }
                else if (shouldSignout)
                {
                    Response.Cookies.Delete(
                        Options.CookieName,
                        cookieOptions);
                }
                else if (_shouldRenew)
                {
                    AuthenticationTicket model = await AuthenticateAsync();

                    model.Properties.IssuedUtc  = _renewIssuedUtc;
                    model.Properties.ExpiresUtc = _renewExpiresUtc;

                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    if (model.Properties.IsPersistent)
                    {
                        cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime;
                    }

                    Response.Cookies.Append(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }

                Response.Headers.Set(
                    HeaderNameCacheControl,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNamePragma,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNameExpires,
                    HeaderValueMinusOne);

                bool shouldLoginRedirect  = shouldSignin && Options.LoginPath.HasValue && Request.Path == Options.LoginPath;
                bool shouldLogoutRedirect = shouldSignout && Options.LogoutPath.HasValue && Request.Path == Options.LogoutPath;

                if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
                {
                    IReadableStringCollection query = Request.Query;
                    string redirectUri = query.Get(Options.ReturnUrlParameter);
                    if (!string.IsNullOrWhiteSpace(redirectUri) &&
                        IsHostRelative(redirectUri))
                    {
                        var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri);
                        Options.Provider.ApplyRedirect(redirectContext);
                    }
                }
            }
        }
Example #13
0
 public void Grant(ClaimsIdentity identity)
 {
     AuthenticationResponseGrant = new AuthenticationResponseGrant(identity, new AuthenticationExtra());
 }
Example #14
0
 public void Grant(ClaimsIdentity identity, AuthenticationExtra extra)
 {
     AuthenticationResponseGrant = new AuthenticationResponseGrant(identity, extra);
 }
Example #15
0
 public void Grant(ClaimsPrincipal principal)
 {
     AuthenticationResponseGrant = new AuthenticationResponseGrant(principal, new AuthenticationExtra());
 }
Example #16
0
 public void Grant(ClaimsPrincipal principal, AuthenticationExtra extra)
 {
     AuthenticationResponseGrant = new AuthenticationResponseGrant(principal, extra);
 }
Example #17
0
        protected override async Task ApplyResponseGrant()
        {
            _logger.WriteVerbose("ApplyResponseGrant");
            AuthenticationResponseGrant signin = Helper.LookupSignin(Options.AuthenticationType);
            bool shouldSignin = signin != null;
            AuthenticationResponseRevoke signout = Helper.LookupSignout(Options.AuthenticationType, Options.AuthenticationMode);
            bool shouldSignout = signout != null;

            if (shouldSignin || shouldSignout || _shouldRenew)
            {
                var cookieOptions = new CookieOptions
                {
                    Domain   = Options.CookieDomain,
                    HttpOnly = Options.CookieHttpOnly,
                    Path     = Options.CookiePath ?? "/",
                };
                if (Options.CookieSecure == CookieSecureOption.SameAsRequest)
                {
                    cookieOptions.Secure = Request.IsSecure;
                }
                else
                {
                    cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always;
                }

                if (shouldSignin)
                {
                    var context = new FormsResponseSignInContext(
                        Response.Environment,
                        Options.AuthenticationType,
                        signin.Identity,
                        signin.Extra);

                    DateTimeOffset issuedUtc  = Options.SystemClock.UtcNow;
                    DateTimeOffset expiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);

                    context.Extra.IssuedUtc  = issuedUtc;
                    context.Extra.ExpiresUtc = expiresUtc;

                    Options.Provider.ResponseSignIn(context);

                    if (context.Extra.IsPersistent)
                    {
                        cookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime;
                    }

                    var    model       = new AuthenticationTicket(context.Identity, context.Extra.Properties);
                    string cookieValue = Options.TicketDataHandler.Protect(model);

                    Response.AddCookie(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }
                else if (shouldSignout)
                {
                    Response.DeleteCookie(
                        Options.CookieName,
                        cookieOptions);
                }
                else if (_shouldRenew)
                {
                    AuthenticationTicket model = await Authenticate();

                    model.Extra.IssuedUtc  = _renewIssuedUtc;
                    model.Extra.ExpiresUtc = _renewExpiresUtc;

                    string cookieValue = Options.TicketDataHandler.Protect(model);

                    if (model.Extra.IsPersistent)
                    {
                        cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime;
                    }

                    Response.AddCookie(
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }

                Response.SetHeader(
                    HeaderNameCacheControl,
                    HeaderValueNoCache);

                Response.SetHeader(
                    HeaderNamePragma,
                    HeaderValueNoCache);

                Response.SetHeader(
                    HeaderNameExpires,
                    HeaderValueMinusOne);

                bool shouldLoginRedirect  = shouldSignin && !string.IsNullOrEmpty(Options.LoginPath) && string.Equals(Request.Path, Options.LoginPath, StringComparison.OrdinalIgnoreCase);
                bool shouldLogoutRedirect = shouldSignout && !string.IsNullOrEmpty(Options.LogoutPath) && string.Equals(Request.Path, Options.LogoutPath, StringComparison.OrdinalIgnoreCase);

                if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
                {
                    IDictionary <string, string[]> query = Request.GetQuery();
                    string[] redirectUri;
                    if (query.TryGetValue(Options.ReturnUrlParameter ?? FormsAuthenticationDefaults.ReturnUrlParameter, out redirectUri) &&
                        redirectUri != null &&
                        redirectUri.Length == 1 &&
                        IsHostRelative(redirectUri[0]))
                    {
                        Response.Redirect(redirectUri[0]);
                    }
                }
            }
        }
Example #18
0
 private Task HandleSignInAsync(AuthenticationResponseGrant context)
 {
     return(HandleSignInAsync(new AuthenticationTicket(context.Identity, context.Properties)));
 }
Example #19
0
        protected override async Task ApplyResponseGrantAsync()
        {
            AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);
            bool shouldSignin = signin != null;
            AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
            bool shouldSignout = signout != null;

            if (!(shouldSignin || shouldSignout || _shouldRenew))
            {
                return;
            }

            AuthenticationTicket model = await AuthenticateAsync();

            try
            {
                var cookieOptions = new CookieOptions
                {
                    Domain   = Options.CookieDomain,
                    HttpOnly = Options.CookieHttpOnly,
                    Path     = Options.CookiePath ?? "/",
                };
                if (Options.CookieSecure == CookieSecureOption.SameAsRequest)
                {
                    cookieOptions.Secure = Request.IsSecure;
                }
                else
                {
                    cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always;
                }

                #region == 登陆,登出,刷新 ==

                // 登陆
                if (shouldSignin)
                {
                    var signInContext = new CookieResponseSignInContext(
                        Context,
                        Options,
                        Options.AuthenticationType,
                        signin.Identity,
                        signin.Properties,
                        cookieOptions);

                    DateTimeOffset issuedUtc;
                    if (signInContext.Properties.IssuedUtc.HasValue)
                    {
                        issuedUtc = signInContext.Properties.IssuedUtc.Value;
                    }
                    else
                    {
                        issuedUtc = Options.SystemClock.UtcNow;
                        signInContext.Properties.IssuedUtc = issuedUtc;
                    }

                    if (!signInContext.Properties.ExpiresUtc.HasValue)
                    {
                        signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
                    }

                    Options.Provider.ResponseSignIn(signInContext);

                    if (signInContext.Properties.IsPersistent)
                    {
                        DateTimeOffset expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan);
                        signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime;
                    }

                    model = new AuthenticationTicket(signInContext.Identity, signInContext.Properties);
                    if (Options.SessionStore != null)
                    {
                        if (_sessionKey != null)
                        {
                            await Options.SessionStore.RemoveAsync(_sessionKey);
                        }
                        _sessionKey = await Options.SessionStore.StoreAsync(model);

                        ClaimsIdentity identity = new ClaimsIdentity(
                            new[] { new Claim(SessionIdClaim, _sessionKey) },
                            Options.AuthenticationType);
                        model = new AuthenticationTicket(identity, null);
                    }

                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    Options.CookieManager.AppendResponseCookie(
                        Context,
                        Options.CookieName,
                        cookieValue,
                        signInContext.CookieOptions);

                    var signedInContext = new CookieResponseSignedInContext(
                        Context,
                        Options,
                        Options.AuthenticationType,
                        signInContext.Identity,
                        signInContext.Properties);

                    Options.Provider.ResponseSignedIn(signedInContext);
                }
                // 登出
                else if (shouldSignout)
                {
                    if (Options.SessionStore != null && _sessionKey != null)
                    {
                        await Options.SessionStore.RemoveAsync(_sessionKey);
                    }

                    var context = new CookieResponseSignOutContext(
                        Context,
                        Options,
                        cookieOptions);

                    Options.Provider.ResponseSignOut(context);

                    Options.CookieManager.DeleteCookie(
                        Context,
                        Options.CookieName,
                        context.CookieOptions);
                }
                // 刷新
                else if (_shouldRenew)
                {
                    model.Properties.IssuedUtc  = _renewIssuedUtc;
                    model.Properties.ExpiresUtc = _renewExpiresUtc;

                    if (Options.SessionStore != null && _sessionKey != null)
                    {
                        await Options.SessionStore.RenewAsync(_sessionKey, model);

                        ClaimsIdentity identity = new ClaimsIdentity(
                            new[] { new Claim(SessionIdClaim, _sessionKey) },
                            Options.AuthenticationType);
                        model = new AuthenticationTicket(identity, null);
                    }

                    string cookieValue = Options.TicketDataFormat.Protect(model);

                    if (model.Properties.IsPersistent)
                    {
                        cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime;
                    }

                    Options.CookieManager.AppendResponseCookie(
                        Context,
                        Options.CookieName,
                        cookieValue,
                        cookieOptions);
                }

                #endregion

                Response.Headers.Set(
                    HeaderNameCacheControl,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNamePragma,
                    HeaderValueNoCache);

                Response.Headers.Set(
                    HeaderNameExpires,
                    HeaderValueMinusOne);

                // 跳转
                bool shouldLoginRedirect  = shouldSignin && Options.LoginPath.HasValue && Request.Path == Options.LoginPath;
                bool shouldLogoutRedirect = shouldSignout && Options.LogoutPath.HasValue && Request.Path == Options.LogoutPath;

                if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200)
                {
                    IReadableStringCollection query = Request.Query;
                    string redirectUri = query.Get(Options.ReturnUrlParameter); // 根据url参数读取 跳转url
                    if (!string.IsNullOrWhiteSpace(redirectUri) &&
                        IsHostRelative(redirectUri))
                    {
                        var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri);
                        Options.Provider.ApplyRedirect(redirectContext);
                    }
                }
            }
            catch (Exception exception)
            {
                CookieExceptionContext exceptionContext = new CookieExceptionContext(Context, Options,
                                                                                     CookieExceptionContext.ExceptionLocation.ApplyResponseGrant, exception, model);
                Options.Provider.Exception(exceptionContext);
                if (exceptionContext.Rethrow)
                {
                    throw;
                }
            }
        }
Example #20
0
        protected override async Task ApplyResponseGrantAsync()
        {
            // only successful results of an authorize request are altered
            if (_clientContext == null ||
                _authorizeEndpointRequest == null ||
                Response.StatusCode != 200)
            {
                return;
            }

            // only apply with signin of matching authentication type
            AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType);

            if (signin == null)
            {
                return;
            }

            var returnParameter = new Dictionary <string, string>();

            if (_authorizeEndpointRequest.IsAuthorizationCodeGrantType)
            {
                DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
                signin.Properties.IssuedUtc  = currentUtc;
                signin.Properties.ExpiresUtc = currentUtc.Add(Options.AuthorizationCodeExpireTimeSpan);

                // associate client_id with all subsequent tickets
                signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId;
                if (!string.IsNullOrEmpty(_authorizeEndpointRequest.RedirectUri))
                {
                    // keep original request parameter for later comparison
                    signin.Properties.Dictionary[Constants.Extra.RedirectUri] = _authorizeEndpointRequest.RedirectUri;
                }

                var context = new AuthenticationTokenCreateContext(
                    Context,
                    Options.AuthorizationCodeFormat,
                    new AuthenticationTicket(signin.Identity, signin.Properties));

                await Options.AuthorizationCodeProvider.CreateAsync(context);

                string code = context.Token;
                if (string.IsNullOrEmpty(code))
                {
                    _logger.WriteError("response_type code requires an Options.AuthorizationCodeProvider implementing a single-use token.");
                    var errorContext = new OAuthValidateAuthorizeRequestContext(Context, Options, _authorizeEndpointRequest, _clientContext);
                    errorContext.SetError(Constants.Errors.UnsupportedResponseType);
                    await SendErrorRedirectAsync(_clientContext, errorContext);

                    return;
                }

                var authResponseContext = new OAuthAuthorizationEndpointResponseContext(
                    Context,
                    Options,
                    new AuthenticationTicket(signin.Identity, signin.Properties),
                    _authorizeEndpointRequest,
                    null,
                    code);

                await Options.Provider.AuthorizationEndpointResponse(authResponseContext);

                foreach (var parameter in authResponseContext.AdditionalResponseParameters)
                {
                    returnParameter[parameter.Key] = parameter.Value.ToString();
                }

                returnParameter[Constants.Parameters.Code] = code;

                if (!String.IsNullOrEmpty(_authorizeEndpointRequest.State))
                {
                    returnParameter[Constants.Parameters.State] = _authorizeEndpointRequest.State;
                }

                string location = string.Empty;
                if (_authorizeEndpointRequest.IsFormPostResponseMode)
                {
                    location = Options.FormPostEndpoint.ToString();
                    returnParameter[Constants.Parameters.RedirectUri] = _clientContext.RedirectUri;
                }
                else
                {
                    location = _clientContext.RedirectUri;
                }

                foreach (var key in returnParameter.Keys)
                {
                    location = WebUtilities.AddQueryString(location, key, returnParameter[key]);
                }

                Response.Redirect(location);
            }
            else if (_authorizeEndpointRequest.IsImplicitGrantType)
            {
                string location = _clientContext.RedirectUri;

                DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
                signin.Properties.IssuedUtc  = currentUtc;
                signin.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);

                // associate client_id with access token
                signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId;

                var accessTokenContext = new AuthenticationTokenCreateContext(
                    Context,
                    Options.AccessTokenFormat,
                    new AuthenticationTicket(signin.Identity, signin.Properties));

                await Options.AccessTokenProvider.CreateAsync(accessTokenContext);

                string accessToken = accessTokenContext.Token;
                if (string.IsNullOrEmpty(accessToken))
                {
                    accessToken = accessTokenContext.SerializeTicket();
                }

                DateTimeOffset?accessTokenExpiresUtc = accessTokenContext.Ticket.Properties.ExpiresUtc;

                var appender = new Appender(location, '#');
                appender
                .Append(Constants.Parameters.AccessToken, accessToken)
                .Append(Constants.Parameters.TokenType, Constants.TokenTypes.Bearer);
                if (accessTokenExpiresUtc.HasValue)
                {
                    TimeSpan?expiresTimeSpan = accessTokenExpiresUtc - currentUtc;
                    var      expiresIn       = (long)(expiresTimeSpan.Value.TotalSeconds + .5);
                    appender.Append(Constants.Parameters.ExpiresIn, expiresIn.ToString(CultureInfo.InvariantCulture));
                }
                if (!String.IsNullOrEmpty(_authorizeEndpointRequest.State))
                {
                    appender.Append(Constants.Parameters.State, _authorizeEndpointRequest.State);
                }

                var authResponseContext = new OAuthAuthorizationEndpointResponseContext(
                    Context,
                    Options,
                    new AuthenticationTicket(signin.Identity, signin.Properties),
                    _authorizeEndpointRequest,
                    accessToken,
                    null);

                await Options.Provider.AuthorizationEndpointResponse(authResponseContext);

                foreach (var parameter in authResponseContext.AdditionalResponseParameters)
                {
                    appender.Append(parameter.Key, parameter.Value.ToString());
                }

                Response.Redirect(appender.ToString());
            }
        }
Example #21
0
 public void Grant(ClaimsPrincipal principal, IDictionary <string, string> extra)
 {
     AuthenticationResponseGrant = new AuthenticationResponseGrant(principal, extra);
 }