コード例 #1
0
        private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
        {
            //Get userName from Database by given clientId
            string userName = _identityValidator.GetUserName(context.ClientId);

            if (userName != null)
            {
                ClaimsIdentity identity = new ClaimsIdentity(new[] { new Claim(ClaimsIdentity.DefaultNameClaimType, userName) }, OAuthDefaults.AuthenticationType);

                //Get roles from Database by given userName
                List <string> roles = _identityValidator.GetRoles(userName);

                if (roles == null)
                {
                    context.Rejected();
                }
                else
                {
                    foreach (string cunRole in roles)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, cunRole));
                    }
                    context.Validated(identity);
                }
            }
            else
            {
                context.Rejected();
            }

            return(Task.FromResult(0));
        }
コード例 #2
0
        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "client_credentials". This occurs when a registered client
        ///             application wishes to acquire an "access_token" to interact with protected resources on it's own behalf, rather than on behalf of an authenticated user.
        ///             If the web application supports the client credentials it may assume the context.ClientId has been validated by the ValidateClientAuthentication call.
        ///             To issue an access token the context.Validated must be called with a new ticket containing the claims about the client application which should be associated
        ///             with the access token. The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers.
        ///             The default behavior is to reject this grant type.
        ///             See also http://tools.ietf.org/html/rfc6749#section-4.4.2
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>Task to enable asynchronous execution</returns>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            this.options.Logger.DebugFormat("Authenticating client credentials flow for application '{0}'", context.ClientId);

            if (context.Scope == null || !context.Scope.Any())
            {
                this.options.Logger.Warn("No scope/redirect uri was specified in the request. Request is invalid.");

                context.Rejected();

                return;
            }

            // Store scope in context
            context.OwinContext.GetOAuthContext().Scope = context.Scope;

            // Authenticate client
            var client = await this.options.ClientManager.AuthenticateClientAsync(context.ClientId, context.Scope);

            // Add grant type claim

            //var claims = client.FindAll(Constants.ClaimType.GrantType);
            //if (claims != null && claims.Count() > 0)
            //{
            //    foreach (var c in claims)
            //    {
            //        client.RemoveClaim(c);
            //    }
            //}
            client.RemoveClaim(x => x.Type == Constants.ClaimType.GrantType);
            client.AddClaim(new Claim(Constants.ClaimType.GrantType, Constants.GrantTypes.ClientCredentials));

            if (client.IsAuthenticated)
            {
                if (client.HasClaim(x => x.Type == Constants.ClaimType.RedirectUri))
                {
                    context.OwinContext.GetOAuthContext().RedirectUri = client.Claims.First(x => x.Type == Constants.ClaimType.RedirectUri).Value;
                }
                else
                {
                    this.options.Logger.Warn("Client '{context.ClientId}' does not have a valid redirect uri, validation will not work.");
                }

                var ticket = new AuthenticationTicket(client, new AuthenticationProperties());

                context.Validated(ticket);

                this.options.Logger.DebugFormat("Client '{0}' was successfully authenticated", context.ClientId);

                return;
            }

            context.Rejected();

            this.options.Logger.Warn("Client could not be authenticated");
        }
コード例 #3
0
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var app =
                await new ApplicationDbContext().Apps.FirstOrDefaultAsync(c => c.ClientId == context.ClientId);

            if (app != null)
            {
                var user = await new ApplicationDbContext().Users.FirstOrDefaultAsync(u => u.UserName == app.Username);

                var identity = new ClaimsIdentity("SidekickOAuth");
                var claims   = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.Email, user.Email),
                    new Claim(ClaimTypes.MobilePhone, user.PhoneNumber),
                    new Claim(ClaimTypes.Sid, user.Id),
                    new Claim(ClaimTypes.GivenName, user.Fullname),


                    new Claim("sidekick.client.name", app.Username),
                    new Claim("sidekick.client.appId", app.Id.ToString()),
                    new Claim("sidekick.client.appName", app.Name),
                    new Claim("sidekick.client.meta", app.Meta),
                    new Claim("sidekick.client.istrusted", app.IsTrusted.ToString()),
                    new Claim(ClaimTypes.Expiration, app.AccessTokenExpiry.ToString()),
                };

                identity.AddClaims(claims);
                context.Validated();
            }
            else
            {
                context.Rejected();
            }
        }
