场景:你自己实现了一套webApi,想供自己的客户端调用,又想做认证。

第一步:通过vs2015建立web api项目,Startup.cs,这个类将会作为Owin的启动类。

第二步:在webapi.config中添加如下代码:

第三步:在web.config中添加连接字符串(这里使用了EF Code First)

第四步:添加上下文对象

第五步:添加AuthRepository类,增加用户注册和查找功能:

第六步:增加AccountController(

using Microsoft.AspNet.Identity;
using Owin2.Auth;
using Owin2.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http; namespace Owin2.Controllers
{
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
private readonly AuthRepository _authRepository = null; public AccountController()
{
_authRepository = new AuthRepository();
}
// POST api/Account/Register Register方法打上了AllowAnonymous标签,意味着调用这个api无需任何授权。
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(UserModel userModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} IdentityResult result = await _authRepository.RegisterUser(userModel); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null)
{
return errorResult;
} return Ok();
} protected override void Dispose(bool disposing)
{
if (disposing)
{
_authRepository.Dispose();
} base.Dispose(disposing);
} private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
} if (!result.Succeeded)
{
if (result.Errors != null)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
} if (ModelState.IsValid)
{ // No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
} return BadRequest(ModelState);
} return null;
}
}
}

  

认证策略的类:

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web; namespace Owin2.Auth
{
public class SimpleAuthorizationServerProvider: OAuthAuthorizationServerProvider
{ /// <summary>
/// ValidateClientAuthentication方法用来对third party application 认证,
/// 具体的做法是为third party application颁发appKey和appSecrect,
/// 在本例中我们省略了颁发appKey和appSecrect的环节,
/// 我们认为所有的third party application都是合法的,context.Validated();
/// 表示所有允许此third party application请求。
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult<object>(null);
} /// <summary>
/// GrantResourceOwnerCredentials方法则
/// 是resource owner password credentials模式的重点
/// 由于客户端发送了用户的用户名和密码,
/// 所以我们在这里验证用户名和密码是否正确,
/// 后面的代码采用了ClaimsIdentity认证方式,
/// 其实我们可以把他当作一个NameValueCollection看待。
/// 最后context.Validated(ticket); 表明认证通过
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password); if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
} var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
identity.AddClaim(new Claim("sub", context.UserName)); var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id",context.ClientId ?? string.Empty
},
{
"userName",context.UserName
}
}); var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
} /// <summary>
/// TokenEndpoint方法将会把Context中的属性加入到token中。
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
} return Task.FromResult<object>(null);
} }
}

  

OAuth2服务已经搭建好了,建立客户端来测试。

第七步:建立客户端(新建另外一个api程序),并且配置Startup.cs

第八步:配置web api.config

第九步:建立测试api控制器

1.先注册

2.通过用户名和密码获取token

3.通过token请求api

客户端和服务端通过配置文件关联。

最新文章

  1. 从入门到精通C++需要学的10本书
  2. 2016 年青岛网络赛---Sort(k叉哈夫曼)
  3. python学习笔记2-functools.wraps 装饰器
  4. WSP (无线会话协议)
  5. Ugly Numbers
  6. VC++中,如何定义callback函数和它的触发事件?
  7. intent传递参数
  8. ORACLE字符串分组聚合函数(字符串连接聚合函数)
  9. php 去掉 头尾 空格 2种方法
  10. 【原创】ZOJ_1649 Rescue 解题报告
  11. js 日期大小比较
  12. 论文阅读笔记(二)U-Net
  13. 测试 多线程 实现 callable 带返回值
  14. js读取xml文件
  15. Nginx 配置为https服务器
  16. Android studio2.3.3升级3.1.2坑
  17. springAOP记录用户操作日志
  18. SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍
  19. spring-boot 学习笔记一
  20. android随机运算器开发小结1

热门文章

  1. 【Oracle】删除undo表空间时,表空间被占用:ORA-30042: Cannot offline the undo tablespace
  2. vue 子组件向父组件传值通信
  3. 04-手把手教你把Vim改装成一个IDE编程环境(图文)
  4. N1-1 - 树 - Minimum Depth of Binary Tree
  5. Linux 基础入门一
  6. 01.Python基础-1.Python简介及基础
  7. PHP学习总结(9)——PHP入门篇之WAMPServer服务控制面板介绍
  8. net--技术栈(大图)
  9. 计算机网络系统--常用DOS命令
  10. Servlet过滤器和监听器知识总结