原文地址: 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的更多相关文章

  1. Secure Spring REST API using Basic Authentication

    What is Basic Authentication? Traditional authentication approaches like login pages or session iden ...

  2. Asp.net Web Api 2 FORM Authentication Demo

    最近看了一点 web api 2方面的书,对认证都是简单介绍了下,所以我在这里做个简单Demo,本文主要是FORM Authentication,顺带把基本认证也讲了. Demo 一.FORM Aut ...

  3. 【Web API2】ASP.NET Web API Security

    实现安全的方式既可以是host提供,也可以框架提供. 1,HTTP Module 方式,工作在IIS上,所以web api要托管在IIS上才行.其作用于HTTP管道的最前端,所以这种方式影响的是全局, ...

  4. Web API: Security: Authentication and Authority

    原文地址: http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-ap ...

  5. 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 ...

  6. Web services 安全 - HTTP Basic Authentication

    根据 RFC2617 的规定,HTTP 有两种标准的认证方式,即,BASIC 和 DIGEST.HTTP Basic Authentication 是指客户端必须使用用户名和密码在一个指定的域 (Re ...

  7. 在ASP.NET Web API 2中使用Owin基于Token令牌的身份验证

    基于令牌的身份验证 基于令牌的身份验证主要区别于以前常用的常用的基于cookie的身份验证,基于cookie的身份验证在B/S架构中使用比较多,但是在Web Api中因其特殊性,基于cookie的身份 ...

  8. 一个HTTP Basic Authentication引发的异常

    这几天在做一个功能,其实很简单.就是调用几个外部的API,返回数据后进行组装然后成为新的接口.其中一个API是一个很奇葩的API,虽然是基于HTTP的,但既没有基于SOAP规范,也不是Restful风 ...

  9. Web API 简单示例

    一.RESTful和Web API Representational State Transfer (REST) is a software architecture style consisting ...

随机推荐

  1. beta冲刺7/7

    队名:Boy Next Door 燃尽图 代码写入 https://github.com/mangoqiqi/paybook/tree/master/Desktop/Web%E8%B4%A6%E5%8 ...

  2. Keil C51与Keil ARM共存

    转自:http://blog.chinaunix.net/uid-20734916-id-3988537.html Keil和MDK共存,按照以下步骤:1 先安装 Keil C51,安装目录改为:&q ...

  3. 网页访问过程(基于CDN)

    1. 全局负载均衡(基于DNS) 如果有多台 WEB 服务器同时为一个域名提供服务时,即一条 URL 对应多个 IP 地址,那么该 URL 的权威域名服务器可能会根据该 URL 解析出多个 IP 地址 ...

  4. pygame学习笔记(1)——安装及矩形、圆型画图

    pygame是一个设计用来开发游戏的python模块,其实说白了和time.os.sys都是一样的东东.今天开始正式学习pygame,下载地址:www.pygame.org.下载后安装完成即可,在py ...

  5. Java中线程安全的集合

    如果多线程并发的访问与一个数据结构,那么很容易破坏一个数据结构. 例如,一个线程可能要向一个散列表中插入一条数据的过程中,被剥夺了控制权.如果另外一个线程也开始遍历同一个链表,很可能造成混乱,抛出异常 ...

  6. bzoj2302-Problem c

    题意 有 \(n\) 个人,从 1 到 \(i\) 编号.给每个人一个值 \(a_i\) ,他们会按编号从小到大进行如下操作:查看 \(a_i\) 有没有人,若没有就坐进去,否则查看 \(a_i+1\ ...

  7. springboot整合spring @Cache和Redis

    转载请注明出处:https://www.cnblogs.com/wenjunwei/p/10779450.html spring基于注解的缓存 对于缓存声明,spring的缓存提供了一组java注解: ...

  8. BZOJ2525 [Poi2011]Dynamite 【二分 + 贪心】

    题目链接 BZOJ2525 题解 就是要求所有有炸弹的点到点燃点距离最大值最小 显然二分答案距离\(D\) 然后按深度排序,贪心点燃当前没覆盖的深度最深的点往上第\(D\)层的点 每覆盖一个点要标记其 ...

  9. Nginx web服务优化 (一)

    1.Nginx基本安全优化 a.更改配置文件参数隐藏版本 编辑nginx.conf配置文件增加参数,实现隐藏Nginx版本号的方式如下.在nginx配置文件nginx.conf中的http标签段内加入 ...

  10. nginx 配置 phpmyadmin

    server { listen 8092; server_name *.xxx.com; root /home/users/cuijian04/odp302/app/phpmyadmin; set $ ...