コード例 #4
0
        /// <summary>
        /// Client Credentialsグラント種別のカスタム認証ロジック
        /// TokenEndpointPathへの grant_type=client_credentials アクセスは、こちらに到達する。
        /// ・client_id, client_secret の検証は、(2) ValidateClientAuthenticationで済。
        /// ・クライアントは"access_token"を取得する。
        /// </summary>
        /// <param name="context">OAuthGrantClientCredentialsContext</param>
        /// <returns>Task</returns>
        /// <see cref="https://msdn.microsoft.com/ja-jp/library/dn343586.aspx"/>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if (!ASPNETIdentityConfig.EnableClientCredentialsGrantType)
            {
                throw new NotSupportedException(Resources.ApplicationOAuthBearerTokenProvider.EnableClientCredentialsGrantType);
            }

            // ASP.Net MVC: Creating an OAuth client credentials grant type token endpoint
            // http://www.hackered.co.uk/articles/asp-net-mvc-creating-an-oauth-client-credentials-grant-type-token-endpoint
            //var client = clientService.GetClient(context.ClientId);

            // WEB API 2 OAuth Client Credentials Authentication, How to add additional parameters? - Stack Overflow
            // http://stackoverflow.com/questions/29132031/web-api-2-oauth-client-credentials-authentication-how-to-add-additional-paramet

            try
            {
                ApplicationUser        user = null;
                ApplicationUserManager userManager
                    = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();

                // client_idに対応するApplicationUserを取得する。
                user = await userManager.FindByNameAsync(
                    OAuth2ProviderHelper.GetInstance().GetClientName(context.ClientId));

                if (user == null)
                {
                    // *.configに定義したclient_idの場合は、アカウントが存在しない。
                    // その場合、どうするか?は案件毎に検討する(既定では、既定の管理者ユーザを使用する)。
                    user = await userManager.FindByNameAsync(ASPNETIdentityConfig.AdministratorUID);

                    // ClaimsIdentityを自前で生成する場合、
                    //ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    //・・・
                }

                // ユーザーに対応するClaimsIdentityを生成する。
                ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                    user, DefaultAuthenticationTypes.ExternalBearer);

                // ClaimsIdentityに、その他、所定のClaimを追加する。
                OAuth2ProviderHelper.AddClaim(identity, context.ClientId, "", "", context.Scope);

                // 検証完了
                context.Validated(identity);

                // オペレーション・トレース・ログ出力
                Logging.MyOperationTrace(string.Format("{0}({1}) passed the 'client credentials flow' by {2}({3}).",
                                                       user.Id, user.UserName, context.ClientId, OAuth2ProviderHelper.GetInstance().GetClientName(context.ClientId)));
            }
            catch
            {
                // ユーザーを取得できませんでした。
                context.SetError(
                    "server_error",
                    Resources.ApplicationOAuthBearerTokenProvider.server_error1);

                // 拒否
                context.Rejected();
            }
        }
コード例 #5
0
ファイル: OAuth2Provider.cs プロジェクト: dmitrkov/A2v10
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            NameValueCollection body = ParseBody(context.Request.Body);
            var client = GetClientInfo(body, context);

            if (client == null)
            {
                return(Task.CompletedTask);
            }

            ExpandoObject dataEO = null;

            var strData = body["data"];

            if (strData != null)
            {
                var dataJson = Encrypt.DecryptString_Aes(strData, client.key, client.vector);
                dataEO = JsonConvert.DeserializeObject <ExpandoObject>(dataJson, new ExpandoObjectConverter());
            }
            var strSecret = body["client_secret"];

            if (strSecret != null)
            {
                if (strSecret == client.secret)
                {
                    dataEO = new ExpandoObject();
                    dataEO.Set("client_id", body["client_id"]);
                    dataEO.Set("session_id", body["session_id"]);
                }
            }

            if (dataEO == null || dataEO.Get <String>("client_id") != client.id)
            {
                context.Rejected();
                return(Task.CompletedTask);
            }

            var claims = new List <Claim>();

            foreach (var kv in dataEO.Enumerate())
            {
                claims.Add(new Claim(kv.Key, kv.Value.ToString()));
            }

            var oaClaim = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
            var ticket  = new AuthenticationTicket(oaClaim, new AuthenticationProperties());

            context.Validated(ticket);

            return(Task.CompletedTask);
        }
