Recommended authentication UX in AngularJS SPA with own and external (Google, FB…) profiles

后端 未结 3 1361
失恋的感觉
失恋的感觉 2021-01-31 00:22

I\'m developing an Asp.net MVC + Web API + AngularJS SPA. I would like to have several types of registration/authentication:

  • own profile provider
  • external
3条回答
  •  别那么骄傲
    2021-01-31 01:20

    I can only comment on my own experience, maybe it is helpful. We use the same stack as you, Asp.net MVC + Web API + AngularJS. We use server-side MVC for authentication (Microsoft.AspNet.Identity), since we are not exposing a public API at this stage and the only consumer of the API will be our SPA this works perfectly with the least amount of effort.

    This also enables us to set a UserContext Angular service on the server once logged in that can be shared through your entire Angular app, the Google Doubleclick Manager guys goes into some of the benefits of this approach during there ng-conf presentation. Since Web Api supports Asp.Net Identity, authentication and authorization works seamlessly between MVC and Web Api.

    To sum up the major pros and cons:

    Pros:

    1. Very easy and quick to implement.
    2. Works across MVC and Web Api.
    3. Clientside code does not need to be concerned with authentication code.
    4. Set UserContext Angular service on server side once during login, easily shared throughout SPA using Angular DI. See presentation as mentioned above.
    5. Integrates with external providers as easily as you would with any normal MVC app.

    Cons:

    1. Since the browser does not send the hash # part of the URL to the server, return URL on login will always be the root of your SPA. E.g. suppose your SPA root is /app, and you try to access /app#/client when you aren't authenticated, you will be redirected to the login page, but the return URL will be /app and not /app#/client as the server has no way to know the hash part of the URL as the browser never sends this.
    2. Not really supported design if you plan to make your your Web Api available outside your SPA. Imagine a console app trying to connect to your API?

    So in short, the MVC view that we use to bootstrap our SPA is protected with [Authorize] as well as our Web Api methods. Inside the MVC view we also initialize our UserContext Angular service using Razor to inject whatever user properties we want to expose. Once the SPA is loaded via the single Razor view, everything else is handled via Angular.

提交回复
热议问题