コード例 #1
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);
        }
コード例 #2
0
        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);
        }
コード例 #3
0
 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);
 }
コード例 #4
0
 /// <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);
 }
コード例 #5
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);
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        /// <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));
        }
        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);
        }
コード例 #9
0
        /// <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);
        }
コード例 #10
0
        private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
        {
            //var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));

            var identity = new ClaimsIdentity(context.Scope.Select(x => new Claim(ProtectedData.roleType, x)),
                                              AuthenticationType.Beaer, ProtectedData.nameType, ProtectedData.roleType);

            identity.AddClaim(new Claim(ProtectedData.nameType, context.ClientId));

            context.Validated(identity);

            return(Task.FromResult(0));
        }
コード例 #11
0
        private Task GrantClientCredetails(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));
        }
コード例 #12
0
        private Task GrantClientCredentials(OAuthGrantClientCredentialsContext arg)
        {
            var identity = new ClaimsIdentity(new GenericIdentity(
                                                  arg.ClientId,
                                                  OAuthDefaults.AuthenticationType
                                                  ),
                                              arg.Scope.Select(key => new Claim("urn:oauth:scope", key))
                                              );

            arg.Validated(identity);

            return(Task.FromResult(0));
        }
コード例 #13
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);
        }
コード例 #14
0
        /// <summary>
        /// Client credentials is used primary server to server authentication
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var scope       = context.OwinContext.GetAutofacLifetimeScope();
            var userService = scope.Resolve <IUserService>();

            ClaimsIdentity addionaloAuthIdentity = await userService.CreateClientClaimsIdentityAsync(context.ClientId);

            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            oAuthIdentity.AddClaims(addionaloAuthIdentity.Claims);
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            context.Validated(ticket);
        }
コード例 #15
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);
        }
コード例 #16
0
ファイル: Startup.Auth.cs プロジェクト: gkpeng19/MyFramework
        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);
        }
コード例 #17
0
ファイル: Startup.Auth.cs プロジェクト: windygu/zcgl
        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);
            context.Validated();
            return(base.GrantClientCredentials(context));
        }
コード例 #18
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            GC_Usuario oGC_Usuario = (from item in this.db.GC_Usuario
                                      where (item.Email == context.ClientId || item.Login == context.ClientId) && item.IsActive
                                      select item).FirstOrDefault();
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, oGC_Usuario.Nome));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Sid, oGC_Usuario.Id.ToString()));

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

            context.Validated(ticket);
            return(base.GrantClientCredentials(context));
        }
コード例 #19
0
        /// <summary>
        /// 创建授权的token信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if (string.IsNullOrEmpty(context.ClientId))
            {
                return(Task.FromResult(0));
            }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
            var properties = CreateProperties(context.ClientId, "clientid");
            var ticket     = new AuthenticationTicket(identity, properties);

            context.Validated(ticket);
            return(Task.FromResult(0));
        }
コード例 #20
0
        /// <summary>
        /// ClientCredentials
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var oAuthIdentity = ClaimsIdentityCreate.GenerateAppIdentity(context.ClientId, "", OAuthDefaults.AuthenticationType);

            //设置角色
            oAuthIdentity.AddClaim(new Claim(oAuthIdentity.RoleClaimType, RoleConfig.AppRole));
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            context.Validated(ticket);
            //设置上下文
            context.OwinContext.Set(_asGrantType, GrantTypes.ClientCredentials);
            context.OwinContext.Set(_asClientID, context.ClientId);

            return(base.GrantClientCredentials(context));
        }
コード例 #21
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            // Extract username defined on "ValidateClientAuthentication" method.
            string userName = context.OwinContext.Get <string>("UserName");

            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, userName));

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

            context.Validated(ticket);

            return(base.GrantClientCredentials(context));
        }
コード例 #22
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var secret = context.OwinContext.Get <string>("clientSecret");
            var client = ClientRepository.Clients.Where(c => c.Id == context.ClientId && c.Secret == secret).FirstOrDefault();

            if (client != null)
            {
                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));
        }