コード例 #6
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var user = context.Request.Get <ApiV2User>("ApiUser");

            if (user == null)
            {
                context.Rejected();
                context.SetError("unauthorized_client");
                return(Task.CompletedTask);
            }

            var body = ParseBody(context.Request);

            var claims = new List <Claim>
            {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", user.Id.ToString()),
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Name),
                new Claim("client_id", body["client_id"])
            };

            void AddClaimFromBody(String name)
            {
                var val = body[name];

                if (val != null)
                {
                    claims.Add(new Claim(name, val));
                }
            }

            if (user.Segment != null)
            {
                claims.Add(new Claim("Segment", user.Segment));
            }
            if (user.TenantId != 0)
            {
                claims.Add(new Claim("TenantId", user.TenantId.ToString()));
            }

            AddClaimFromBody("session_id");
            AddClaimFromBody("state");

            var oaClaim = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
            var ticket  = new AuthenticationTicket(oaClaim, new AuthenticationProperties());

            context.Validated(ticket);

            return(Task.CompletedTask);
        }
コード例 #7
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            try
            {
                var actorId  = context.Request.Headers["ActorId"];
                var identity = _container.Resolve <ClaimsIdentityProvider>().GetActorIdentity(Guid.Parse(actorId), context.Options.AuthenticationType);
                context.Validated(identity);
                context.Request.Context.Authentication.SignIn(identity);
                return(Task.FromResult(0));
            }
            catch (Exception ex)
            {
                context.Rejected();
                context.SetError(OAuth2Constants.Errors.UnauthorizedClient, ex.Message);
            }

            return(Task.FromResult(0));
        }
コード例 #8
0
        //Todo: this method, seed method
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            bool validated = false;

            OAuthClient oauthClient = context.OwinContext.Get <OAuthClient>(OwinClientKey);

            if (oauthClient != null && oauthClient.AllowedGrant == OAuthGrant.ClientCredentials)
            {
                ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType));

                string[] scopes = { NicksOAuthConstants.ValuesAvailableScope };
                identity.AddClaim(new Claim(NicksOAuthConstants.ScopeClaimType, String.Join(" ", scopes)));

                Guid oauthSessionValue = Guid.NewGuid();
                identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthSessionClaimKey, oauthSessionValue.ToString()));

                identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthClientCredentialsGrantKey, "true"));

                AuthenticationProperties properties = CreateProperties(context.ClientId);
                properties.Dictionary.Add("scope", String.Join(" ", scopes));
                context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5); //Success!
                //properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.

                AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
                //ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.

                context.Validated(ticket);
                //context.Ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.
                validated = true;
            }

            if (!validated)
            {
                context.SetError("Authentication Failed");
                context.Rejected();
            }

            return(Task.FromResult <object>(null));
        }
コード例 #9
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            try
            {
                string ComputerName = context.Request.Headers.FirstOrDefault(x => x.Key == "User-Agent")
                                      .Value.FirstOrDefault();
                ComputerName += " (" + context.Request.RemoteIpAddress + ":" + context.Request.RemotePort + ")";


                var identity = new ClaimsIdentity(new GenericIdentity(ComputerName, context.Options.AuthenticationType), //var identity = new ClaimsIdentity(new GenericIdentity(ComputerName, OAuthDefaults.AuthenticationType),
                                                  context.Scope.Select(x => new Claim(ClaimTypes.System, context.ClientId))
                                                  );
                //var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType),
                //    context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
                context.Validated(identity);
            }
            catch
            {
                context.Rejected();
                context.SetError("error: invalid_client");
            }
            return(Task.FromResult(0));
        }
