客户端模式定义

客户端使用自己的名义,而不是用户的名义,向“服务提供商” 进行认证。

如何理解这句话? 乍一看,定义有点拗口,刚接触的童鞋可能完全不知所云。

没关系,我们先把他的工作流程图画出来,如下:

据上图,可以得出一个大概的结论

1、用户(User)通过客户端(Client)访问受限资源(Resource)

2、因为资源受限,所以需要授权;而这个授权是Client与Authentication之间完成的,可以说跟User没有什么关系

3、根据2得出,Resource与User没有关联关系,即User不是这个Resource的Owner(所有者)

既然是这样,那大概可以推出这种认证的适用范围。

第一,肯定不能用作登录认证!因为登录认证后需要得到用户的一些基本信息,如昵称,头像之类,这些信息是属于User的;

第二,适用于一些对于权限要求不强的资源认证,比如:仅用于区分用户是否登录,排除匿名用户获取资源

新建一个资源项目:ResourceServer

引用owin:install-package Microsoft.Owin -Version 2.1.0

新增Startup.cs

[assembly: OwinStartup(typeof(ResourceServer.Startup))]
namespace ResourceServer
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}

新增Startup.Auth.cs

namespace ResourceServer
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
       // 这句是资源服务器认证token的关键,认证逻辑在里边封装好了,我们看不到
app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions());
}
}
}

新增ValuesController.cs

namespace ResourceServer.Controllers
{
[Authorize]
public class ValuesController : ApiController
{
public string Get()
{
return "lanxiaoke";
}
}
}

新建认证服务项目

修改Startup.Auth.cs

public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
// Setup Authorization Server
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/OAuth/Token"),
ApplicationCanDisplayErrors = true,
#if DEBUG
AllowInsecureHttp = true,
#endif
// Authorization server provider which controls the lifecycle of Authorization Server
Provider = new OAuthAuthorizationServerProvider
{
OnValidateClientAuthentication = ValidateClientAuthentication,
OnGrantClientCredentials = GrantClientCredetails
}, // Authorization code provider which creates and receives authorization code
AuthorizationCodeProvider = new AuthenticationTokenProvider
{
OnCreate = CreateAuthenticationCode,
OnReceive = ReceiveAuthenticationCode,
}, // Refresh token provider which creates and receives referesh token
RefreshTokenProvider = new AuthenticationTokenProvider
{
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
}
});
} private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret))
{
if (clientId == "123456" && clientSecret == "abcdef")
{
context.Validated();
}
}
return Task.FromResult(0);
} private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
{
var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
context.Validated(identity);
return Task.FromResult(0);
} private readonly ConcurrentDictionary<string, string> _authenticationCodes =
new ConcurrentDictionary<string, string>(StringComparer.Ordinal); private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
{
context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
_authenticationCodes[context.Token] = context.SerializeTicket();
} private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
{
string value;
if (_authenticationCodes.TryRemove(context.Token, out value))
{
context.DeserializeTicket(value);
}
} private void CreateRefreshToken(AuthenticationTokenCreateContext context)
{
context.SetToken(context.SerializeTicket());
} private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
}
}

自此,认证服务项目算是建好了,因为对于客户端模式,认证服务器只需要返回token

新增Client项目

     static void Main(string[] args)
{
var authorizationServerUri = new Uri("http://localhost:8270/");
var authorizationServerDescription = new AuthorizationServerDescription
{
TokenEndpoint = new Uri(authorizationServerUri, "OAuth/Token")
}; var client = new WebServerClient(authorizationServerDescription, "123456", "abcdef");
var state = client.GetClientAccessToken(new[] { "scopes1", "scopes2" });
var token = state.AccessToken;
Console.WriteLine("Token: {0}", token); var resourceServerUri = new Uri("http://localhost:8001/");
var httpClient = new HttpClient(client.CreateAuthorizingHandler(token));
var values = httpClient.GetStringAsync(new Uri(resourceServerUri, "api/Values")).Result;
Console.WriteLine("Result: {0}", values); Console.ReadKey();
}

OK,Client环境搭好了,我们来运行下试试

认证成功!

  

