使用VS2015新建一个WebApi项目。

关键的配置在Startup.Auth.cs里

public partial class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static string PublicClientId { get; private set; }

        // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // 将数据库上下文和用户管理器配置为对每个请求使用单个实例
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // 使应用程序可以使用 Cookie 来存储已登录用户的信息
            // 并使用 Cookie 来临时存储有关使用第三方登录提供程序登录的用户的信息
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // 针对基于 OAuth 的流配置应用程序
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(),
                //在生产模式下设 AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // 使应用程序可以使用不记名令牌来验证用户身份
            app.UseOAuthBearerTokens(OAuthOptions);

            // 取消注释以下行可允许使用第三方登录提供程序登录
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
    }

再建一个控制台项目ApiTest

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace TestApi
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "john@example.com";
            string password = "Password@123";
            var registerResult = Register(userName, password);

            Console.WriteLine("Registration Status Code: {0}", registerResult);

            //string token = GetToken(userName, password);
            //Console.WriteLine("");
            //Console.WriteLine("Access Token:");
            //Console.WriteLine(token);

            Dictionary<string, string> token = GetTokenDictionary(userName, password);
            Console.WriteLine("");
            Console.WriteLine("Access Token:");
            Console.WriteLine(token);

            // Write each item in the dictionary out to the console:
            foreach (var kvp in token)
            {
                Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);
            }
            Console.WriteLine("");

            Console.WriteLine("Getting User Info:");
            //Console.WriteLine(GetUserInfo());
            Console.WriteLine(GetUserInfo(token["access_token"]));

            Console.Read();
        }
        static string Register(string email, string password)
        {
            var registerModel = new
            {
                Email = email,
                Password = password,
                ConfirmPassword = password
            };
            using (var client = new HttpClient())
            {
                var response =
                    client.PostAsJsonAsync(
                    "http://localhost:8890/api/Account/Register",
                    registerModel).Result;
                return response.StatusCode.ToString();
            }
        }
        static string GetToken(string userName, string password)
        {
            var pairs = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>( "grant_type", "password" ),
                            new KeyValuePair<string, string>( "username", userName ),
                            new KeyValuePair<string, string> ( "Password", password )
                        };
            var content = new FormUrlEncodedContent(pairs);
            using (var client = new HttpClient())
            {
                var response =
                    client.PostAsync("http://localhost:8890/Token", content).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        static Dictionary<string, string> GetTokenDictionary(string userName, string password)
        {
            var pairs = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>( "grant_type", "password" ),
                    new KeyValuePair<string, string>( "username", userName ),
                    new KeyValuePair<string, string> ( "Password", password )
                };
            var content = new FormUrlEncodedContent(pairs);

            using (var client = new HttpClient())
            {
                var response =
                    client.PostAsync("http://localhost:8890/Token", content).Result;
                var result = response.Content.ReadAsStringAsync().Result;

                // Deserialize the JSON into a Dictionary<string, string>
                Dictionary<string, string> tokenDictionary =
                    JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                return tokenDictionary;
            }
        }
        static string GetUserInfo()
        {
            using (var client = new HttpClient())
            {
                var response =
                    client.GetAsync("http://localhost:8890/api/Account/UserInfo").Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        static string GetUserInfo(string token)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

                var response = client.GetAsync("http://localhost:8890/api/Account/UserInfo").Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        static HttpClient CreateClient(string accessToken = "")
        {
            var client = new HttpClient();
            if (!string.IsNullOrWhiteSpace(accessToken))
            {
                client.DefaultRequestHeaders.Authorization =
                    new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            }
            return client;
        }
    }
}

注意这里需要引入

运行起来

带角色授权的参考:

ASP.NET Web Api and Identity 2.0 – Customizing Identity Models and Implementing Role-Based Authorization

