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 ...
随机推荐
- 项目冲刺Beta第二篇博客
Beta版本冲刺计划安排 1.当天站立式会议照片: 2.工作分工: 团队成员 分工 张洪滨060 排行榜界面美化 陈敬轩059 注册成功界面美化 黄兴067 登录界面美化 林国梽068 答题界 ...
- TCP系列53—拥塞控制—16、Destination Metrics和Congestion Manager
一.概述 我们之前介绍过rtt.ssthresh等变量,这些变量一般在TCP连接建立的时候有个初始值,然后随着TCP的数据交互逐渐调整到适应对应的网络状态的值.但是如果每次TCP建立连接都依靠默认初始 ...
- java 数据结构与算法---栈
原理来自百度百科 一.栈的定义 栈是一种只能在一端进行插入和删除操作的特殊线性表:它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数 ...
- 记录下log4j的两种配置方式
XML文件配置 <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE log4j:configura ...
- 【刷题】BZOJ 3295 [Cqoi2011]动态逆序对
Description 对于序列A,它的逆序对数定义为满足i<j,且Ai>Aj的数对(i,j)的个数.给1到n的一个排列,按照某种顺序依次删除m个元素,你的任务是在每次删除一个元素之前统计 ...
- BZOJ 2668: [cqoi2012]交换棋子
2668: [cqoi2012]交换棋子 Time Limit: 3 Sec Memory Limit: 128 MBSubmit: 1112 Solved: 409[Submit][Status ...
- HTML的标签元素分类的区别
HTML ,即Hyper Text Markup Language 超文本标记语言: 文本:纯字符,如window中的txt文本 超文本:在纯文本中嵌入样式,图片,音频,视频,链接等内容 HTML的基 ...
- linux内核分析 第八周 理解进程调度时机跟踪分析进程调度与进程切换的过程
笔记: 实验:使用gdb跟踪分析一个schedule()函数
- ORB算法介绍(转)
本文为原创文章,转载请注明出处:http://blog.csdn.net/yang843061497/article/details/38553765 绪论 假如我有2张美女图片,我想确认这2张图片中 ...
- cuckoo 安装
最新 https://www.jianshu.com/p/f623fa0bebf9 http://www.freebuf.com/articles/system/123816.html http:// ...