コード例 #10
0
        //Todo: this method, seed method
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            bool validated = false;

            OAuthClient oauthClient = context.OwinContext.Get<OAuthClient>(OwinClientKey);
            if (oauthClient != null && oauthClient.AllowedGrant == OAuthGrant.ClientCredentials)
            {
                ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType));
                
                string[] scopes = { NicksOAuthConstants.ValuesAvailableScope };
                identity.AddClaim(new Claim(NicksOAuthConstants.ScopeClaimType, String.Join(" ", scopes)));

                Guid oauthSessionValue=Guid.NewGuid();
                identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthSessionClaimKey, oauthSessionValue.ToString()));
                
                identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthClientCredentialsGrantKey, "true"));
                                
                AuthenticationProperties properties = CreateProperties(context.ClientId);
                properties.Dictionary.Add("scope", String.Join(" ", scopes));
                context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5); //Success!
                //properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.
                
                AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);                
                //ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.
                
                context.Validated(ticket);
                //context.Ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.
                validated = true;
            }

            if(!validated)
            {
                context.SetError("Authentication Failed");
                context.Rejected();
            }

            return Task.FromResult<object>(null);
        }
コード例 #11
0
        /// <summary>
        /// Client Credentialsグラント種別のカスタム認証ロジック
        /// TokenEndpointPathへの grant_type=client_credentials アクセスは、こちらに到達する。
        /// ・client_id, client_secret の検証は、(2) ValidateClientAuthenticationで済。
        /// ・クライアントは"access_token"を取得する。
        /// </summary>
        /// <param name="context">OAuthGrantClientCredentialsContext</param>
        /// <returns>Task</returns>
        /// <see cref="https://msdn.microsoft.com/ja-jp/library/dn343586.aspx"/>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if (!ASPNETIdentityConfig.EnableClientCredentialsGrantType)
            {
                throw new NotSupportedException(Resources.ApplicationOAuthBearerTokenProvider.EnableClientCredentialsGrantType);
            }

            // ASP.Net MVC: Creating an OAuth client credentials grant type token endpoint
            // http://www.hackered.co.uk/articles/asp-net-mvc-creating-an-oauth-client-credentials-grant-type-token-endpoint
            // WEB API 2 OAuth Client Credentials Authentication, How to add additional parameters? - Stack Overflow
            // http://stackoverflow.com/questions/29132031/web-api-2-oauth-client-credentials-authentication-how-to-add-additional-paramet

            try
            {
                ApplicationUser        user = null;
                ApplicationUserManager userManager
                    = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();

                // client_idに対応するApplicationUserを取得する。
                user = await userManager.FindByNameAsync(
                    OAuth2Helper.GetInstance().GetClientName(context.ClientId));

                // ClaimsIdentity
                ClaimsIdentity identity = null;
                if (user != null)
                {
                    // User Accountの場合、

                    // ユーザーに対応するClaimsIdentityを生成する。
                    identity = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                    // ClaimsIdentityに、その他、所定のClaimを追加する。
                    identity = OAuth2Helper.AddClaim(identity, context.ClientId, "", context.Scope, "");

                    // オペレーション・トレース・ログ出力
                    Logging.MyOperationTrace(
                        string.Format("{0}({1}) passed the 'client credentials flow' by {2}({3}).",
                                      user.Id, user.UserName, context.ClientId, OAuth2Helper.GetInstance().GetClientName(context.ClientId)));

                    // 検証完了
                    context.Validated(identity);
                }
                else
                {
                    // Client Accountの場合、

                    string clientName = OAuth2Helper.GetInstance().GetClientName(context.ClientId);
                    if (string.IsNullOrEmpty(clientName))
                    {
                        // 検証失敗
                        context.Rejected();
                    }
                    else
                    {
                        // ClaimsIdentityを自前で生成する。
                        identity = new ClaimsIdentity(context.Options.AuthenticationType);
                        // Name Claimを追加
                        identity.AddClaim(new Claim(ClaimTypes.Name, OAuth2Helper.GetInstance().GetClientName(context.ClientId)));
                        // ClaimsIdentityに、その他、所定のClaimを追加する。
                        identity = OAuth2Helper.AddClaim(identity, context.ClientId, "", context.Scope, "");

                        // オペレーション・トレース・ログ出力
                        Logging.MyOperationTrace(string.Format(
                                                     "Passed the 'client credentials flow' by {0}({1}).", context.ClientId, clientName));

                        // 検証完了
                        context.Validated(identity);
                    }
                }
            }
            catch
            {
                // ユーザーを取得できませんでした。
                context.SetError(
                    "server_error",
                    Resources.ApplicationOAuthBearerTokenProvider.server_error1);

                // 拒否
                context.Rejected();
            }
        }
        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "client_credentials". This occurs when a registered client
        ///             application wishes to acquire an "access_token" to interact with protected resources on it's own behalf, rather than on behalf of an authenticated user. 
        ///             If the web application supports the client credentials it may assume the context.ClientId has been validated by the ValidateClientAuthentication call.
        ///             To issue an access token the context.Validated must be called with a new ticket containing the claims about the client application which should be associated
        ///             with the access token. The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers.
        ///             The default behavior is to reject this grant type.
        ///             See also http://tools.ietf.org/html/rfc6749#section-4.4.2
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>Task to enable asynchronous execution</returns>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            this.options.Logger.DebugFormat("Authenticating client credentials flow for application '{0}'", context.ClientId);

            if (context.Scope == null || !context.Scope.Any())
            {
                this.options.Logger.WarnFormat("No scope/redirect uri was specified in the request. Request is invalid.");

                context.Rejected();

                return;
            }

            // Store scope in context
            context.OwinContext.GetOAuthContext().Scope = context.Scope;

            // Authenticate client
            var client = await this.options.ClientManager.AuthenticateClientAsync(context.ClientId, context.Scope);

            // Add grant type claim
            client.Identity.RemoveClaim(x => x.Type == ClaimType.GrantType);
            client.Identity.AddClaim(ClaimType.GrantType, GrantType.ClientCredentials);

            if (client.Identity.IsAuthenticated)
            {
                var ticket = new AuthenticationTicket(client.Identity.AsClaimsIdentity(), new AuthenticationProperties());

                context.Validated(ticket);

                this.options.Logger.DebugFormat("Client '{0}' was successfully authenticated", context.ClientId);

                return;
            }

            context.Rejected();

            this.options.Logger.WarnFormat("Client could not be authenticated");
        }
