【7】.net WebAPI Owin OAuth 2.0 密码模式验证实例
1.OAuth密码模式

2.在VS中创建WebAPI项目
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
这两个类库并添加Owin启动类Startup
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.OAuth; [assembly: OwinStartup(typeof(WebAPIOAuth.Startup))] namespace WebAPIOAuth
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var OAuthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"), //获取 access_token 授权服务请求地址
AuthorizeEndpointPath = new PathString("/authorize"), //获取 authorization_code 授权服务请求地址
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(), //access_token 过期时间 Provider = new OpenAuthorizationServerProvider(), //access_token 相关授权服务
}; app.UseOAuthBearerTokens(OAuthOptions); //表示 token_type 使用 bearer 方式 不记名令牌验证
}
}
}
ConfigureOAuth(IAppBuilder app)方法开启了OAuth服务。简单说一下OAuthAuthorizationServerOptions中各参数的含义:
AllowInsecureHttp:允许客户端一http协议请求;
TokenEndpointPath:token请求的地址,即http://localhost:端口号/token;
AccessTokenExpireTimeSpan :token过期时间;
Provider :提供具体的认证策略;
3.继承授权服务OAuthAuthorizationServerProvider类
重载ValidateClientAuthentication方法验证客户端的正确性
重载GrantResourceOwnerCredentials方法实现用户名密码的验证,验证通过后会颁发token。
public class OpenAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
/// <summary>
/// 验证调用端的clientid与clientSecret已验证调用端的合法性(clientid、clientSecret为约定好的字符串)。
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
context.TryGetBasicCredentials(out clientId, out clientSecret);
if (clientId == "" && clientSecret == "")
{
context.Validated(clientId);
}
await base.ValidateClientAuthentication(context);
} /// <summary>
/// 通过重载GrantResourceOwnerCredentials获取用户名和密码进行认证
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//调用后台的登录服务验证用户名与密码
if (context.UserName != "Admin" || context.Password != "")
{
context.SetError("invalid_grant", "用户名或密码不正确。");
return;
} var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
context.Validated(ticket); await base.GrantResourceOwnerCredentials(context);
}
}
在需要验证的方法处添加[Authorize]标签,当访问此接口时必须通过授权验证才可访问。
以上服务器端代码全部完成。
4.创建新的客户端项目进行测试
添加测试类
class OAuthClientTest
{
private HttpClient _httpClient;
private string token; public OAuthClientTest()
{
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri("http://localhost");
} public async Task<string> GetAccessToken()
{
var clientId = "";
var clientSecret = ""; var parameters = new Dictionary<string, string>();
parameters.Add("grant_type", "password");
parameters.Add("username", "Admin");
parameters.Add("password", ""); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret))
); var response = await _httpClient.PostAsync("OAuthTest/token", new FormUrlEncodedContent(parameters));
var responseValue = await response.Content.ReadAsStringAsync();
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return JObject.Parse(responseValue)["access_token"].Value<string>();
}
else
{
Console.WriteLine(responseValue);
return string.Empty;
}
} public async Task Call_WebAPI_By_Resource_Owner_Password_Credentials_Grant()
{
if(string.IsNullOrEmpty(token))
token = await GetAccessToken();
Console.WriteLine(token);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Console.WriteLine(await (await _httpClient.GetAsync("OAuthTest/api/Values")).Content.ReadAsStringAsync());
}
}
main方法中调用进行测试:
static void Main(string[] args)
{
var clientTest = new OAuthClientTest();
var task = clientTest.Call_WebAPI_By_Resource_Owner_Password_Credentials_Grant();
task.Wait();
//var token = clientTest.GetAccessToken();
//var strToken = token.Result;
//Console.WriteLine(strToken);
Console.ReadLine();
}
结果如下:
其中长串字符为token,"value1, value2"为访问webapi返回的结果,表明访问成功。
参考1:http://www.cnblogs.com/xishuai/p/aspnet-webapi-owin-oauth2.html
参考2:http://www.cnblogs.com/Leo_wl/p/4919783.html
【7】.net WebAPI Owin OAuth 2.0 密码模式验证实例的更多相关文章
- webapi之owin的oauth2.0密码模式_01概述
一般在webapi接口中,为了防止接口被随意调用,都会验证用户身份. 然而不能每次调用接口都需要用户输入用户名密码来验证,这时就需要授权颁发令牌了,持有令牌就可以访问接口,接口也能验证令牌身份. 简单 ...
- oauth2.0密码模式详解
oauth2.0密码模式 欢迎关注博主公众号「Java大师」, 专注于分享Java领域干货文章http://www.javaman.cn/sb2/oauth-password 如果你高度信任某个应用, ...
- .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书
原文:.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书 一.客户端模式介绍 客户端模式(Client Credentials Grant)是指客户 ...
- 基于OWIN WebAPI 使用OAuth授权服务【客户端验证授权(Resource Owner Password Credentials Grant)】
适用范围 前面介绍了Client Credentials Grant ,只适合客户端的模式来使用,不涉及用户相关.而Resource Owner Password Credentials Grant模 ...
- Security-OAuth2.0 密码模式之客户端实现
我的OAuth2.0 客户端项目目录 pom 的配置 <?xml version="1.0" encoding="UTF-8"?> <proj ...
- IdentityServer4:IdentityServer4+API+Client+User实践OAuth2.0密码模式(2)
一.密码模式实操 仍然使用第一节的代码:做如下改动: 1.授权服务端 前面我们使用项目:Practice.IdentityServer作为授权服务器 修改项目的Config.cs类: 添加测试用户,并 ...
- WebApi Owin OAuth
Microsoft.Owin.Host.SystemWeb Owin Microsoft.Owin Microsoft.Owin.Diagnostics Owin Micros ...
- OWIN OAuth 2.0 Authorization Server
http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server The assumption ...
- Security-OAuth2.0 密码模式之服务端实现
第一步:配置数据库 ,固定创建三张表 ,OAuth2 框架需要默认使用这三张表 我使用的时Mysql,工具为navcat CREATE TABLE `oauth_access_token` ( `to ...
随机推荐
- Ubuntu add-apt-repository: command not found
在Ubuntu下,时不时会有这个错误的. add-apt-repository: command not found 这个是缺少程序,安装一下就可以了.只是不知道安装的名字. 按以下命令走一趟就可以的 ...
- ELK学习链接
1. ELK原理与介绍 2. ELK部署记录
- java中集合
一. List集合: 一次只存储一个元素 1.常用的list集合是ArrayList (1)在创建这个集合的对象时, 需要指定这个集合存储的数据类型! 否则这个集合的数据是不安全的. (2)与数组的 ...
- php-fpm 和 nginx 的两种通信方式
在 linux 中,nginx 服务器和 php-fpm 可以通过 tcp socket 和 unix socket 两种方式实现. 一下内容转自:https://blog.csdn.net/qq62 ...
- 由一个场景分析Mysql的join原理
背景 这几天同事写报表,sql语句如下 select * from `sail_marketing`.`mk_coupon_log` a left join `cp0`.`coupon` c on c ...
- java编码规范_缩进和注释
1. 缩进排版(Indentation) 4个空格常被作为缩进排版的一个单位.缩进的确切解释并未详细指定(空格 vs. 制表符).一个制表符等于n个空格(视具体的编辑器而定,Eclipse ...
- 浅析Postgres中的并发控制(Concurrency Control)与事务特性(下)
上文我们讨论了PostgreSQL的MVCC相关的基础知识以及实现机制.关于PostgreSQL中的MVCC,我们只讲了元组可见性的问题,还剩下两个问题没讲.一个是"Lost Update& ...
- POJ 2209
#include<iostream> #include<stdio.h> #include<algorithm> #include<math.h> #d ...
- maven web不能创建src/main/java等文件等问题
我们在创建maven web项目的时候,默认只有src/main/resources这个source folder,我们按照maven结构添加src/main/java和src/test/java等s ...
- [原创]php任务调度器 hellogerard/jobby
目录 简介 安装 标准使用 选项 项目实践 简介 一个强大的php层面上的定时任务调度器, 无需修改系统层面的crontab 实际中, php 结合 crontab 来实现定时任务是一种经得住考验的实 ...