ASP.NET WebAPI Bearer Authorization的更多相关文章

  1. Add JWT Bearer Authorization to Swagger and ASP.NET Core

    Add JWT Bearer Authorization to Swagger and ASP.NET Core     If you have an ASP.NET Core web applica ...

  2. ASP.NET WebApi OWIN 实现 OAuth 2.0

    OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用. OAuth 允许用户提供一个令牌, ...

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

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

  4. [转]ASP.NET WebApi OWIN 实现 OAuth 2.0

    OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用. OAuth 允许用户提供一个令牌, ...

  5. ASP.NET WEBAPI 的身份验证和授权

    定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...

  6. 基于OWIN ASP.NET WebAPI 使用OAUTH2授权服务的几点优化

    前面在ASP.NET WEBAPI中集成了Client Credentials Grant与Resource Owner Password Credentials Grant两种OAUTH2模式,今天 ...

  7. ASP.NET WebApi 基于分布式Session方式实现Token签名认证

    一.课程介绍 明人不说暗话,跟着阿笨一起学玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NETWebSer ...

  8. ASP.NET WebAPI 双向token实现对接小程序登录逻辑

    最近在学习用asp.net webapi搭建小程序的后台服务,因为基于小程序端和后台二者的通信,不像OAuth(开放授权),存在第三方应用.所以这个token是双向的,一个是对用户的,一个是对接口的. ...

  9. ASP.NET WebApi 基于分布式Session方式实现Token签名认证(发布版)

    一.课程介绍 明人不说暗话,跟着阿笨一起学玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NETWebSer ...

随机推荐

  1. idea intellij对Spring进行单元测试

    1.加入Junit4及SpringJUnit4支持 <!-- junit --> <dependency> <groupId>junit</groupId&g ...

  2. crontab使用环境变量

    两种方式: 1)直接在crontab中定义变量,如: A=123 * * * * * echo $A > /tmp/a.txt 注意在定义变量时不能使用$引用其它变量,如下面的做法错误: A=1 ...

  3. QT中的线程与事件循环理解(1)

    1.需要使用多线程管理的例子 一个进程可以有一个或更多线程同时运行.线程可以看做是“轻量级进程”,进程完全由操作系统管理,线程即可以由操作系统管理,也可以由应用程序管理.Qt 使用QThread 来管 ...

  4. js跳转页面方法实现汇总

    一.页面之间的跳转传参 1.在页面之间跳转的方式有两种: window.location.href=”test.html?num=10”   地址会改变参数也会被传递但是不会打开新窗口 window. ...

  5. python操作Hbase

    本地操作 启动thrift服务:./bin/hbase-daemon.sh start thrift hbase模块产生: 下载thrfit源码包:thrift-0.8.0.tar.gz 解压安装 . ...

  6. 求n得阶乘得最后一位非零数字

    如题,最后一位数好求,他只和最后一位相乘后的最后一位有关,唯一影响我们得是末尾0,而阶乘中末尾0来自于2和5,(10得话可以看成2 * 5),所以有这个思想我们可以筛选出1 * 2 * 3 * ... ...

  7. ASP.NET Web API 框架研究 Action的选择

    如何从HttpController众多方法里如何选择出有效的Action方法?主要分一下几个步骤: 首先,获取候选HttpActionDescriptor列表(ILookup(string,HttpA ...

  8. Implementation of WC in JAVA

    Implementation of WC in JAVA github地址 相关要求 基本功能 -c [文件名] 返回文件的字符数 (实现) -w [文件名] 返回文件的词的数目 (实现) -l [文 ...

  9. PCB中实现元器件旋转一个角度放置

    我们常常放置器件都是横着或者竖着的...但是有时候需要器件能旋转一个角度放更方便的话,可以这样 设置器件的属性.....

  10. INDEX--从数据存放的角度看索引

    测试表结构: CREATE TABLE TB1 ( ID ,), C1 INT, C2 INT ) 1. 聚集索引(Clustered index) 聚集索引可以理解为一个包含表中除索引键外多有剩余列 ...