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 ...
随机推荐
- thinkphp 学习1-模型
1.用M()方法创建模型类 $model = M("configsettings"); 2.使用find()方法或select()方法返回结果集 find()只返回一行记录,sel ...
- Selenium WebDriver 中鼠标和键盘事件分析及扩展(转)
文章转自:http://www.ibm.com/developerworks/cn/java/j-lo-keyboard/
- Oracle中SYS_CONNECT_BY_PATH函数的妙用 ;
Oracle 中SYS_CONNECT_BY_PATH函数是非常重要的函数,下面就为您介绍一个使用SYS_CONNECT_BY_PATH函数的例子,实例如下: 数据准备: ),b )); ', 'A' ...
- XHTML和HTML、CSS 验证器
XHTML 验证器和 CSS 验证器.需要这些工具去验证你的页面是否符合 XHTML 和 CSS 标准,并且可以使用它查出奇正错误的地方. XHTML 验证器 地址:http://validator. ...
- Best Time to Buy and Sell Stock IV
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- C# 实例化类的执行顺序
先进行细分: 类的成员分为:字段.属性.方法.构造方法 成员的修饰符:静态成员.实例成员 层次结构:父类.子类 先不考虑继承关系,执行顺序为: 静态字段 静态构造方法 实例字段 实例构造方法 属性和方 ...
- P3919 【模板】可持久化数组(可持久化线段树/平衡树)
题目描述 如题,你需要维护这样的一个长度为 N 的数组,支持如下几种操作 在某个历史版本上修改某一个位置上的值 访问某个历史版本上的某一位置的值 此外,每进行一次操作(对于操作2,即为生成一个完全一 ...
- Vivian's Problem UVA - 1323(梅林素数+状压二进制)
借鉴:https://blog.csdn.net/miku23736748/article/details/52135932 https://blog.csdn.net/acm_cxlove/arti ...
- c++11 函数模板的默认模板参数
c++11 函数模板的默认模板参数 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> ...
- 单点登录(十七)----cas4.2.x登录mongodb验证方式成功后返回更多信息更多属性到客户端
我们在之前已经完成了cas4.2.x登录使用mongodb验证方式登录成功了.也解决了登录名中使用中文乱码的问题. 单点登录(十三)-----实战-----cas4.2.X登录启用mongodb验证方 ...