场景:你自己实现了一套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

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

OAuth2建立webapi认证服务供自己的客户端使用--密码模式的更多相关文章

  1. 使用OAuth打造webapi认证服务供自己的客户端使用

    一.什么是OAuth OAuth是一个关于授权(Authorization)的开放网络标准,目前的版本是2.0版.注意是Authorization(授权),而不是Authentication(认证). ...

  2. 使用OAuth打造webapi认证服务供自己的客户端使用(二)

    在上一篇”使用OAuth打造webapi认证服务供自己的客户端使用“的文章中我们实现了一个采用了OAuth流程3-密码模式(resource owner password credentials)的W ...

  3. OAuth打造webapi认证服务

    使用OAuth打造webapi认证服务供自己的客户端使用 一.什么是OAuth OAuth是一个关于授权(Authorization)的开放网络标准,目前的版本是2.0版.注意是Authorizati ...

  4. Spring Boot Security Oauth2之客户端模式及密码模式实现

    Spring Boot Security Oauth2之客户端模式及密码模式实现 示例主要内容 1.多认证模式(密码模式.客户端模式) 2.token存到redis支持 3.资源保护 4.密码模式用户 ...

  5. SpringBootSecurity学习(17)前后端分离版之 OAuth2.0 数据库(JDBC)存储客户端

    自动批准授权码 前面我们授权的流程中,第一步获取授权码的时候,都会经历一个授权是否同意页面: 这个流程就像第三方登录成功后,提问是否允许获取昵称和头像信息的页面一样,这个过程其实是可以自动同意的,需要 ...

  6. Core篇——初探IdentityServer4(客户端模式,密码模式)

    Core篇——初探IdentityServer4(客户端模式,密码模式) 目录 1.Oatuth2协议的客户端模式介绍2.IdentityServer4客户端模式实现3.Oatuth2协议的密码模式介 ...

  7. postgres(pgAdmin) 客户端保存密码

    pgAdmin 大象客户端保存密码后连接服务器,删除掉当前连接,建立一个新的连接不用输入密码也能连接上,其实是客户端保存了密码,让人误以为是空密码可登录.可以通过右键连接,选择重载服务配置,再次连接就 ...

  8. 在线建立或重做mysql主从复制架构方法(传统模式和GTID模式)【转】

    mysql主从复制架构,是mysql数据库主要特色之一,绝大多数公司都有用到. 而GTID模式是基于事务的复制模式的意思,发展到现在也是越来越多人用. 以前很多文章,介绍搭建mysql主从复制架构,是 ...

  9. Security-OAuth2.0 密码模式之客户端实现

    我的OAuth2.0 客户端项目目录 pom 的配置 <?xml version="1.0" encoding="UTF-8"?> <proj ...

随机推荐

  1. 关于CommandTimeOut

    指示在终止尝试和产生错误之前执行命令期间需等待的时间. 设置和返回值 设置或返回长整型值,该值指示等待命令执行的时间(单位为秒).默认值为 30. 说明 Connection 对象或Command 上 ...

  2. Vtk读取并显示保存图像

    (1):Vtk读取并显示图像:三种方法 转载:未知出处 转载:用VTK显示平面图片:http://blog.csdn.net/tonylk/article/details/464881 用到vtkJP ...

  3. QT线程使用收集示例

    关于多线程问题: Qt和Boost做跨平台的线程封装,OpenMP主要做并行计算,让不精通多线程的人也能高效地利用CPU的计算能力.个人倾向于用boost.thread, boost.mpi.   一 ...

  4. 一系列令人敬畏的.NET核心库,工具,框架和软件

    内容 一般 框架,库和工具 API 应用框架 应用模板 身份验证和授权 Blockchain 博特 构建自动化 捆绑和缩小 高速缓存 CMS 代码分析和指标 压缩 编译器,管道工和语言 加密 数据库 ...

  5. 10件5G能实现,但4G不能做的事情

    10件5G能实现,但4G不能做的事情 从三星Galaxy S10 5G手机到OnePlus 7 Pro 5G手机以及更高版本,首批5G手机现已上市.5G网络时代的开启是从小范围内,如果你居住在可以使用 ...

  6. Aeroplane chess HDU - 4405_数学期望_逆推

    Code: #include<cstdio> #include<algorithm> #include<cstring> using namespace std; ...

  7. navicat Premium远程链接mysql报错

    1,报错1057,原来是没有远程权限连接mysql 2.打开my.ini文件,添加skip-grant-tables跳过验证 3.添加到path环境变量,前面是英文下的分号 4.切换到cmd,输入my ...

  8. jmeter图片的上传

    首先添加一个线程组,然后在线程组里面添加一个http请求,因为是发送数据,所有是post请求,写好上传的地址,然后写好文件路径 1.添加线程组 :右键测试计划,添加-Threads(Users)-线程 ...

  9. SLAB

    slab:由于内核会有许多小对象,这些对象构造销毁十分频繁,比如i-node,dentry,这些对象如果每次构建的时候就向内存要一个页(4kb),而其实只有几个字节,这样就会非常浪费,为了解决这个问题 ...

  10. spring boot --部署war到tomcat中

    1.在pom文件中,将默认的jar包打包,改成以war包打包:<!--打包方式--><packaging>war</packaging> 2.将项目在doc命令中执 ...