コード例 #1
0
        //
        // Summary:
        //     Called when a request to the Token endpoint arrives with a "grant_type" of "password".
        //     This occurs when the user has provided name and password credentials directly
        //     into the client application's user interface, and the client application is using
        //     those to acquire an "access_token" and optional "refresh_token". If the web application
        //     supports the resource owner credentials grant type it must validate the context.Username
        //     and context.Password as appropriate. To issue an access token the context.Validated
        //     must be called with a new ticket containing the claims about the resource owner
        //     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.3.2
        //
        // Parameters:
        //   context:
        //     The context of the event carries information in and results out.
        //
        // Returns:
        //     Task to enable asynchronous execution
        public override async Task GrantResourceOwnerCredentials(Microsoft.Owin.Security.OAuth.OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userName = context.UserName;
            var password = context.Password;

            var user = databaseManager.LoginByUsernamePassword(userName, password).ToList();

            if (user == null || user.Count() <= 0)
            {
                context.SetError("invalid_grant", "The user name and password is incorrect");
                return;
            }

            var claims   = new List <System.Security.Claims.Claim>();
            var userInfo = user.FirstOrDefault();

            claims.Add(new System.Security.Claims.Claim(
                           System.Security.Claims.ClaimTypes.Name, userInfo.username));

            // Setting claim identities for OAuth2
            var oAuthClaimIdentity   = new System.Security.Claims.ClaimsIdentity(claims, Microsoft.Owin.Security.OAuth.OAuthDefaults.AuthenticationType);
            var cookiesClaimIdentity = new System.Security.Claims.ClaimsIdentity(claims, Microsoft.Owin.Security.Cookies.CookieAuthenticationDefaults.AuthenticationType);

            // Setting user authentication
            var properties = CreateProperties(userInfo.username);
            var ticket     = new Microsoft.Owin.Security.AuthenticationTicket(oAuthClaimIdentity, properties);

            // Grant access to user
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesClaimIdentity);
        }
コード例 #2
0
        public override async Task GrantResourceOwnerCredentials(Microsoft.Owin.Security.OAuth.OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });


                using (hlaplusEntities con = new hlaplusEntities())
                {
                    var user = con.UserAccounts.Where(u => u.Email == context.UserName).FirstOrDefault();
                    // var userAccount = con.UserAccounts.ToList();
                    // var user=userAccount.Find(u => u.Email.Trim() == context.UserName);

                    if (user == null)
                    {
                        context.SetError("invalid_grant", "The user name is incorrect.");
                        return;
                    }
                    else
                    {
                        if (!BCrypt.Net.BCrypt.Verify(context.Password, user.Password))
                        {
                            context.SetError("invalid_grant", "The Password is incorrect.");
                            return;
                        }
                    }
                }

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

                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                identity.AddClaim(new Claim("sub", context.UserName));

                var props = new AuthenticationProperties(new Dictionary <string, string>
                {
                    {
                        "as:client_id", (context.ClientId == null) ?  context.UserName : context.ClientId
                    },
                    {
                        "userName", context.UserName
                    }
                });

                var db         = new hlaplusEntities();
                var activeuser = db.UserAccounts.Where(u => u.Email == context.UserName).FirstOrDefault();
                //activeuser.LastActivityDate = DateTimeOffset.Now;
                //activeuser.LastLoginDate = DateTimeOffset.Now;
                //activeuser.IsOnline = true;
                db.SaveChanges();
                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
コード例 #3
0
        /// <summary>
        /// 发放。授权资源访问凭证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async System.Threading.Tasks.Task GrantResourceOwnerCredentials(Microsoft.Owin.Security.OAuth.OAuthGrantResourceOwnerCredentialsContext context)
        {
            //return base.GrantResourceOwnerCredentials(context);
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            //鉴定ClientID之后。授权来源
            if (allowedOrigin == null)
            {
                allowedOrigin = this.userClientAuth? "*" : this.AnoymouseAllowedOrigins;
            }
            /////ngauthenticationweb Access-Control-Allow-Origin //来源鉴定
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", allowedOrigin.Split(','));
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET", "POST", "PUT", "DELETE" });


            Microsoft.AspNet.Identity.EntityFramework.IdentityUser user =
                await authRepository.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "用户名,密码不正确");
                return;
            }
            //claim based 认证
            var identity = new System.Security.Claims.ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, context.UserName));
            identity.AddClaim(new System.Security.Claims.Claim("sub", context.UserName));
            identity.AddClaim(new System.Security.Claims.Claim("role", "user"));
            //identity.AddClaim(new System.Security.Claims.Claim("test", "test"));
            var claims = MallAuth.ServerCache.GlobalCache.getInstance().getUserClaims(context.UserName);

            foreach (var item in claims)
            {
                identity.AddClaim(new System.Security.Claims.Claim(item.Type, item.Value));
            }
            ///额外的响应参数.注意这个和Claim不同
            var props = new Microsoft.Owin.Security.AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new Microsoft.Owin.Security.AuthenticationTicket(identity, props);

            context.Validated(ticket);

            //context.Validated(identity);
        }