public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authorizationHeader = actionContext.Request.Headers.Authorization;

            if (authorizationHeader == null)
            {
                actionContext.Response =
                    actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                var token = authorizationHeader.Parameter;
                //User:Passward need to be in base64 encoded
                //Need to give Authorization Basic MzEwMTkzMTQzOlRlc3QxMjM= while making request in header
                var tokenValues =
                    Encoding.UTF8.GetString(Convert.FromBase64String(token)).Split(':');
                var userName = tokenValues[0];
                var password = tokenValues[1];

                if (_securityProvider.Login(userName, password))
                {
                    System.Threading.Thread.CurrentPrincipal =
                        new GenericPrincipal(new GenericIdentity(userName), null);
                    //Now this identity can be used to access logged-in current username
                }
                else
                {
                    actionContext.Response =
                        actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
        }
コード例 #2
0
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                try {
                    // Cookie is not persisted, user has to login every time. Add checkbox for persistent cookie?
                    if (!_securityProvider.Login(model.UserName, model.Password))
                    {
                        ModelState.AddModelError("", "Incorrect username or password.");
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                catch (Exception e) {
                    log.Error(string.Format("User login failed - {0}", e.Message, e));
                    ModelState.AddModelError("", "Something went wrong while trying to log you in.");
                }
            }

            return(View());
        }