OAuth2建立webapi认证服务供自己的客户端使用--密码模式
场景:你自己实现了一套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认证服务供自己的客户端使用--密码模式的更多相关文章
- 使用OAuth打造webapi认证服务供自己的客户端使用
一.什么是OAuth OAuth是一个关于授权(Authorization)的开放网络标准,目前的版本是2.0版.注意是Authorization(授权),而不是Authentication(认证). ...
- 使用OAuth打造webapi认证服务供自己的客户端使用(二)
在上一篇”使用OAuth打造webapi认证服务供自己的客户端使用“的文章中我们实现了一个采用了OAuth流程3-密码模式(resource owner password credentials)的W ...
- OAuth打造webapi认证服务
使用OAuth打造webapi认证服务供自己的客户端使用 一.什么是OAuth OAuth是一个关于授权(Authorization)的开放网络标准,目前的版本是2.0版.注意是Authorizati ...
- Spring Boot Security Oauth2之客户端模式及密码模式实现
Spring Boot Security Oauth2之客户端模式及密码模式实现 示例主要内容 1.多认证模式(密码模式.客户端模式) 2.token存到redis支持 3.资源保护 4.密码模式用户 ...
- SpringBootSecurity学习(17)前后端分离版之 OAuth2.0 数据库(JDBC)存储客户端
自动批准授权码 前面我们授权的流程中,第一步获取授权码的时候,都会经历一个授权是否同意页面: 这个流程就像第三方登录成功后,提问是否允许获取昵称和头像信息的页面一样,这个过程其实是可以自动同意的,需要 ...
- Core篇——初探IdentityServer4(客户端模式,密码模式)
Core篇——初探IdentityServer4(客户端模式,密码模式) 目录 1.Oatuth2协议的客户端模式介绍2.IdentityServer4客户端模式实现3.Oatuth2协议的密码模式介 ...
- postgres(pgAdmin) 客户端保存密码
pgAdmin 大象客户端保存密码后连接服务器,删除掉当前连接,建立一个新的连接不用输入密码也能连接上,其实是客户端保存了密码,让人误以为是空密码可登录.可以通过右键连接,选择重载服务配置,再次连接就 ...
- 在线建立或重做mysql主从复制架构方法(传统模式和GTID模式)【转】
mysql主从复制架构,是mysql数据库主要特色之一,绝大多数公司都有用到. 而GTID模式是基于事务的复制模式的意思,发展到现在也是越来越多人用. 以前很多文章,介绍搭建mysql主从复制架构,是 ...
- Security-OAuth2.0 密码模式之客户端实现
我的OAuth2.0 客户端项目目录 pom 的配置 <?xml version="1.0" encoding="UTF-8"?> <proj ...
随机推荐
- Qt5.2 for Android 配置及部署到手机运行
使用DNK编程也没有那么难,使用QT为安卓跨平台编程需要安装NDK,SDK通过NDK调用C++程序,偶尔能提高一些效率. SDK下载地址:http://developer.android.com/sd ...
- 微信App支付:微信支付的appid,appsecret,商户号mch_id,微信交易支付密钥(mch_key)在哪里查看
1-1) 查看微信支付 appid 的方法 微信支付使用的 appid, 是微信服务号的 appid, 需要你登录微信服务号后台, 在 开发-基本配置/开发者ID(AppID) 中查看微信支付 app ...
- ubuntu18.0安装redis
ubuntu版本:Ubuntu-Server 10.04.1 LTS redis版本:4.0.9 安装 使用apt安装 sudo apt-get update sudo apt-get install ...
- 解决AttributeError: 'module' object has no attribute 'main' 安装第三方包报错
1.找到pycharm 目录下的 \helper\packaging_tool.py 文件 2.用新版pycharm 的packaging_tool.py 替换 旧版 同名文件 文件代码如下: imp ...
- Javascript继承(原始写法,非es6 class)
知识点: Object.create的内部原理: Object.create = function (o) { var F = function () {}; F.prototype ...
- js生产随机数
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; var string_le ...
- CSS 居中【整合】
<center> text-align:center 在父容器里水平居中 inline 文字,或 inline 元素 vertical-align:middle 垂直居中 inline 文 ...
- python开发项目:学生选课系统
程序要求:1.创建北京.上海两所学校(分析:通过学校类实例化两个学校实例) 2.创建Linux.python.go三个课程,Linux\go在北京开,Linux在上海开(创建Linux.python. ...
- 如何在 VMware 上安装 CentOS 6.8
一.下载 CentOS 6.8 64位 链接:https://pan.baidu.com/s/15qmWGar2m0WzsWxDk4tSSg 密码:wqra 二.安装步骤 1.新建虚拟机 2.自定义 ...
- FreeMarker 页面静态化解决方案
一.网页的静态化方案 1.生成静态页面的时机:在做添加操作时,同时生成该新增内容的对应的静态页面 2.静态页面的名称:内容 id + ".html" 3.静态页面所在的路径:工程外 ...
