A simple ASP .NET MVC API controller using roles

老子叫甜甜 提交于 2021-02-07 11:13:59

问题


I wrote a web application using ASP .NET MVC and authorization system by default. I configured IdentityRole and input through external providers. Using the current database I have created my data context. Now I want to write a Xamarin.Android app and connect to my database, I want a simple API. But the feature that you want to access this API was only available to user with a certain role. The API is really very simple and therefore do not want to add to the draft WCF or WebAPI project. How to do it best?


回答1:


First, you don't need a separate project to use Web Api; you can use both MVC and Web Api in the same project. For one off endpoints for things like in-site AJAX requests, just creating MVC actions that return JSON or XML would be fine, but if you're talking about a true API, even if it's fairly simplistic, I'd say go Web Api.

You'd protect your Web Api actions much the same as you would your MVC actions, using the [Authorize] attribute. If you need to restrict by role, you just pass a role(s) to that. However, the big difference here, especially if you're serving a mobile app, is that you'll need pass the authorization along with the request. That's generally accomplished using the Authorization header along with a bearer token. Basically, you would need to set up an endpoint that signs a user in and returns a token. Then, each subsequent request that needs authorization includes that token in the header.




回答2:


I want to finish and to fully answer this question and close this topic. I've been searching for how to add the ability for a mobile client to connect to an existing site on ASP.NET MVC. In my search, I came across a great article Justin Hyland on March 2, 2014 In principle, everything in this article is well and clearly written, but I want to make a tiny contribution for clarity. Under Setup WebAPIConfig stated that the need

added in the following code to the WebApiConfig Register method

But if we consider the case ASP.NET MVC we don't have such file. It's all very simple, you just need such a file to create the folder App_Start. The contents of the file can be left exactly as it is in the article.

To get rid of the bugs which will inevitably appear we need to install two nuget package: Microsoft.AspNet.WebApi and Microsoft.AspNet.WebApi.Owin.

Excellent! Now we can turn to the method to obtain the token and then adding the token to the query we can get the needed data closed by the attribute [Authorize].

A small remark. If You need to access a method which is closed for a specific role that to the Authenticate method from the article should add a few lines of code. Immediately after the line:

identity.AddClaim(new Claim(ClaimTypes.Name, user));

add the line:

identity.AddClaim(new Claim(ClaimTypes.Role, role));

where role you can get the following, for example:

var userIdentity = UserManager.FindAsync(user, password).Result;
var role = RoleManager.FindById(userIdentity.Roles.First().RoleId).Name;

User and password you have to send a request.

I also want to give an example of code which will send request and receive response. To not have to look for and immediately start coding.

        async Task<string> GetToken(string userName, string password)
        {
        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>( "user", userName ),
            new KeyValuePair<string, string> ( "password", password )
        }
        );

        using (var client = new HttpClient())
        {
            HttpResponseMessage response = await client.PostAsync(APP_PATH + "/Authenticate", content);
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }

    async Task<string> GetUserInfo(string token)
    {
        using (var client = CreateClient(token))
        {
            var response = await client.GetAsync(APP_PATH + "/ValidateToken");
            return await response.Content.ReadAsStringAsync();
        }
    }

    HttpClient CreateClient(string accessToken = "")
    {
        var client = new HttpClient();
        if (!string.IsNullOrWhiteSpace(accessToken))
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        }
        return client;
    }

All have only to call the appropriate methods in the correct order. I hope that is useful to someone. P.S. If You create a new project in Visual Studio to get this functionality you just need to tick:



来源:https://stackoverflow.com/questions/42436764/a-simple-asp-net-mvc-api-controller-using-roles

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