Exemplo n.º 1
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();
            }
        }
Exemplo n.º 2
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    bool isValid = false;
                    isValid = true; //This should be the Service/DB call to validate the client id, client secret.
                                    //ValidateApp(context.ClientId, clientSecret);

                    if (isValid)
                    {
                        var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                        oAuthIdentity.AddClaim(new Claim("ClientID", context.ClientId));
                        var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
                        context.Validated(ticket);
                    }
                    else
                    {
                        context.SetError("cannot authentication ");
                        // logger.Error(string.Format("GrantResourceOwnerCredentials(){0}Credentials not valid for ClientID : {1}.", Environment.NewLine, context.ClientId));
                    }
                }
                catch (Exception)
                {
                    context.SetError("Error", "internal server error");
                    //  logger.Error(string.Format("GrantResourceOwnerCredentials(){0}Returned tuple is null for ClientID : {1}.", Environment.NewLine, context.ClientId));
                }
            }));
        }
Exemplo n.º 3
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var authentication = context.OwinContext.Authentication;

            if (authentication == null)
            {
                return(base.GrantClientCredentials(context));
            }
            var user = authentication.User;

            if (user == null)
            {
                return(base.GrantClientCredentials(context));
            }

            var userAccountService = context.OwinContext.Environment.GetUserAccountService <UserAccount>();
            var account            = userAccountService.GetByUsername("users", user.Identity.Name);

            if (account == null)
            {
                return(base.GrantClientCredentials(context));
            }

            var claims = account.GetAllClaims();
            var id     = new System.Security.Claims.ClaimsIdentity(claims, "MembershipReboot");

            context.Validated(id);

            return(base.GrantClientCredentials(context));
        }
Exemplo n.º 4
0
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            var props         = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "client_id", context.ClientId
                },
                {
                    "client_ip", HttpContext.Current.Request.UserHostAddress
                },
                {
                    "browser_type", HttpContext.Current.Request.Browser.Type
                },
                {
                    "browser_version", HttpContext.Current.Request.Browser.Version
                }
            });
            //设置返回值中的refreshtoken过期时间,展示给客户端
            var client  = context.OwinContext.Get <AuthorizationInfo>("client");
            var issued  = DateTime.Now;
            var expired = issued.AddMinutes(Convert.ToDouble(client.refresh_token_life_time));

            props.Dictionary.Add("issued", issued.ToString("yyyy-MM-dd HH:mm:ss"));
            props.Dictionary.Add("expires", expired.ToString("yyyy-MM-dd HH:mm:ss"));
            //授权ticket
            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
            return(base.GrantClientCredentials(context));
        }
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            context.Validated(oAuthIdentity);
            await base.GrantClientCredentials(context);
        }
Exemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var client = context.OwinContext.Get <ClienteApiDto>("oauth:client");
            var user   = client.Usuario;

            if (user != null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Username));
                identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Username));
                identity.AddClaim(new Claim("gID", user.Id.ToString()));
                if (user.KeyRoles.Any())
                {
                    foreach (var role in user.KeyRoles.ToList())
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, role));
                    }
                }
                var props  = CreateProperties(user.Id.ToString());
                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);
            }
            return(Task.FromResult <object>(null));
        }
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var identity = GetClaimsIdentity(context);

            context.Validated(identity);
            return(Task.FromResult <object>(null));
        }
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));

            context.Validated(identity);
            return(Task.FromResult(0));
        }
Exemplo n.º 9
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));
        }