コード例 #13
0
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var app =
                await new ApplicationDbContext().Apps.FirstOrDefaultAsync(c => c.ClientId == context.ClientId);
            if (app != null)
            {
                var user = await new ApplicationDbContext().Users.FirstOrDefaultAsync(u => u.UserName == app.Username);

                var identity = new ClaimsIdentity("SidekickOAuth");
                var claims = new List<Claim>
                             {
                                 new Claim(ClaimTypes.Name, user.UserName),
                                 new Claim(ClaimTypes.Email, user.Email),
                                 new Claim(ClaimTypes.MobilePhone, user.PhoneNumber),
                                 new Claim(ClaimTypes.Sid, user.Id),
                                 new Claim(ClaimTypes.GivenName, user.Fullname),
        

                                 new Claim("sidekick.client.name", app.Username),
                                 new Claim("sidekick.client.appId", app.Id.ToString()),
                                 new Claim("sidekick.client.appName", app.Name),
                                 new Claim("sidekick.client.meta", app.Meta),
                                 new Claim("sidekick.client.istrusted", app.IsTrusted.ToString()),
                                 new Claim(ClaimTypes.Expiration, app.AccessTokenExpiry.ToString()),


                             };

                identity.AddClaims(claims);
                context.Validated();

            }
            else
            {
                context.Rejected();
            }

        }