OAuth2 的原理这里不多讲,可以看:https://www.cnblogs.com/icebutterfly/p/8066548.html

直奔主题:这里要实现的功能为,统计微软的Owin程序集实现本地获取token,完成token工作。

上代码:

第一步:配置Startup.Auth.cs

    public partial class Startup
{ public void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth2/token"),//设置获取token地址
Provider = new MyOAuthAuthorizationServerProvider(),//自定义token验证
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds()//定义token过期时间
}); //下面必须加用bearer方式
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
});
}
}

第二步:继承OAuthAuthorizationServerProvider接口,重新里面的严重方法。我只实现通过用户名密码获取token,所以只重写两个方法即可

public class MyOAuthAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
{
context.TryGetFormCredentials(out clientId, out clientSecret);
} if (context.ClientId == null)
{
context.SetError("invalid_clientId", "client_Id is not set");
return Task.FromResult<object>(null);
}
if (!string.IsNullOrEmpty(clientSecret))
{
context.OwinContext.Set("clientSecret", clientSecret);
}
var client = ClientRepository.Clients.Where(c => c.Id == clientId).FirstOrDefault();
if (client != null)
{
context.Validated();
}
else
{
context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId));
return Task.FromResult<object>(null);
}
return Task.FromResult<object>(null);
} public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//这里写验证代码
if (context.UserName=="admin"&&context.Password=="")
{
var identity = new ClaimsIdentity(
new GenericIdentity(context.UserName,
OAuthDefaults.AuthenticationType),
context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "The user name or password is incorrect");
return Task.FromResult<object>(null);
}
return Task.FromResult();
}
}

第三步:定义Client实体

    public class Client
{
public string Id { get; set; }
} public class ClientRepository
{
public static List<Client> Clients = new List<Client>() {
new Client{
Id = "test1"
},
new Client{
Id = "test2",
}
};
}

第四步:编写测试方法

    public class HomeController : Controller
{ [Authorize]//授权标签
public ActionResult Test()
{
//获取到授权登陆用户
var authentication = HttpContext.GetOwinContext().Authentication;
string name= authentication.User.Identity.Name; return Json(new { Message="Hello world",name= name });
} }

OK,就这么简单完成。

现在来测试:

第一步:获取token,我用的POSTMan。成功获取到token

第二步:用postman测试也行,这里贴出用ajax请求的结果

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script>
function ajax() {
$.ajax({
url: '/home/test',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
headers: {
'Authorization': 'Bearer ' + $('#token').val(),
},
data: {},
success: function (data) {
console.log(data);
},
})
}
</script>
</head>
<body>
<input type="text" id="token" />
<input type="button" value="提交" onclick="ajax()" />
</body>
</html>

测试结果为:

{
"Message": "Hello world",
"name": "admin"
}

OAuth2 .net MVC实现获取token的更多相关文章

  1. Spring Security 实战干货:OAuth2登录获取Token的核心逻辑

    1. 前言 在上一篇Spring Security 实战干货:OAuth2授权回调的核心认证流程中,我们讲了当第三方同意授权后会调用redirectUri发送回执给我们的服务器.我们的服务器拿到一个中 ...

  2. spring oauth2获取token时WARN:Could not decode JSON for additional information: BaseClientDetails解决办法

    错误描述 简述:oauth_client_details表中additional_information字段默认为null,ClientDetails实体类中类型为Map<String,Obje ...

  3. 新浪微博登陆,获取token

    用WeiboAuthListener获取code 用下面的代码获取token..半成品的sdk真让人捉急. String code = values.getString("code" ...

  4. ASP.NET WebApi OWIN 实现 OAuth 2.0(自定义获取 Token)

    相关文章:ASP.NET WebApi OWIN 实现 OAuth 2.0 之前的项目实现,Token 放在请求头的 Headers 里面,类似于这样: Accept: application/jso ...

  5. MVC 统一验证Token demo

    /// <summary> /// 获取token /// </summary> /// <param name="staffId"></ ...

  6. spring security oauth2搭建resource-server demo及token改造成JWT令牌

    我们在上文讲了如何在spring security的环境中搭建基于oauth2协议的认证中心demo:https://www.cnblogs.com/process-h/p/15688971.html ...

  7. nodejs向远程服务器发送post请求----融云Web SDK/客户端获取token

    最近要用到一个叫融云的及时通讯的SDK,在获取token这个步骤的时候有点卡顿,以防以后碰到类似的问题,再此记录一下. 客户端通过融云 SDK 每次连接服务器时,都需要向服务器提供 Token,以便验 ...

  8. MVC控制器获取@Html.DropDownList值

    MVC控制器获取@Html.DropDownList值 发表于 2014 年 4 月 1 日 作者 efour — 暂无评论 先贴一段代码,演示@Html.DropDownList的使用. 前台 前台 ...

  9. 获取token,绑定微信号,自定义菜单,事件响应demo

    摘要: 这个demo包含了获取token,绑定微信号,设置自定义菜单,响应文本和事件 这个教程的基础篇和提升篇都看完了,总感觉有点隔靴挠痒的感觉,讲的东西我都懂,没有吸收多少新鲜的知识.貌似还没有我这 ...

随机推荐

  1. Windows 配置 nginx php 多版本切换

    1. 下载 nginx   nginx.org 2. 下载 php  windows.php.net   选择 nts 版本,解压后,将php.ini.development 重命名为  php.in ...

  2. js关系图库:aworkflow

    auto-workflow 用于快速构建各种关系图的库,比如流程图,可视化执行流等 github地址:https://github.com/auto-workflow/AWorkflow 快速开始 n ...

  3. 编写高质量代码改善C#程序的157个建议——建议73:避免锁定不恰当的同步对象

    建议73:避免锁定不恰当的同步对象 在C#中,让线程同步的另一种编码方式就是使用线程锁.线程锁的原理,就是锁住一个资源,使得应用程序在此刻只有一个线程访问该资源.通俗地讲,就是让多线程变成单线程.在C ...

  4. [LintCode笔记了解一下]80.Median

    Given a unsorted array with integers, find the median of it. A median is the middle number of the ar ...

  5. CodeForces 227E Anniversary (斐波那契的高妙性质+矩阵快速幂)

    There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathemati ...

  6. centos安装mysql,tomcat

    软件下载: jre和jdk下载:http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javas ...

  7. opencv——阈值分割图像

    #include "stdafx.h" #include "opencv2\opencv.hpp" using namespace cv; IplImage* ...

  8. shiro注解@RequiresPermissions多权限任选一参数用法

    @RequiresPermissions(value={"xxx:xxx","xxx:xxx"},logical=Logical.OR)

  9. mybatis mybatis.xml 文件和properties文件结合来进行配置数据源

  10. Reporting Service服务SharePoint集成模式安装配置(9、PowerPivot for SharePoint 安装配置详细)

    PowerPivot for SharePoint 增加了对发布到 SharePoint 中的 PowerPivot 工作簿的协作和文档管理支持. PowerPivot for SharePoint ...