Exemplo n.º 10
0
        public static async Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
        {
            //var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType));
            //context.Validated(identity);

            var clientGuid = Guid.Parse(context.ClientId);
            var appManager = new ApplicationManager();
            var app        = await appManager.GetApplicationByClientId(clientGuid);

            var user = new COHApplicationUser();

            if (app != null)
            {
                user.ClientId        = clientGuid.ToString("N");
                user.ApplicationName = app.Name;
                user.ApplicationId   = app.Id.ToString();
            }

            var userManager = new COHUserManager();
            var identity    = userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType).Result;

            context.Validated(identity);

            return;
        }
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            // create identity
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim("sub", context.ClientId));

            //Adiciona os dados do cliente autenticado, neste caso, o id da organização da tabela dealernet_integrations

            string login;

            using (SimpleInjector.Lifestyles.AsyncScopedLifestyle.BeginScope(_container))
            {
                var userAppService = _container.GetInstance <IUsuarioServico>();
                var objLogin       = userAppService.RetornarPorCPF(context.ClientId);
                login = objLogin.Login;
                identity.AddClaim(new Claim("userLogin", login));
                identity.AddClaim(new Claim("userId", objLogin.Id.ToString()));
            }

            // create metadata to pass on to refresh token provider
            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "as:client_id", context.ClientId }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);

            ////context.Validated(identity);
            //return Task.FromResult<object>(null);
            return(base.GrantClientCredentials(context));
        }
Exemplo n.º 12
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();
            }
        }
Exemplo n.º 13
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    bool isValid = false;
                    isValid = context.ClientId == "1235" && clientSecret == "6779ef20e75817b79602" ? true : false;

                    if (isValid)
                    {
                        var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                        oAuthIdentity.AddClaim(new Claim("ClientID", context.ClientId));
                        var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
                        context.Validated(ticket);
                    }
                    else
                    {
                        context.SetError("Error", "Credentials not valid");
                    }
                }
                catch (Exception)
                {
                    context.SetError("Error", "internal server error");
                }
            }));
        }
        /// <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 Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var companyCode   = context.OwinContext.Get <string>(COMPANY_CODE);
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            oAuthIdentity.AddClaim(new Claim(YEF.Core.Security.ClaimTypes.MerchantCode, companyCode));
            if (!string.IsNullOrEmpty(companyCode))
            {
                var merchantService = ServiceLocator.Instance.GetService <IMerchantService>();
                var totalCount      = 0;
                var merchant        = merchantService.Search(new MerchantFilter {
                    Code = companyCode
                }, out totalCount).FirstOrDefault();
                if (merchant != null)
                {
                    oAuthIdentity.AddClaim(new Claim(YEF.Core.Security.ClaimTypes.MerchantID, merchant.ID.ToString()));
                }
            }
            if (AppContext.DepartmentID.HasValue)
            {
                oAuthIdentity.AddClaim(new Claim(YEF.Core.Security.ClaimTypes.DepartmentId, AppContext.DepartmentID.Value.ToString()));
                oAuthIdentity.AddClaim(new Claim(YEF.Core.Security.ClaimTypes.DepartmentName, AppContext.DepartmentName));
                oAuthIdentity.AddClaim(new Claim(YEF.Core.Security.ClaimTypes.DepartmentCode, AppContext.DepartmentCode));
            }

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));

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

            context.Validated(ticket);

            return(base.GrantClientCredentials(context));
        }
Exemplo n.º 15
0
        private async Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
        {
            var authenticationManager = context.OwinContext.Authentication;
            var authenticateResult    = await authenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);

            context.Validated(new AuthenticationTicket(authenticateResult.Identity, authenticateResult.Properties));
        }
Exemplo n.º 16
0
        /// <summary>
        /// 客户端授权[生成access token]
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            /*
             * var client = _oauthClientService.GetClient(context.ClientId);
             * claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, client.ClientName));
             */
            //验证权限
            int scopeCount = context.Scope.Count;

            if (scopeCount > 0)
            {
                string name = context.Scope[0].ToString();
            }
            //默认权限
            var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            //!!!
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
            var props = new AuthenticationProperties(new Dictionary <string, string> {
                {
                    "client_id", context.ClientId
                },
                {
                    "scope", string.Join(" ", context.Scope)
                }
            });
            var ticket = new AuthenticationTicket(claimsIdentity, props);

            context.Validated(ticket);
            return(base.GrantClientCredentials(context));
        }