asp.net权限认证系列

  1. asp.net权限认证:Forms认证
  2. asp.net权限认证:HTTP基本认证(http basic)
  3. asp.net权限认证:Windows认证
  4. asp.net权限认证:摘要认证(digest authentication)
  5. asp.net权限认证:OWIN实现OAuth 2.0 之客户端模式(Client Credential)
  6. asp.net权限认证:OWIN实现OAuth 2.0 之密码模式(Resource Owner Password Credential)
  7. asp.net权限认证:OWIN实现OAuth 2.0 之授权码模式(Authorization Code)
  8. asp.net权限认证:OWIN实现OAuth 2.0 之简化模式(Implicit)

asp.net权限认证:OWIN实现OAuth 2.0 之客户端模式(Client Credential)的更多相关文章

  1. asp.net权限认证:OWIN实现OAuth 2.0 之密码模式(Resource Owner Password Credential)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  2. asp.net权限认证:OWIN实现OAuth 2.0 之简化模式(Implicit)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  3. (转)基于OWIN WebAPI 使用OAuth授权服务【客户端模式(Client Credentials Grant)】

    适应范围 采用Client Credentials方式,即应用公钥.密钥方式获取Access Token,适用于任何类型应用,但通过它所获取的Access Token只能用于访问与用户无关的Open ...

  4. 基于OWIN WebAPI 使用OAuth授权服务【客户端模式(Client Credentials Grant)】

    适应范围 采用Client Credentials方式,即应用公钥.密钥方式获取Access Token,适用于任何类型应用,但通过它所获取的Access Token只能用于访问与用户无关的Open ...

  5. asp.net权限认证:OWIN实现OAuth 2.0 之授权码模式(Authorization Code)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  6. asp.net权限认证:Windows认证

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  7. asp.net权限认证:Forms认证

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  8. asp.net权限认证:HTTP基本认证(http basic)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  9. asp.net权限认证:摘要认证(digest authentication)

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

随机推荐

  1. Keil C动态内存管理机制分析及改进(转)

    源:Keil C动态内存管理机制分析及改进 Keil C是常用的嵌入式系统编程工具,它通过init_mempool.mallloe.free等函数,提供了动态存储管理等功能.本文通过对init_mem ...

  2. 用命令行使用soot反编译生成jimple

    使用工具:soot-2.5.0.jar 注意:soot-2.5.0.jar必须使用Java1.7以及之前的版本,使用Java1.8会发生错误. 修改jdk的方法是在设置java_home的路径的时候, ...

  3. (中等) HDU 3335 , DLX+重复覆盖。

    Description As we know,the fzu AekdyCoin is famous of math,especially in the field of number theory. ...

  4. ARM-LINUX学习笔记-1

    安装完linux之后记得系统更新,更新使用apt命令,如下(记得使用之前使用sudo -i 指令切换到root用户模式) apt-get update  更新系统软件源,相当于查找更新 apt-get ...

  5. 16、手把手教你Extjs5(十六)Grid金额字段单位MVVM方式的选择

    这一节来完成Grid中的金额字段的金额单位的转换.转换旰使用MVVM特性,总体上和控制菜单的几种模式类似.首先在目录app/view/main/menu下建立文件Monetary.js,用于放金额单位 ...

  6. Bash中的变量

    Bash中的变量1.用户定义的变量变量的定义  用户定义的变量有字母数字及下划线组成,并且变量名的第一个字符不能为数字.            与其它UNIX名字一样,变量名是大小写敏感的. 对于变量 ...

  7. 编译时.test文件报错无法解决的方法,关闭test编译

    有几次遇到从网上下载到的iOS开源代码编译报错,报错位置为Test Target的源文件,我就挺奇怪我又没做测试为啥会编译Test Target的源文件,之前的暴力解决方法是把Test Target直 ...

  8. 3)Javascript设计模式:Observer模式

    Observer模式 var Observer = (function() { var instance = null; function Observe() { this.events = {} } ...

  9. Asp.Net集群中Session共享

    今天遇到了这个问题,于是研究了一下.要解决这个问题,首先就要明白一些Session的机理.Session在服务器是以散列表形式存在的,我们都知道Session是会话级的,每个用户访问都会生成一个Ses ...

  10. 【贪心】【堆】Gym -100956D - Greedy Game

    题意:给定n个物品,每个物品对于A和B来说具有不同的价值,记为ai,bi,两人交替取,A先手,A总是贪心地取当前剩下的物品中,对于他价值最高的,如果有多个,则任取一个.问B在最坏情况下,能取到的物品的 ...