Beispiel #1
0
        public async System.Threading.Tasks.Task <ActionResult> Register(string username, string email, string password)
        {
            var userStore = new Microsoft.AspNet.Identity.EntityFramework.UserStore <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>();
            var manager   = new Microsoft.AspNet.Identity.UserManager <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(userStore);
            var user      = new Microsoft.AspNet.Identity.EntityFramework.IdentityUser()
            {
                UserName = username, Email = email, EmailConfirmed = false
            };

            manager.UserTokenProvider =
                new Microsoft.AspNet.Identity.EmailTokenProvider <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>();

            Microsoft.AspNet.Identity.IdentityResult result = await manager.CreateAsync(user, password);

            if (result.Succeeded)
            {
                //I have some options: log them in, or I can send them an email to "Confirm" their account details.'
                //I don't have email set up this week, so we'll come back to that.
                string confirmationToken = await manager.GenerateEmailConfirmationTokenAsync(user.Id);

                string confirmationLink = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/Confirm/" + user.Id + "?token=" + confirmationToken;

                string apiKey = System.Configuration.ConfigurationManager.AppSettings["SendGrid.ApiKey"];

                SendGrid.ISendGridClient           client = new SendGrid.SendGridClient(apiKey);
                SendGrid.Helpers.Mail.EmailAddress from   = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Coding Cookware Administrator");

                SendGrid.Helpers.Mail.EmailAddress to = new SendGrid.Helpers.Mail.EmailAddress(email);

                string subject = "Confirm your Coding Cookware Account";

                string htmlContent      = string.Format("<a href=\"{0}\">Confirm Your Account</a>", confirmationLink);
                string plainTextContent = confirmationLink;

                SendGrid.Helpers.Mail.SendGridMessage message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

                SendGrid.Response response = await client.SendEmailAsync(message);

                TempData["EmailAddress"] = email;

                return(RedirectToAction("ConfirmationSent"));


                //Commenting this out: I'm not going to log the user in on registration anymore - I'm going to send them a confirmation email instead.
                //This authentication manager will create a cookie for the current user, and that cookie will be exchanged on each request until the user logs out
                //var authenticationManager = HttpContext.GetOwinContext().Authentication;
                //var userIdentity = await manager.CreateIdentityAsync(user, Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
                //authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { }, userIdentity);
            }
            else
            {
                ViewBag.Error = result.Errors;
                return(View());
            }

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #2
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);
        }
Beispiel #3
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuthRepository _repo = new AuthRepository())
            {
                Microsoft.AspNet.Identity.EntityFramework.IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

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

            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);
        }
Beispiel #4
0
 public Microsoft.AspNet.Identity.EntityFramework.IdentityUser AuthUser()
 {
     Microsoft.AspNet.Identity.EntityFramework.IdentityUser user = UserManager.FindByEmail(this.User.Identity.Name);
     return(user);
 }
        public void Test_Contruction()
        {
            var user = new Microsoft.AspNet.Identity.EntityFramework.IdentityUser("aaa");

            Assert.AreEqual(user.UserName, "aaa");
        }
Beispiel #6
0
        public static ApiAuth.Result IsApiAuth(Controllers.GenericAuthController c, string[] validRoles, IEnumerable <ApiCall.CallParameter> parameters = null, [CallerMemberName] string method = "")
        {
            var usrmgr = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();

            string login = null;

            if (c.User?.Identity?.IsAuthenticated == true)
            {
                Microsoft.AspNet.Identity.EntityFramework.IdentityUser user = usrmgr.FindByEmail(c.User.Identity.Name);

                if (validRoles == null)
                {
                    return(ApiAuth.Result.Valid(new ApiCall()
                    {
                        IP = c.Request.UserHostAddress, UserId = user?.Id, User = c.User.Identity.Name, Id = method, Method = method, Parameters = parameters
                    }));
                }
                else if (validRoles.Count() == 0)
                {
                    return(ApiAuth.Result.Valid(new ApiCall()
                    {
                        IP = c.Request.UserHostAddress, UserId = user?.Id, User = c.User.Identity.Name, Id = method, Method = method, Parameters = parameters
                    }));
                }
                else
                {
                    foreach (var role in validRoles)
                    {
                        if (c.User.IsInRole(role.Trim()))
                        {
                            return(ApiAuth.Result.Valid(new ApiCall()
                            {
                                IP = c.Request.UserHostAddress, UserId = user?.Id, User = c.User.Identity.Name, Id = method, Method = method, Parameters = parameters
                            }));
                        }
                    }
                    return(ApiAuth.Result.Invalid(new ApiCall()
                    {
                        IP = c.Request.UserHostAddress, UserId = user?.Id, User = c.User.Identity.Name, Id = method, Method = method, Parameters = parameters
                    }));
                }
            }
            else if (IsApiAuthHeader(c.HttpContext.Request, out login))
            {
                Microsoft.AspNet.Identity.EntityFramework.IdentityUser user = usrmgr.FindByEmail(login);
                if (user == null)
                {
                    return(ApiAuth.Result.Invalid(new ApiCall()
                    {
                        IP = c.Request.UserHostAddress, UserId = null, User = null, Id = method, Method = method, Parameters = parameters
                    }));
                }
                else
                {
                    if (validRoles == null)
                    {
                        return(ApiAuth.Result.Valid(new ApiCall()
                        {
                            IP = c.Request.UserHostAddress, UserId = user.Id, User = user.Email, Id = method, Method = method, Parameters = parameters
                        }));
                    }
                    else if (validRoles.Count() == 0)
                    {
                        return(ApiAuth.Result.Valid(new ApiCall()
                        {
                            IP = c.Request.UserHostAddress, UserId = user.Id, User = user.Email, Id = method, Method = method, Parameters = parameters
                        }));
                    }
                    else
                    {
                        foreach (var role in validRoles)
                        {
                            if (usrmgr.IsInRole(user.Id, role.Trim()))
                            {
                                return(ApiAuth.Result.Valid(new ApiCall()
                                {
                                    IP = c.Request.UserHostAddress, UserId = user.Id, User = user.Email, Id = method, Method = method, Parameters = parameters
                                }));
                            }
                        }
                        return(ApiAuth.Result.Invalid(new ApiCall()
                        {
                            IP = c.Request.UserHostAddress, UserId = user.Id, User = user.Email, Id = method, Method = method, Parameters = parameters
                        }));
                    }
                }
            }
            else
            {
                return(ApiAuth.Result.Invalid(new ApiCall()
                {
                    IP = c.Request.UserHostAddress, UserId = null, User = null, Id = method, Method = method, Parameters = parameters
                }));
            }
        }
 public void Test_Contruction()
 {
     var user = new Microsoft.AspNet.Identity.EntityFramework.IdentityUser("aaa");
     Assert.AreEqual(user.UserName, "aaa");
 }