.net Web API中基于令牌的身份验证,无需任何用户界面

9q78igpj  于 2022-12-27  发布在  .NET
关注(0)|答案(2)|浏览(137)

我正在ASP.NET Web API中开发一个REST API。我的API只能通过非基于浏览器的客户端访问。我需要为我的API实现安全性,所以我决定使用基于令牌的身份验证。我对基于令牌的身份验证有相当的了解,并阅读了一些教程,但他们都有一些用户界面的登录。我不需要任何用户界面的登录,因为登录的详细信息将通过HTTP POST的客户端将从我们的数据库授权。如何在我的API中实现基于令牌的身份验证?请注意-我的API将被频繁访问,因此我也必须注意性能。如果我能更好地解释,请告诉我。

vh0rcniy

vh0rcniy1#

我认为对于MVC和Web API之间的区别存在一些混淆。简而言之,对于MVC,您可以使用登录表单并使用cookie创建会话。对于Web Api,则没有会话。这就是您希望使用令牌的原因。
你不需要一个登录表单。令牌端点就是你所需要的。就像Win描述的那样,你将把凭证发送到令牌端点,在那里处理凭证。
下面是一些用于获取令牌的客户端C#代码:

//using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //string token = GetToken("https://localhost:<port>/", userName, password);

    static string GetToken(string url, string userName, string password) {
        var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
        var content = new FormUrlEncodedContent(pairs);
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            var response = client.PostAsync(url + "Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

要使用令牌,请将其添加到请求的标头中:

//using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //var result = CallApi("https://localhost:<port>/something", token);

    static string CallApi(string url, string token) {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            if (!string.IsNullOrWhiteSpace(token)) {
                var t = JsonConvert.DeserializeObject<Token>(token);

                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
            }
            var response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

其中令牌为:

//using Newtonsoft.Json;

class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

现在来看服务器端:
在启动验证中

var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // https
            AllowInsecureHttp = false
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);

在ApplicationOAuthProvider.cs中,实际赠款或拒绝访问的代码:

//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public ApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await userManager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
        var properties = new AuthenticationProperties(propertyDictionary);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        // Token is validated.
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
            context.Validated();

        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == _publicClientId)
        {
            var expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                context.Validated();
        }
        return Task.FromResult<object>(null);
    }

}

正如你所看到的,在获取令牌的过程中没有涉及到控制器。事实上,如果你只想要一个Web API,你可以删除所有的MVC引用。我已经简化了服务器端代码,使其更具可读性。你可以添加代码来升级安全性。
确保只使用SSL。实现RequireHttpsAttribute以强制执行此操作。
您可以使用Authorize / AllowAnonymous属性来保护Web API。此外,您还可以添加过滤器(如RequireHttpsAttribute)来提高Web API的安全性。

jecbmhm3

jecbmhm32#

ASP.NET Web API已经内置了授权服务器。* 使用Web API模板创建新的ASP.NET Web应用程序时,可以在Startup.cs中看到它。*

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

所有你要做的就是张贴URL编码的用户名和密码内查询字符串。

/Token/userName=johndoe%40example.com&password=1234&grant_type=password

相关问题