简体   繁体   English

如何通过现有的WebAPI验证我的MVC5应用程序?

[英]How can I authenticate my MVC5 application through an existing WebAPI?

I am creating an ASP.NET MVC 5 application. 我正在创建一个ASP.NET MVC 5应用程序。 I have no access to a database . 无权访问数据库 Everything I do goes through a WebApi . 我所做的一切都通过WebApi进行

I want to authenticate users through this API and at the same time get an access token. 我想通过此API对用户进行身份验证,同时获得访问令牌。

How can I do this without throwing away all of the account maintenance code that Visual Studio places in my MVC 5 application? 在不丢弃Visual Studio放在我的MVC 5应用程序中的所有帐户维护代码的情况下,如何做到这一点?

I thought that this would be in the framework somewhere, but everything I find on the internet seems like a hack. 我以为这应该在框架中的某个地方,但是我在互联网上找到的所有内容似乎都是黑客。 I refuse to hack anything dealing with security. 我拒绝破解任何涉及安全性的内容。 How can I do this? 我怎样才能做到这一点?

I'm working with a virgin ASP.NET MVC 5 application. 我正在使用原始的ASP.NET MVC 5应用程序。 There is no custom code here. 这里没有自定义代码。

Clarification: 澄清:

How can I add a hook into the log-in logic to get the token from the WebApi whenever the user signs in? 每当用户登录时,如何在登录逻辑中添加钩子以从WebApi获取令牌?

Possible Solution: 可能的解决方案:

I have done the following: 我已经完成以下工作:

public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    // Constructor and other code have been hidden to simplify this sample.

    public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
    {
        var status = await base.PasswordSignInAsync(userName, password, isPersistent, shouldLockout);

        if (status == SignInStatus.Success)
        {
            var baseAddress = new Uri(ConfigurationManager.AppSettings["WebApiAddress"]);

            var client = new HttpClient { BaseAddress = baseAddress };
            var response = await client.PostAsync("Token", new StringContent(String.Format("grant_type=password&username={0}&password={1}", userName, password), Encoding.UTF8));

            response.EnsureSuccessStatusCode();

            var tokenResponse = await response.Content.ReadAsStringAsync();
            var json = JObject.Parse(tokenResponse);

            var token = json["access_token"].ToString();
            token.ToString();

            HttpContext.Current.Session["AccessToken"] = token;
        }

        return status;
    }
}

I am going to refactor this code so that this becomes a method call. 我将重构此代码,以使其成为方法调用。

If this is a bad idea, please let me know. 如果这是个坏主意,请告诉我。 If there is a better location for this, let me know that as well. 如果有更好的位置,也请告诉我。 I don't like this. 我不喜欢这样 It feels like a hack, but I don't know what else to do. 感觉就像是骇客,但我不知道该怎么办。

In the default template, you authenticate by calling /token with username, password, and grant_type, something like this: 在默认模板中,您可以通过使用用户名,密码和grant_type调用/ token进行身份验证,如下所示:

POST /token HTTP/1.1
Host: yoursite.com
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

grant_type=password&username=something@something.com&password=mypass

This should return a token that you can set as a header in your consecutive requests to authenticate your users, something like: 这应该返回一个令牌,您可以将其设置为连续请求中用于验证用户身份的标头,例如:

GET /api/sms HTTP/1.1
Host: yoursite.com
Authorization: Bearer hegRkzAdXHE-JzAccW-ANpJEyyMU0gBS80ZMxMa1mtpbqGNNtvifMsHVM1O7AinNhIkQuyHbz3wrRcUA0veAC32N8_Oig5f58S6mXiNUbA4y7qLbr4HPyXBQLNq3F29LsnDWJ-cPCivWB13cPeS2en6q39E_ix2CErDDLh-X5i-vmOrK5XgqK1PUlIkyRoA6fvwKKQ3HVrQvNV3D0WSBlIt7i8ykMTnIofAj1_4hpmrQdlLaxq3zfUG9JQbeedUSP5WcjTs1dwdUcJrZWUDrGLHp8bgQ4Av_zx27opx25yyWLOdVsceeth2ytZ0G5vo_m_PCApN9TJGtU70eaYdLa0ZLLIXpG1pDilpGgTeT-bp1qhA8LqKxtXkH54X_o8GlOstoT6NjeyEBG80ZjmHZS_dMn_Uve-qKDGdKPM4JuvBRU2Cqt2M5FiUdGsDjdkOxFVb4xwfAaz0QbwmOAz7xIywIszfEw3blg4eQLefPBAM
Cache-Control: no-cache

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM