原文地址: 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. UDP与TCP笔记

    1.UDP UDP协议在工作时是建立在IP协议之上的,UDP从进程的缓冲区接收进程每一次产生的输出,对每次输出都生成一个UDP数据报,然后把生成的UDP数据报直接封装在IP数据报中进行传输,因此在传输 ...

  2. 学习jenv

    背景 生活不只是眼前的苟且, 还有诗和远方. 上个月工作需要启动了一个小项目, 按最初的计划会用JDK8. 但当计划报上去后, 运维部门出于后续升级维护的考虑, 不允许使用已经出来4年多的JDK8了, ...

  3. RecyclerView 上拉加载下拉刷新

    RecyclerView 上拉加载下拉刷新 <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/teach_s ...

  4. Alpha阶段敏捷冲刺①Scrum 冲刺博客

    第 1 篇 Scrum 冲刺博客对整个冲刺阶段起到领航作用,应该主要包含三个部分的内容: 各个成员在 Alpha 阶段认领的任务 成员 任务 张晨晨 完成界面设计(前端) 黄登峰 完成界面设计(前端) ...

  5. Linux限制cpu睿频&限制频率

    .关闭睿频 > /sys/devices/system/cpu/intel_pstate/no_turbo .限制CPU最大频率到50% " | sudo tee /sys/devic ...

  6. Linux 下安装mysql 8.0.11(CentOS 7.4 系统)

    CentOS 7 自带MariaDB (前mysql开发工程师开发的,因此与吗,mysql 有很多相似之处) 1.检查卸载自带的MariaDB rpm -qa|grep mariadb //查询出来已 ...

  7. pycharm安装jpype报错及解决方法

    安装jpype时发生报错: 按照提示去装了Microsoft visual C++,结果重新安装还是报错,根据https://blog.csdn.net/qq_38934189/article/det ...

  8. .net对Redis集群的调用(FrameWork版本4.0)

    使用 StackExchange.Redis 实现.net对Redis集群的调用,方法如下: 1.打开 项目-管理NuGet程序包 2.在打开界面搜索StackExchange.Redis,找到Sta ...

  9. DBGridEH序号的自动生成

    序号的自动生成1.定义变量  private         maxno:integer;  public        bmodified:boolean;2.写函数  function max(c ...

  10. js复制内容到剪切板

    注意第一部分的内容不兼容Safari,全兼容的请使用第二部分方法 第一部分 查看demo请点  这里. 原生js复制指定内容到剪切板,超简单的实现方式, 实现思路如下: 1.创建一个input,把想要 ...