コード例 #23
0
        /// <summary>
        /// 生成 access_token(client credentials 授权方式 - 客户端模式)
        /// 和用户无关,一般用于应用程序和 api 之间的交互场景,比如落网开放出 api,供第三方开发者进行调用数据等
        /// </summary>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var OAuthIdentity = new ClaimsIdentity(new GenericIdentity(
                                                       context.ClientId, OAuthDefaults.AuthenticationType),
                                                   context.Scope.Select(x => new Claim("urn:oauth:scope", x))
                                                   );

            OAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "aud", context.ClientId }
            });
            var ticket = new AuthenticationTicket(OAuthIdentity, props);

            context.Validated(ticket);
        }
コード例 #24
0
        /// <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, "iphone"));
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties()
            {
                IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMilliseconds(Infrastructure.REFREST_INTERVAL)
            });

            context.Validated(ticket);
            return(base.GrantClientCredentials(context));
            //var authidentity = new ClaimsIdentity(new GenericIdentity(context.ClientId, context.Options.AuthenticationType));
            //context.Validated(authidentity);
            //return Task.FromResult<object>(null);
        }
コード例 #25
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
            client.Identity.RemoveClaim(x => x.Type == ClaimType.GrantType);
            client.Identity.AddClaim(ClaimType.GrantType, GrantType.ClientCredentials);

            if (client.Identity.IsAuthenticated)
            {
                if (client.Identity.HasClaim(x => x.Type == ClaimType.RedirectUri))
                {
                    context.OwinContext.GetOAuthContext().RedirectUri = client.Identity.Claims.First(x => x.Type == 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.Identity.AsClaimsIdentity(), 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");
        }
コード例 #26
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));
             */
            var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, "iphone"));
            var ticket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties()
            {
                AllowRefresh = true
            });

            context.Validated(ticket);
            return(base.GrantClientCredentials(context));
        }
コード例 #27
0
ファイル: OAuthProvider.cs プロジェクト: thophamhuu/WB
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var client = ClientContext.FindClient(context.ClientId);

            if (client != null)
            {
                var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, client.ClientName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, client.Roles));

                var props = CreateProperties(client.ClientId);

                var ticket = new AuthenticationTicket(oAuthIdentity, props);
                context.Validated(ticket);
            }

            return(base.GrantClientCredentials(context));
        }
コード例 #28
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));
        }
コード例 #29
0
        /// <summary>
        /// 当客户端请求类型为 "grant_type=client_credentials" 时触发
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private System.Threading.Tasks.Task GrantClientCredetails(OAuthGrantClientCredentialsContext arg)
        {
            YFPLUS_Client client = null;

            using (DSCSYSEntities context = new DSCSYSEntities())
            {
                client = context.YFPLUS_Client.AsNoTracking().AsQueryable().SingleOrDefault(s => s.ClientIdentify == arg.ClientId);
            }
            var claims = new List <Claim>();

            claims.Add(new Claim("ClientID", client.ID + ""));
            claims.AddRange(arg.Scope.Select(x => new Claim("urn:oauth:scope", x)));

            var identity = new ClaimsIdentity(new GenericIdentity(client.Name, OAuthDefaults.AuthenticationType), claims);

            arg.Validated(identity);

            return(Task.FromResult(0));
        }
コード例 #30
0
        // grant type = client_credentials
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var application = context.OwinContext.Get <IApplication>("oh:application");

            if (application != null)
            {
                context.OwinContext.Set("Client_Creds", true);
                ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(identity.NameClaimType, application.Name));
                identity.AddClaim(new Claim("Id", application.Id));
                identity.AddClaim(new Claim(identity.RoleClaimType, "Application"));
                foreach (var extra in application.AdditionalTokenParameters)
                {
                    identity.AddClaim(new Claim(extra.Key, extra.Value));
                }
                var props = new AuthenticationProperties(application.AdditionalResponseParameters);
                context.Validated(new AuthenticationTicket(identity, props));
            }
            return(Task.FromResult <object>(null));
        }
