// /oauth/authorize
 public override async Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
 {
     if (context.Request.User != null && context.Request.User.Identity.IsAuthenticated)
     {
         // si l'utilisateur est loggé,
         // on crée un ticket d'authent, on crée un authorization code et on fait le redirect
         var redirectUri = context.Request.Query["redirect_uri"];
         var clientId = context.Request.Query["client_id"];
         var authorizeCodeContext = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(context.OwinContext, context.Options.AuthorizationCodeFormat,
             new Microsoft.Owin.Security.AuthenticationTicket((ClaimsIdentity)context.Request.User.Identity, new Microsoft.Owin.Security.AuthenticationProperties(new Dictionary<string, string>
             {
                 {"client_id", clientId},
                 {"redirect_uri", redirectUri}
             })
             {
                 IssuedUtc = DateTimeOffset.UtcNow,
                 ExpiresUtc = DateTimeOffset.UtcNow.Add(context.Options.AuthorizationCodeExpireTimeSpan)
             }));
         await context.Options.AuthorizationCodeProvider.CreateAsync(authorizeCodeContext);
         
         // clear cookies
         var cookies = context.Request.Cookies.ToList();
         foreach (var c in cookies)
         {
             context.Response.Cookies.Delete(c.Key, new Microsoft.Owin.CookieOptions());
         }
         context.Response.Redirect(redirectUri + "?code=" + Uri.EscapeDataString(authorizeCodeContext.Token));
     }
     else
     {
         // si on n'est pas loggé, on redirige vers la page de login
         context.Response.Redirect("/account/login?returnUrl=" + Uri.EscapeDataString(context.Request.Uri.ToString()));
     }
     context.RequestCompleted();
 }
 public override Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
 {
     // The authentication types should be set to "Bearer" while setting up the ClaimsIdentity
     // I have set up basic mandatory ClaimsIdentity. You can add the necessary claims if required.
     System.Security.Claims.ClaimsIdentity ci = new System.Security.Claims.ClaimsIdentity("Bearer");
     context.OwinContext.Authentication.SignIn(ci);
     context.RequestCompleted();
     return Task.FromResult<object>(null);
 }
        /// <summary>
        /// 生成 authorization_code(authorization code 授权方式)、生成 access_token (implicit 授权模式)
        /// </summary>
        public override async Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
        {
            if (context.AuthorizeRequest.IsImplicitGrantType)
            {
                //implicit 授权方式
                var identity = new ClaimsIdentity("Bearer");
                context.OwinContext.Authentication.SignIn(identity);
                context.RequestCompleted();
            }
            else if (context.AuthorizeRequest.IsAuthorizationCodeGrantType)
            {
                //authorization code 授权方式
                var redirectUri = context.Request.Query["redirect_uri"] ?? "/code";
                var clientId = context.Request.Query["client_id"];
                var identity = new ClaimsIdentity(new GenericIdentity(
                    clientId, OAuthDefaults.AuthenticationType));

                var authorizeCodeContext = new AuthenticationTokenCreateContext(
                    context.OwinContext,
                    context.Options.AuthorizationCodeFormat,
                    new AuthenticationTicket(
                        identity,
                        new AuthenticationProperties(new Dictionary<string, string>
                        {
                            {"client_id", clientId},
                            {"redirect_uri", redirectUri}
                        })
                        {
                            IssuedUtc = DateTimeOffset.UtcNow,
                            ExpiresUtc = DateTimeOffset.UtcNow.Add(context.Options.AuthorizationCodeExpireTimeSpan)
                        }));

                await context.Options.AuthorizationCodeProvider.CreateAsync(authorizeCodeContext);
                context.Response.Redirect(redirectUri + "?code=" + Uri.EscapeDataString(authorizeCodeContext.Token));
                context.RequestCompleted();
            }
        }
        private async Task AuthEndPoint(OAuthAuthorizeEndpointContext context)
        {
            var authentication = context.OwinContext.Authentication;
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            //if (authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie).Result?.Identity == null)
            if ( ! context.Request.User.Identity.IsAuthenticated)
            {
                authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);
                context.RequestCompleted();
                return;
            }

            //Since we also do OAuth, we have to sign in the OAuth Identification Type as well
            var user = userManager.FindByName(context.Request.User?.Identity?.Name);

            ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

            authentication.SignIn(oAuthIdentity);
            context.RequestCompleted();
            
            return;
        }
        public override async Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
        {
            string uri = context.Request.Uri.ToString();

            if (string.IsNullOrWhiteSpace(_options.JwtOptions.SupportedScope))
            {
                Error(context, OAuthImplicitFlowError.ServerError, "no supported scope defined");
                return;
            }

            if (!HasSupportedScope(context, _options.JwtOptions.SupportedScope))
            {
                string errorDescription = string.Format("only {0} scope is supported",
                    _options.JwtOptions.SupportedScope);
                Error(context, OAuthImplicitFlowError.Scope, errorDescription);
                return;
            }

            string rawJwt = await TryGetRawJwtTokenAsync(context);

            if (string.IsNullOrWhiteSpace(rawJwt))
            {
                context.OwinContext.Authentication.Challenge(new AuthenticationProperties {RedirectUri = uri});
                return;
            }

            var tokenValidator = new TokenValidator();
            ClaimsPrincipal principal = tokenValidator.Validate(rawJwt, _options.JwtOptions);

            if (!principal.Identity.IsAuthenticated)
            {
                Error(context, OAuthImplicitFlowError.AccessDenied, "unauthorized user, unauthenticated");
                return;
            }

            ClaimsIdentity claimsIdentity = await _options.TransformPrincipal(principal);

            if (!claimsIdentity.Claims.Any())
            {
                Error(context, OAuthImplicitFlowError.AccessDenied, "unauthorized user");
                return;
            }

            ConsentAnswer consentAnswer = await TryGetConsentAnswerAsync(context.Request);

            if (consentAnswer == ConsentAnswer.Rejected)
            {
                Error(context, OAuthImplicitFlowError.AccessDenied, "resource owner denied request");
                return;
            }

            if (consentAnswer == ConsentAnswer.Missing)
            {
                Error(context, OAuthImplicitFlowError.ServerError,
                    "missing consent answer");
                return;
            }


            if (!(consentAnswer == ConsentAnswer.Accepted || consentAnswer == ConsentAnswer.Implicit))
            {
                Error(context, OAuthImplicitFlowError.ServerError,
                    string.Format("invalid consent answer '{0}'", consentAnswer.Display));
                return;
            }

            string appJwtTokenAsBase64 =
                JwtTokenHelper.CreateSecurityTokenDescriptor(claimsIdentity.Claims, _options.JwtOptions)
                    .CreateTokenAsBase64();

            var builder = new UriBuilder(context.AuthorizeRequest.RedirectUri);

            const string tokenType = "bearer";

            var fragmentStringBuilder = new StringBuilder();

            fragmentStringBuilder.AppendFormat("access_token={0}&token_type={1}&state={2}&scope={3}",
                Uri.EscapeDataString(appJwtTokenAsBase64), Uri.EscapeDataString(tokenType),
                Uri.EscapeDataString(context.AuthorizeRequest.State ?? ""),
                Uri.EscapeDataString(_options.JwtOptions.SupportedScope));

            if (consentAnswer == ConsentAnswer.Implicit)
            {
                fragmentStringBuilder.AppendFormat("&consent_type={0}", Uri.EscapeDataString(consentAnswer.Invariant));
            }

            builder.Fragment = fragmentStringBuilder.ToString();

            string redirectUri = builder.Uri.ToString();

            context.Response.Redirect(redirectUri);
            context.RequestCompleted();
        }
        void Error(OAuthAuthorizeEndpointContext context, OAuthImplicitFlowError error, string errorDescription)
        {
            var builder = new UriBuilder(context.AuthorizeRequest.RedirectUri);

            var fragmentBuilder = new StringBuilder();

            fragmentBuilder.AppendFormat("error={0}", Uri.EscapeDataString(error.InvariantName));

            if (!string.IsNullOrWhiteSpace(errorDescription))
            {
                fragmentBuilder.AppendFormat("&error_description={0}", Uri.EscapeDataString(errorDescription));
            }
            if (!string.IsNullOrWhiteSpace(context.AuthorizeRequest.State))
            {
                fragmentBuilder.AppendFormat("&state={0}", Uri.EscapeDataString(context.AuthorizeRequest.State));
            }

            builder.Fragment = fragmentBuilder.ToString();

            string redirectUriWithFragments = builder.Uri.ToString();

            context.Response.Redirect(redirectUriWithFragments);
            context.RequestCompleted();
        }