// /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 <bool> InvokeAuthorizeEndpoint()
        {
            _logger.WriteVerbose("InvokeAuthorizeEndpoint");

            var authorizeRequest = new AuthorizeRequest(Request.GetQuery());
            var clientIdContext  = new OAuthValidateClientCredentialsContext(
                Request.Environment,
                authorizeRequest.ClientId,
                null,
                authorizeRequest.RedirectUri);

            await Options.Provider.ValidateClientCredentials(clientIdContext);

            if (clientIdContext.IsValidated)
            {
                authorizeRequest.RedirectUri = clientIdContext.RedirectUri;
                _authorizeRequest            = authorizeRequest;
            }

            var authorizeEndpointContext = new OAuthAuthorizeEndpointContext(Request.Environment);
            await Options.Provider.AuthorizeEndpoint(authorizeEndpointContext);

            return(authorizeEndpointContext.IsRequestCompleted);
        }
 /// <summary>
 /// Called at the final stage of an incoming Authorize endpoint request before the execution continues on to the web application component 
 /// responsible for producing the html response. Anything present in the OWIN pipeline following the Authorization Server may produce the
 /// response for the Authorize page. If running on IIS any ASP.NET technology running on the server may produce the response for the 
 /// Authorize page. If the web application wishes to produce the response directly in the AuthorizeEndpoint call it may write to the 
 /// context.Response directly and should call context.RequestCompleted to stop other handlers from executing. If the web application wishes
 /// to grant the authorization directly in the AuthorizeEndpoint call it cay call context.OwinContext.Authentication.SignIn with the
 /// appropriate ClaimsIdentity and should call context.RequestCompleted to stop other handlers from executing.
 /// </summary>
 /// <param name="context">The context of the event carries information in and results out.</param>
 /// <returns>Task to enable asynchronous execution</returns>
 public virtual Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
 {
     return OnAuthorizeEndpoint.Invoke(context);
 }
Example #6
0
 /// <summary>
 /// Called at the final stage of an incoming Authorize endpoint request before the execution continues on to the web application component
 /// responsible for producing the html response. Anything present in the OWIN pipeline following the Authorization Server may produce the
 /// response for the Authorize page. If running on IIS any ASP.NET technology running on the server may produce the response for the
 /// Authorize page. If the web application wishes to produce the response directly in the AuthorizeEndpoint call it may write to the
 /// context.Response directly and should call context.RequestCompleted to stop other handlers from executing. If the web application wishes
 /// to grant the authorization directly in the AuthorizeEndpoint call it cay call context.OwinContext.Authentication.SignIn with the
 /// appropriate ClaimsIdentity and should call context.RequestCompleted to stop other handlers from executing.
 /// </summary>
 /// <param name="context">The context of the event carries information in and results out.</param>
 /// <returns>Task to enable asynchronous execution</returns>
 public virtual Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
 {
     return(OnAuthorizeEndpoint.Invoke(context));
 }
 public override Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
 {
     return base.AuthorizeEndpoint(context);
 }
        private async Task <bool> InvokeAuthorizeEndpointAsync()
        {
            var authorizeRequest = new AuthorizeEndpointRequest(Request.Query);

            var clientContext = new OAuthValidateClientRedirectUriContext(
                Context,
                Options,
                authorizeRequest.ClientId,
                authorizeRequest.RedirectUri);

            if (!String.IsNullOrEmpty(authorizeRequest.RedirectUri))
            {
                bool acceptableUri = true;
                Uri  validatingUri;
                if (!Uri.TryCreate(authorizeRequest.RedirectUri, UriKind.Absolute, out validatingUri))
                {
                    // The redirection endpoint URI MUST be an absolute URI
                    // http://tools.ietf.org/html/rfc6749#section-3.1.2
                    acceptableUri = false;
                }
                else if (!String.IsNullOrEmpty(validatingUri.Fragment))
                {
                    // The endpoint URI MUST NOT include a fragment component.
                    // http://tools.ietf.org/html/rfc6749#section-3.1.2
                    acceptableUri = false;
                }
                else if (!Options.AllowInsecureHttp &&
                         String.Equals(validatingUri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
                {
                    // The redirection endpoint SHOULD require the use of TLS
                    // http://tools.ietf.org/html/rfc6749#section-3.1.2.1
                    acceptableUri = false;
                }
                if (!acceptableUri)
                {
                    clientContext.SetError(Constants.Errors.InvalidRequest);
                    return(await SendErrorRedirectAsync(clientContext, clientContext));
                }
            }

            await Options.Provider.ValidateClientRedirectUri(clientContext);

            if (!clientContext.IsValidated)
            {
                _logger.WriteVerbose("Unable to validate client information");
                return(await SendErrorRedirectAsync(clientContext, clientContext));
            }

            var validatingContext = new OAuthValidateAuthorizeRequestContext(
                Context,
                Options,
                authorizeRequest,
                clientContext);

            if (string.IsNullOrEmpty(authorizeRequest.ResponseType))
            {
                _logger.WriteVerbose("Authorize endpoint request missing required response_type parameter");
                validatingContext.SetError(Constants.Errors.InvalidRequest);
            }
            else if (!authorizeRequest.IsAuthorizationCodeGrantType &&
                     !authorizeRequest.IsImplicitGrantType)
            {
                _logger.WriteVerbose("Authorize endpoint request contains unsupported response_type parameter");
                validatingContext.SetError(Constants.Errors.UnsupportedResponseType);
            }
            else
            {
                await Options.Provider.ValidateAuthorizeRequest(validatingContext);
            }

            if (!validatingContext.IsValidated)
            {
                // an invalid request is not processed further
                return(await SendErrorRedirectAsync(clientContext, validatingContext));
            }

            _clientContext            = clientContext;
            _authorizeEndpointRequest = authorizeRequest;

            var authorizeEndpointContext = new OAuthAuthorizeEndpointContext(Context, Options);

            await Options.Provider.AuthorizeEndpoint(authorizeEndpointContext);

            return(authorizeEndpointContext.IsRequestCompleted);
        }
 public Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
 {
     throw new NotImplementedException();
 }
        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();
        }
 bool HasSupportedScope(OAuthAuthorizeEndpointContext context, string supportedScope)
 {
     return !context.AuthorizeRequest.Scope.Any() ||
            context.AuthorizeRequest.Scope.Any(scope => scope.Equals(supportedScope));
 }
        async Task<string> TryGetRawJwtTokenAsync(OAuthAuthorizeEndpointContext context)
        {
            string jwt;

            if (context.Request.IsPost())
            {
                IFormCollection formCollection = await context.Request.ReadFormAsync();

                jwt = formCollection.Get(_options.JwtOptions.JwtTokenParameterName);
            }
            else if (context.Request.IsGet())
            {
                jwt = context.Request.Query.Get(_options.JwtOptions.JwtTokenParameterName);
            }
            else
            {
                jwt = "";
            }

            return jwt;
        }