コード例 #31
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var userManager   = context.OwinContext.GetUserManager <ApplicationUserManager>();
            var signInManager = context.OwinContext.GetUserManager <ApplicationSignInManager>();

            var userId = context.OwinContext.Get <Guid>(OAuthNames.UserId);
            var user   = userManager.FindByIdAsync(userId).Result;

            var identity = signInManager.CreateUserIdentity(user);

            var authProps = new AuthenticationProperties();

            authProps.Dictionary.Add(OAuthNames.ClientId, context.ClientId);
            authProps.ExpiresUtc = DateTimeOffset.Now.AddMinutes(120);

            var ticket = new AuthenticationTicket(identity, authProps);

            context.Validated(ticket);

            return(base.GrantClientCredentials(context));
        }
コード例 #32
0
        /// <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));
            List <string> scopes = context.Scope.Where(m => !m.IsMissing()).ToList();

            if (scopes.Any())
            {
                identity.AddClaims(scopes.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));
        }
コード例 #33
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));
        }
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            try
            {
                var owinContext = context.OwinContext;
                var authResult  = await owinContext.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

                var identity = authResult.Identity;
                context.OwinContext.Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                context.Validated(identity);
            }
            catch (Exception ex)
            {
                // ignore, user has no external cookie
                Log.Error(ex, "Error when Granting Client Credentials");
            }
            finally
            {
                await base.GrantClientCredentials(context);
            }
        }
コード例 #35
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));
        }
コード例 #36
0
        //实现客户端模式获取Access Token
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var secret = context.OwinContext.Get <string>("clientSecret");
            var client = ClientRepository.GetClient().Where(c => c.ID == context.ClientId && c.Secret == secret).FirstOrDefault();

            if (client != null)
            {
                var identity = new ClaimsIdentity(
                    new GenericIdentity(context.ClientId,
                                        OAuthDefaults.AuthenticationType),
                    context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
                //支持jwt
                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    {
                        "aud", (context.ClientId == null) ? string.Empty : context.ClientId
                    }
                });
                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);
            }
            return(Task.FromResult(0));
        }
コード例 #37
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()),
                    new Claim("sidekick.client.refreshTokenExpiry", app.RefreshTokenExpiry.ToString()),
                    new Claim("sidekick.client.allowedIps", string.IsNullOrEmpty(app.AllowedIp)?"*":app.AllowedIp),
                };

                identity.AddClaims(claims);
                context.Validated();
            }
            else
            {
                context.Rejected();
            }
        }
コード例 #38
0
        /// <summary>
        /// 客户端模式下对客户端授权逻辑
        /// </summary>
        /// <param name="context">OAuth上下文</param>
        /// <returns></returns>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var client_secret = context.OwinContext.Get <string>(SECRET_KEY);

            var clientRrpository = identityContext.Clients;
            var client           = clientRrpository.FirstOrDefault(e => e.ClientId == context.ClientId);

            if (client != null)
            {
                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.NameIdentifier, context.ClientId),
                };

                var identity = new ClaimsIdentity(
                    claims,
                    OAuthDefaults.AuthenticationType
                    );

                context.Validated(identity);
            }

            return(Task.FromResult(0));
        }
コード例 #39
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if (string.IsNullOrEmpty(context?.ClientId))
            {
                return(base.GrantClientCredentials(context));
            }

            var client = ContainerManager.Resolve <IAuthRepository>().FindClient(context.ClientId);

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

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { client.AllowedOrigin });
            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(base.GrantClientCredentials(context));
        }
コード例 #40
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);
        }
コード例 #41
0
 public Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
 {
     throw new NotImplementedException();
 }
コード例 #42
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);
 }
コード例 #43
0
 public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
 {
     return base.GrantClientCredentials(context);
 }
コード例 #44
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");
        }
コード例 #46
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 virtual Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
 {
     return OnGrantClientCredentials.Invoke(context);
 }
コード例 #47
0
 public override async  Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
 {
     await base.GrantClientCredentials(context);
 }