- ASP.NET Web API Security Essentials
- Rajesh Gunasundaram
- 242字
- 2021-07-30 10:15:53
Implementing authentication in HTTP message handlers
For a self-hosted web API, the best practice is to implement authentication in an HTTP Message Handler. The principal will be set by the message handler after verifying the HTTP request. For a web API that is self-hosted, consider implementing authentication in a message handler. Otherwise, use an HTTP module instead.
The following code snippet shows an example of basic authentication implemented in an HTTP module:
public class AuthenticationHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var credentials = ParseAuthorizationHeader(request); if (credentials != null) { // Check if the username and passowrd in credentials are valid against the ASP.NET membership. // If valid, the set the current principal in the request context var identity = new GenericIdentity(credentials.Username); Thread.CurrentPrincipal = new GenericPrincipal(identity, null);; } return base.SendAsync(request, cancellationToken) .ContinueWith(task => { var response = task.Result; if (credentials == null && response.StatusCode == HttpStatusCode.Unauthorized) Challenge(request, response); return response; }); } protected virtual Credentials ParseAuthorizationHeader(HttpRequestMessage request) { string authorizationHeader = null; var authorization = request.Headers.Authorization; if (authorization != null && authorization.Scheme == "Basic") authorizationHeader = authorization.Parameter; if (string.IsNullOrEmpty(authorizationHeader)) return null; authorizationHeader = Encoding.Default.GetString(Convert.FromBase64String(authorizationHeader)); var authenticationTokens = authorizationHeader.Split(':'); if (authenticationTokens.Length < 2) return null; return new Credentials() { Username = authenticationTokens[0], Password = authenticationTokens[1], }; } void Challenge(HttpRequestMessage request, HttpResponseMessage response) { response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", request.RequestUri.DnsSafeHost)); } public class Credentials { public string Username { get; set; } public string Password { get; set; } } }
推薦閱讀
- Visual FoxPro程序設(shè)計(jì)教程
- Web Application Development with R Using Shiny(Second Edition)
- PLC編程及應(yīng)用實(shí)戰(zhàn)
- Python數(shù)據(jù)可視化之Matplotlib與Pyecharts實(shí)戰(zhàn)
- Python語(yǔ)言實(shí)用教程
- 時(shí)空數(shù)據(jù)建模及其應(yīng)用
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)教程(Windows 7+Office 2010)
- Elasticsearch Essentials
- SQL Server 2016 從入門到實(shí)戰(zhàn)(視頻教學(xué)版)
- Java語(yǔ)言程序設(shè)計(jì)實(shí)用教程(第2版)
- Python繪圖指南:分形與數(shù)據(jù)可視化(全彩)
- Mastering Vim
- Learning SaltStack(Second Edition)
- 給產(chǎn)品經(jīng)理講技術(shù)
- Go Programming Cookbook(Second Edition)