Implementing Authentication and role based authorization in ASP.NET MVC web API service and MVC client architecture

孤街浪徒 提交于 2019-12-04 04:56:05
Jos Vinke

First of all I think it's never a good idea to invent your own authentication mechanism.

To answer your current problems:

1 Generally spoken you always want to secure your Api using authentication since it's the place where you access your data. Your client (MVC App/Smartphone) should authorize itself to get access to your Api.

2 & 3 Since you are using a REST Api I would suggest to keep your Api stateless, with other words, don't keep any session information. Just include the role data you need in your Token. You could use for example an JSON Web Token.

4 I would always use the authorization header to send authorization data. In your DelegatingHandler (Note the difference MessageHandler MVC, DelegatingHander HTTP) you can simpy retrieve the header.

protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
 {
    var authorizationHeader = request.Headers.Authorization;
    // Your authorization logic.

    return base.SendAsync(request, cancellationToken);
 }

For more info on how to include the authorization header in an ajax call please see: How to use Basic Auth with jQuery and AJAX?

Extra info:

If I were you I would also take a look at Thinktecture's Identity Server: https://github.com/thinktecture/Thinktecture.IdentityServer.v2

And maybe this answer about REST Service Authentication will help you as well: REST service authentication

Why create an entire token system (unless you're using some kind of federated security) you have forms authentication and cookies, once the cookie is set and returned the browser will send the cookie with any AJAX requests made by your SPA.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!