Search code examples
asp.net-mvcasp.net-web-apiasp.net-identity

A simple ASP .NET MVC API controller using roles


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?


Solution

  • 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: enter image description here