1 year ago

#71438

test-img

Ganesh Devlekar

Authenticate mvc controller then redirect from angular to mvc path

We are using ASP.NET MVC with razor but some of pages are in angular 12. cause we are migrating gradually from ASP.NET MVC to Angular 12.

In this we have authenticated user from an ASP.NET MVC controller by post request with token, returning true when authenticated else false.

In ASP.NET MVC I am using Forms authentication.

I have this code in my controller:

public ActionResult AuthenticateUser(LoginModel loginmodel)
{
    // some code to validate user
    // loginmodel.token -> valid token 
    // loginmodel.examid -> valid exam id
    //FormsAuthentication.SetAuthCookie(userLogin.UserName, false);
    FormsAuthentication.RedirectFromLoginPage(userLogin.UserName, false);
    // BY using this line we are directing user to dashboard once authenticated

    return Json(true);            // user is authenticated
else  
    return Json(false);
}

In Angular after serving request (following code is request by Angular to above C# code)

 this.myService.AuthenticateUser(this.examid,token).pipe(first()).subscribe(data => {
   data = JSON.parse(JSON.stringify(data));

   if (data == true) 
   {
       window.location.href = "https://localhost/dashboard"
   }
   else
       window.location.href = "https://localhost/login"
})

It is not redirecting to dashboard instead of it is showing following error

Error shown in console from angular

For me it looks like angular is trying to parse response instead of redirecting by window.location.href . is there am i missing some thing in this ?

Update:

if i remove this line from controller FormsAuthentication.RedirectFromLoginPage(userLogin.UserName, false); then angular is redirecting to dashboard but it refuses connection / authentication even if i added this FormsAuthentication.SetAuthCookie.

image for illustration

angular

asp.net-mvc

angular-routing

0 Answers

Your Answer

Accepted video resources