使用角色的简单ASP .NET MVC API控制器 [英] A simple ASP .NET MVC API controller using roles

查看:37
本文介绍了使用角色的简单ASP .NET MVC API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我默认情况下使用ASP .NET MVC和授权系统编写了一个Web应用程序.我配置了IdentityRole并通过外部提供程序输入.使用当前数据库,我创建了我的数据上下文.现在,我想编写一个Xamarin.Android应用程序并连接到我的数据库,我想要一个简单的API.但是,您想要访问此API的功能仅对具有特定角色的用户可用.该API确实非常简单,因此不想添加到WCF或WebAPI项目草稿中.如何做到最好?

解决方案

我要完成并完全回答此问题并结束本主题.我一直在寻找如何增加移动客户端连接到ASP.NET MVC上现有站点的功能.在搜索中,我遇到了一篇很棒的文章

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?

解决方案

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:

这篇关于使用角色的简单ASP .NET MVC API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