1.OAuth密码模式

2.在VS中创建WebAPI项目

在nuget中安装:

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 密码模式验证实例的更多相关文章

  1. webapi之owin的oauth2.0密码模式_01概述

    一般在webapi接口中,为了防止接口被随意调用,都会验证用户身份. 然而不能每次调用接口都需要用户输入用户名密码来验证,这时就需要授权颁发令牌了,持有令牌就可以访问接口,接口也能验证令牌身份. 简单 ...

  2. oauth2.0密码模式详解

    oauth2.0密码模式 欢迎关注博主公众号「Java大师」, 专注于分享Java领域干货文章http://www.javaman.cn/sb2/oauth-password 如果你高度信任某个应用, ...

  3. .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

    原文:.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书 一.客户端模式介绍 客户端模式(Client Credentials Grant)是指客户 ...

  4. 基于OWIN WebAPI 使用OAuth授权服务【客户端验证授权(Resource Owner Password Credentials Grant)】

    适用范围 前面介绍了Client Credentials Grant ,只适合客户端的模式来使用,不涉及用户相关.而Resource Owner Password Credentials Grant模 ...

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

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

  6. IdentityServer4:IdentityServer4+API+Client+User实践OAuth2.0密码模式(2)

    一.密码模式实操 仍然使用第一节的代码:做如下改动: 1.授权服务端 前面我们使用项目:Practice.IdentityServer作为授权服务器 修改项目的Config.cs类: 添加测试用户,并 ...

  7. WebApi Owin OAuth

    Microsoft.Owin.Host.SystemWeb    Owin    Microsoft.Owin Microsoft.Owin.Diagnostics    Owin    Micros ...

  8. OWIN OAuth 2.0 Authorization Server

    http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server The assumption ...

  9. Security-OAuth2.0 密码模式之服务端实现

    第一步:配置数据库 ,固定创建三张表 ,OAuth2 框架需要默认使用这三张表 我使用的时Mysql,工具为navcat CREATE TABLE `oauth_access_token` ( `to ...

随机推荐

  1. iOS Keychain 跨应用

    Keychain 可以用来持久保存一些信息.通常每个应用都有自己的 Keychain Access.但有时你会需要多个应用共用一些信息.这时需要创建 Keychain Access Group. Ke ...

  2. Cookie背景了解

    Cookie的复数形态是Cookies, 英文的意思是小甜饼,小饼干. 类型为小型文本文件, 指某些网站为了辨别用户身份储存在用户本地中断上的数据. 是前网景公司的员工 卢-蒙特利在1993年3月发明 ...

  3. PHP set_error_handler()函数的使用

    我们写程序,难免会有问题(是经常会遇到问题 ),而PHP遇到错误时,就会给出出错脚本的位置.行数和原因.有很多人说,这并没有什么大不了.确实,在调试程序阶段,这确实是没啥的,而且我认为给出错误路径是必 ...

  4. InnoDB: The innodb_system data file 'ibdata1' must be writable错误

    重新安装percona5.7过程中,启动mysql服务总是报如下的错误 --10T02::.781070Z [ERROR] InnoDB: The innodb_system data file 'i ...

  5. spring利用注解方式实现Java读取properties属性值

    1. 建立properties文件:我在resource下面建立一个config文件夹,config文件夹里面有mytest.properties文件,文件内容如下: sam.username=sam ...

  6. elasticsearch5.2.1使用logstash同步mysql

    centos 本人亲测可以  首先安装好mysql,elasticsearch   不懂的请参考另一篇文章 安装logstash官方:https://www.elastic.co/guide/en/l ...

  7. Unable to access 'default.path.data' (/var/lib/elasticsearch)

  8. string常用字符串操作函数

    1.strdup和strndup 说明:strdup() 函数将参数 s 指向的字符串复制到一个字符串指针上去,这个字符串指针事先可以没被初始化.在复制时,strdup() 会给这个指针分配空间,使用 ...

  9. 网络基础 04_IP编址

    1 IP地址简介 什么是IP地址 在IP网络中,任何一个节点都需要一个唯一的IP IPV4 :32位 点分十进制 2 IP编址分类 有类编址 IP地址的类别 IP地址类型 网络地址:指代网络的地址.在 ...

  10. 何为Web App,何为Hybird App

    这些概念听起来很火,当下也很流行,真正理解起来却并非易事.如果让我来全面的解释Web App和Hybird App,我觉得还有些困难. 这篇文章只是我深入了解移动领域开发过程中的不断整理和总结,其中涉 ...