2

I am using ASP.NET MVC and AngularJs. I need to authenticate.

I authenticate using the default code of the MVC Project in VS2015. Here the View:

<div class="credential_box">
    @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form" }))
    {
        @Html.LabelFor(m => m.Username) 
        @Html.TextBoxFor(m => m.Username, new { @class = "credential" })

        @Html.LabelFor(m => m.Password) 
        @Html.PasswordFor(m => m.Password, new { @class = "credential" })

        <input type="submit" value="ACCEDI" style="cursor:pointer" />
    }
</div>

And here the controller:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: true);

    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);
        case ...
    }
}

Asp.Net identity is configured as follow:

public void ConfigureAuth(IAppBuilder app)
{
    ...
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    });            
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}

The login works, because if I pass from a page to another one that require authentication and i am not logged in, I need to login.

Now, there are some parts of the project that use AngularJs. So I have to pass the authentication cookie to the requests I do with AngularJs. Is it possible?

I am using AngularJs Resource to do the requests. So, I have some services:

intranet
    .factory("countriesService", function ($resource, ENDPOINT) {
        return {
            countries: $resource(ENDPOINT + "api/Countries", null, {
                'update' : { method: 'PUT' }
            })
        };
    });

And a controller like this:

intranet.controller("countriesController", function ($scope, countriesService, dialogsService) {
    $scope.countries = [];
    $scope.country = {};
    $scope.oldCountryInUpdate = {};

    /****************** GET COUNTRIES ******************/
    $scope.getCountries = function () {
        new countriesService
                .countries
                .query({ }, getCountriesSuccess, getCountriesError);
    };

    var getCountriesSuccess = function (data) {
        $scope.countries = data;
        $scope.country.id = $scope.countries[0].id; //Seleziona il primo elemento della lista
    };

    var getCountriesError = function (response) { };
}

It's about 3 days I am trying but I cannot solve this problem alone. Can anyone help me please?

Thank you

Simone
  • 2,304
  • 6
  • 30
  • 79
  • `if I pass from a page to another one that require authentication, I need to login.` Both ***MVC*** and ***Web API*** go through same OWIN cookie middle-ware. When you login in ***MVC*** controller, you do not need to login for ***Web API*** controller as long as they are in same domain. – Win Nov 03 '16 at 16:31
  • I have corrected the post. I was not so clear. However I do not have any problem server Side. The problem is when I pass on client. When I make a request via AngularJs i lose the cookie! How do I add the authentication cookie in the AngularJs request? – Simone Nov 03 '16 at 17:00
  • Cookies should not lost if both ***MVC*** and ***Web API*** are in same domain. Are they in two different domains? – Win Nov 04 '16 at 15:40
  • MVC and WebApi yes... But I think angularJs with WebApi not... – Simone Nov 04 '16 at 17:13

0 Answers0