栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Web API中基于令牌的身份验证,没有任何用户界面

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Web API中基于令牌的身份验证,没有任何用户界面

我认为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 FormUrlEnpredContent(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; }}

现在在服务器端:

在Startup.Auth.cs中

        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更安全。我希望这有帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/433051.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号