Exemplo n.º 17
0
        /// <summary>
        /// 对客户端进行授权
        /// 客户端访问方式必须是"grant_type", "client_credentials"
        /// 暂未具体实现()
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var clientId     = context.OwinContext.Get <string>("clientId");
            var clientSecret = context.OwinContext.Get <string>("clientSecret");
            //验证是授权信息是否正确,并发放授权信息,添加自定的验证方式默认是true
            bool isAuth = true;

            /*
             *
             * 添加自定义的验证逻辑
             *
             */
            if (isAuth)
            {
                var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                //创建授权对象,并记录到HttpContext.Current.User.Identity
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
                //授权安全令牌后,记录当前授权用户id 到会话对象中
                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    { "as:clientId", context.ClientId },
                    { "as:clientSecret", clientSecret }
                });
                //发布授权
                var ticket = new AuthenticationTicket(oAuthIdentity, props);
                context.Validated(ticket);
            }
            //return Task.FromResult<object>(null);
            return(base.GrantClientCredentials(context));
        }
Exemplo n.º 18
0
        /// <summary>
        /// 客户端授权模式 grant_type=client_credentials
        /// 生成 access_token(client_credentials 授权方式)client_id=client0&client_secret=secret0
        /// </summary>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });//GET,POST,PUT,DELETE,PATCH,OPTIONS....

            string clientSecret = context.OwinContext.Get <string>("clientSecret");
            var    client       = Repository.clients.SingleOrDefault(t => t.clientId == context.ClientId && t.clientSecret == clientSecret);

            if (client != null)
            {
                var identity = new ClaimsIdentity(new GenericIdentity(
                                                      context.ClientId, OAuthDefaults.AuthenticationType),
                                                  context.Scope.Select(x => new Claim("urn:oauth:scope", x))
                                                  );

                var props = new AuthenticationProperties(new Dictionary <string, string> {
                    { "自定义参数0", "0" },
                    { "自定义参数1", context.ClientId }
                });//自定义输出参数

                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);
            }
            else
            {
                context.SetError("invalid_client_credentials", "客户端授权失败,clientSecret不正确");
            }

            return(Task.FromResult(0));
        }
Exemplo n.º 19
0
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if (!ObjectId.TryParse(context.ClientId, out var mongoObjectId))
            {
                context.SetError("invalid_request");
                return;
            }
            var client = await _clientManager.FindClientByIdAsync(context.ClientId);

            if (client == null || !client.IsActive)
            {
                context.SetError("invalid_client");
                return;
            }
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType, client.Name, "client_application");

            oAuthIdentity.AddClaim(new Claim("client_id", context.ClientId));
            foreach (var scope in client.Scopes)
            {
                oAuthIdentity.AddClaim(new Claim(CustomClaimTypes.AuthorisedScopes, scope));
            }
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            ticket.Properties.Dictionary.Add("client_id", client.Id);
            context.Validated(ticket);
        }
Exemplo n.º 20
0
        private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
        {
            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x))));

            context.Validated(principal);

            return(Task.FromResult(0));
        }
        /// <summary>
        /// 生成 access_token(client credentials 授权方式)
        /// </summary>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var identity = new ClaimsIdentity(new GenericIdentity(
                context.ClientId, OAuthDefaults.AuthenticationType),
                context.Scope.Select(x => new Claim("urn:oauth:scope", x)));

            context.Validated(identity);
        }
 /// <summary>
 ///     客户端授权[生成access token]
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
 {
     var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.OwinContext.Get<string>("as:client_id")));
     var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties {AllowRefresh = true});
     context.Validated(ticket);
     return base.GrantClientCredentials(context);
 }
Exemplo n.º 23
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var identity = CreateOAuthIdentity(context.ClientId, context.Scope);

            context.Validated(identity);

            return(base.GrantClientCredentials(context));
        }
 public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
 {
     var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "jeremy"));
     var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
     context.Validated(ticket);
     return base.GrantClientCredentials(context);
 }
        private Task GrantClientCredentails(OAuthGrantClientCredentialsContext context)
        {
            var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));

            context.Validated(identity);

            return Task.FromResult(0);
        }
        /// <summary> 生成 access_token(client credentials 授权方式) </summary>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var scopes   = context.Scope.Select(x => new Claim("urn:oauth:scope", x));
            var item     = new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType);
            var identity = new ClaimsIdentity(item, scopes);

            context.Validated(identity);
            await base.GrantClientCredentials(context);
        }
