Web API和AngularJS - ajax请求响应,401即使经过身份验证也未授权

时间:2017-01-13 09:20:09

标签: javascript angularjs login asp.net-web-api2 form-authentication

问题:我确实请求web api并验证并设置formauthentication cookie。从角度JS发布,在每个$http请求上,它只会进入401未经授权的访问,因为每个web api控制器都具有[Authorize]属性。

在这里,请帮助我解决此登录/身份验证问题。

以下是所有代码:

web api有以下登录信息:

 public HttpResponseMessage SignIn(UserModel user)
        {
            try
            {
            if (this.ModelState.IsValid)
            {                
                if (user.UserName == "final" && user.Password == "final")
                {
                    var response = this.Request.CreateResponse(HttpStatusCode.Created, "success");
                    FormsAuthentication.SetAuthCookie(user.UserName, false);                    
                    return response;
                }
                return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized,"noaccess");
            }
            return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest,"badrequest");
            }
            catch (Exception)
            {
                return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "internalerror");
            }
        }

angular JS登录服务:

function login() {            
            vm.dataLoading = true;
            authenticationService.Login(vm.username, vm.password).then(function (d, status, xhr) {                
                if (d.data == "success") {
                    authenticationService.SetCredentials(vm.username, vm.password);
                    $location.path('/');
                } else {                                                                
                    //"Invalid credentials. Please try again.";
                }
                vm.dataLoading = false;
            }, function (d) {                
                if (d.data.message != "internalerror") {                    
                    // "Invalid credentials. Please try again.";
                } else {
                    // "An error has occurred while login. Please try again.";
                }
                vm.dataLoading = false;
            });
        }

authenticationService - SetCredentials方法:

function SetCredentials(username, password) {
            var authdata = Base64.encode(username + ':' + password);

            $rootScope.globals = {
                currentUser: {
                    username: username
                   ,authdata: authdata
                }
            };

            // set default auth header for http requests
            $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;

            // store user details in globals cookie that keeps user logged in for 1 week (or until they logout)
            var cookieExp = new Date();
            cookieExp.setDate(cookieExp.getDate() + 7);
            $cookies.putObject('globals', $rootScope.globals, { expires: cookieExp });

        }

登录后,AJAX调用如下:

 this.Retrieve = function (fileName) {
                    return $http({
                        method: "POST",
                        url: config.APIURL + 'space/Retrieve',
                        data: JSON.stringify({ Name: fileName }),
                        headers: { 'Content-Type': 'application/json' }
                    });
                };

登录并发送401访问的数据包信息:

Request URL:http://localhost/pr.WebAPI/api/space
Request Method:GET
Status Code:401 Unauthorized
Remote Address:[::1]:80


Response Headers
view source
Cache-Control:no-cache
Content-Length:68
Content-Type:application/json; charset=utf-8
Date:Fri, 13 Jan 2017 09:43:58 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:.ASPXAUTH=9C338EBAA4F9B02D8D28D6B0BB34B03E4EEBF2BEB29C8BAE79496236FBD3132C3B4F4CCC6F072C5A69C033E6867341B1C1729399B5B4EEDBD79E4160EE857476A342DF166260EF4663033FC2B25C2A47435CCD09966C9EA1EE8BDBD8BAA50E19
Host:localhost
Referer:http://localhost/pr.Web/app/views/Index.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

0 个答案:

没有答案