Web API: Security: Basic Authentication
原文地址: http://msdn.microsoft.com/en-us/magazine/dn201748.aspx
Custom HttpModule code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web; namespace Test.MVC
{
public class CustomAuthModel: IHttpModule, IDisposable
{
public void Init(HttpApplication context)
{
context.AuthenticateRequest += AuthenticateRequests;
context.EndRequest += TriggerCredentials; } private void TriggerCredentials(object sender, EventArgs e)
{
HttpResponse resp = HttpContext.Current.Response;
if (resp.StatusCode == )
{
resp.Headers.Add("WWW-Authenticate", @"Basic realm='PHVIS'");
}
} private void AuthenticateRequests(object sender, EventArgs e)
{
string authHeader = HttpContext.Current.Request.Headers["Authorization"];
if(authHeader!=null)
{
AuthenticationHeaderValue authHeaderValue = AuthenticationHeaderValue.Parse(authHeader);
if(authHeaderValue.Parameter!=null)
{
byte[] unencode = Convert.FromBase64String(authHeaderValue.Parameter);
string usePw = Encoding.GetEncoding("iso-8859-1").GetString(unencode);
string[] creds = usePw.Split(':'); if (creds[] == "Name" && creds[] == "pw")
{
GenericIdentity gi = new GenericIdentity(creds[]);
string [] roles= new string[]{"Admin","Manager"};
Thread.CurrentPrincipal = new GenericPrincipal(gi, roles);
HttpContext.Current.User = Thread.CurrentPrincipal;
} }
}
} public void Dispose()
{ } } }
CustomAuthModel.cs
Web Config
<modules>
<add name="CustomAuthModel"
type="Test.MVC.CustomAuthModel, Test.MVC"/>
</modules>
Web API code:
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Test.EntityFramework.Models; namespace Test.MVC.Controllers
{
public class TestController : ApiController
{
private TestDBContext db = new TestDBContext(); // GET api/Test
[Authorize]
public IQueryable<Test.EntityFramework.Models.Test> GetTests()
{
if (User.Identity.IsAuthenticated == true)
{ }
return db.Tests;
}
}
}
TestController.cs
Client code:
public static async Task TestSecurity()
{
using (HttpClientHandler clientHandler = new HttpClientHandler())
{
clientHandler.Credentials = new NetworkCredential("Name", "pw");
using (HttpClient client = new HttpClient(clientHandler))
{
client.BaseAddress = new Uri("http://localhost:55165/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync("api/test"); // Blocking call // Get
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
var products = await response.Content.ReadAsAsync<IEnumerable<Test.EntityFramework.Models.Test>>();
foreach (var p in products)
{
Console.WriteLine("{0}\t{1};", p.ID, p.Title);
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
}
}
Program.cs
Web API: Security: Basic Authentication的更多相关文章
- Secure Spring REST API using Basic Authentication
What is Basic Authentication? Traditional authentication approaches like login pages or session iden ...
- Asp.net Web Api 2 FORM Authentication Demo
最近看了一点 web api 2方面的书,对认证都是简单介绍了下,所以我在这里做个简单Demo,本文主要是FORM Authentication,顺带把基本认证也讲了. Demo 一.FORM Aut ...
- 【Web API2】ASP.NET Web API Security
实现安全的方式既可以是host提供,也可以框架提供. 1,HTTP Module 方式,工作在IIS上,所以web api要托管在IIS上才行.其作用于HTTP管道的最前端,所以这种方式影响的是全局, ...
- Web API: Security: Authentication and Authority
原文地址: http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-ap ...
- Authentication and Authorization in ASP.NET Web API
You've created a web API, but now you want to control access to it. In this series of articles, we ...
- Web services 安全 - HTTP Basic Authentication
根据 RFC2617 的规定,HTTP 有两种标准的认证方式,即,BASIC 和 DIGEST.HTTP Basic Authentication 是指客户端必须使用用户名和密码在一个指定的域 (Re ...
- 在ASP.NET Web API 2中使用Owin基于Token令牌的身份验证
基于令牌的身份验证 基于令牌的身份验证主要区别于以前常用的常用的基于cookie的身份验证,基于cookie的身份验证在B/S架构中使用比较多,但是在Web Api中因其特殊性,基于cookie的身份 ...
- 一个HTTP Basic Authentication引发的异常
这几天在做一个功能,其实很简单.就是调用几个外部的API,返回数据后进行组装然后成为新的接口.其中一个API是一个很奇葩的API,虽然是基于HTTP的,但既没有基于SOAP规范,也不是Restful风 ...
- Web API 简单示例
一.RESTful和Web API Representational State Transfer (REST) is a software architecture style consisting ...
随机推荐
- 3ds Max学习日记(十)——显示场景资源管理器
之前把max的对象窗口(场景资源管理器)给弄没了,搞了半天都不知道怎么调回来,百度搜索到的结果也不知道都是些啥玩意.不过好在最后还是弄出来了! 一开始是下面这样的,没有场景资源管理器用起来很不 ...
- debug阶段贡献分
组名: 新蜂 组长: 武志远 组员: 宫成荣 谢孝淼 杨柳 李峤 项目名称: java俄罗斯方块NEO 发布时间:11.29 武志远 武志远 武志远 武志远 武志远 宫成荣 宫成荣 杨柳 宫成荣 宫成 ...
- wpf后台设置颜色(背景色,前景色)
有时候你是不是也会遇到要在wpf后台给某个控件设置背景色或者给文字设置前景色的情况? 本人最近看到一个从自定义的combobox读取系统字体和颜色的实例,该实例实现了随字体combobox选项改变而改 ...
- Robot Framework 教程 (5) - 连接Oracel数据库
Robot Framework 提供了多种Library.其中Database Library可用来连接操作数据库. 1.安装Database Library 打开Robot Framework官网, ...
- [转帖]SQLSERVER的兼容级别
SQL Server数据库的兼容级别 http://www.cnblogs.com/sosoft/archive/2017/07/08/sqljrjb.html 改天尝试一下 在SQLSERVER20 ...
- [知乎]SSD的延迟
以及一些SSD的性能数据
- [转帖]真TM长的:SQL Server 2008存储结构——GAM和SGAM、PFS结构、IAM结构、DCM&BCM
谈到GAM和SGAM,我们不得不从数据库的页和区说起. https://blog.csdn.net/snowfoxmonitor/article/details/49991015 一个数据库由用户定义 ...
- [转帖]windows 2008 Server R2 /Win7启用TLS 1.2
来自新浪博客的 一个文章 自己很早之前曾经看过 iis的加密工具 但是当时没有认识到TLS1.2协议的问题 这里 晚上学习了一下. http://blog.sina.com.cn/s/blog_16 ...
- C++中sizeof操作符与strlen函数
sizeof操作符: sizeof是一个操作符,返回一条表达式或一个类型名字所占的字节数.返回值一个常量表达式,类型为size_t. size_t sizeof(type) size_t sizeof ...
- sklearn-特征工程之特征选择
title: sklearn-特征工程之特征选择 date: 2016-11-25 22:49:24 categories: skearn tags: sklearn --- 抄袭/参考资料 使用sk ...