Exemplo n.º 27
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {

            var oauthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oauthIdentity.AddClaim(new Claim("scope", "Register"));
            var ticket = new AuthenticationTicket(oauthIdentity, new AuthenticationProperties());
            context.Validated(ticket);
            return base.GrantClientCredentials(context);
        }
Exemplo n.º 28
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var original = (ClaimsIdentity)context.Request.User.Identity;
            var identity = new ClaimsIdentity(original.AuthenticationType);

            identity.AddClaim(new Claim(original.NameClaimType, original.Name));
            context.Validated(identity);
            return(Task.FromResult(0));
        }
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            var ticket        = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            context.Validated(ticket);

            await base.GrantClientCredentials(context);
        }
Exemplo n.º 30
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");
        }
Exemplo n.º 31
0
        /// <summary>
        ///  clientId, clientSecret认证 "grant_type": "client_credentials"
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            context.Validated(ticket);
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 32
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(context.OwinContext.Get <string>("idUser"), OAuthDefaults.AuthenticationType));

            context.Validated(new AuthenticationTicket(identity, null));

            var fromResult = Task.FromResult(0);

            return(fromResult);
        }
Exemplo n.º 33
0
        /// <summary>
        /// 生成 access_token(client credentials 授权方式)
        /// </summary>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var identity = new ClaimsIdentity(new GenericIdentity(
                                                  context.ClientId, OAuthDefaults.AuthenticationType),
                                              context.Scope.Select(x => new Claim("urn:oauth:scope", x)));

            identity.AddClaim(new Claim(ClaimTypes.Sid, "10086"));

            context.Validated(identity);
        }
        /// <summary>
        /// 客户证书授予
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Role, string.Join(" ", context.Scope)));

            context.Validated(identity);

            return(Task.FromResult <object>(null));
        }
Exemplo n.º 35
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var OAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            OAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "Yeweimi"));
            var ticket = new AuthenticationTicket(OAuthIdentity, new AuthenticationProperties());

            context.Validated(ticket);
            return(base.GrantClientCredentials(context));
        }
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context) {
            var identity = new ClaimsIdentity(AuthenticationType.Anonymous);
            var systemUtc = new SystemClock().UtcNow;
            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties {
                IssuedUtc = systemUtc,
                ExpiresUtc = systemUtc.AddMinutes(20)
            });
            context.Validated(ticket);

            return base.GrantClientCredentials(context);
        }
        /// <summary>
        /// 当客户端Id与客户端密钥验证通过后,生成在线票据令牌
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
            identity.AddClaims(context.Scope.Select(m => new Claim("urn:oauth:scope", m)));

            AuthenticationProperties properties = new AuthenticationProperties(
                new Dictionary<string, string>() { { "as:client_id", context.ClientId } });
            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
            context.Validated(ticket);
            return Task.FromResult(0);
        }
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if(context.ClientId != null)
            {
                var id = new ClaimsIdentity(context.Options.AuthenticationType);
                id.AddClaim(new Claim("sub", context.ClientId));
                id.AddClaim(new Claim("role", "user"));
                context.Validated(id);
            }

            return Task.FromResult(0);
        }
Exemplo n.º 39
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            _clientId = context.ClientId;

            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "App"));
            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { "as:client_id", context.ClientId }
                });
            var ticket = new AuthenticationTicket(oAuthIdentity, props);
            context.Validated(ticket);

            return base.GrantClientCredentials(context);
        }
Exemplo n.º 40
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();
            }

        }
        /// <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");
        }
        //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);
        }
 /// <summary>
 /// 客户端授权[生成access token]
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
 {
     /*
        var client = _oauthClientService.GetClient(context.ClientId);
        claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, client.ClientName));
      */
     //验证权限
     int scopeCount = context.Scope.Count;
     if (scopeCount > 0)
     {
         string name = context.Scope[0].ToString();
     }
     //默认权限
     var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     //!!!
     claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
     var props = new AuthenticationProperties(new Dictionary<string, string> {
                     {
                         "client_id",context.ClientId
                     },
                     {
                         "scope",string.Join(" ",context.Scope)
                     }
                 });
     var ticket = new AuthenticationTicket(claimsIdentity, props);
     context.Validated(ticket);
     return base.GrantClientCredentials(context);
 }