OAuth2建立webapi认证服务供自己的客户端使用--密码模式
场景:你自己实现了一套webApi,想供自己的客户端调用,又想做认证。

第一步:通过vs2015建立web api项目,Startup.cs,这个类将会作为Owin的启动类。

第二步:在webapi.config中添加如下代码:

第三步:在web.config中添加连接字符串(这里使用了EF Code First)

第四步:添加上下文对象

第五步:添加AuthRepository类,增加用户注册和查找功能:

第六步:增加AccountController(
using Microsoft.AspNet.Identity;
using Owin2.Auth;
using Owin2.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http; namespace Owin2.Controllers
{
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
private readonly AuthRepository _authRepository = null; public AccountController()
{
_authRepository = new AuthRepository();
}
// POST api/Account/Register Register方法打上了AllowAnonymous标签,意味着调用这个api无需任何授权。
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(UserModel userModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} IdentityResult result = await _authRepository.RegisterUser(userModel); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null)
{
return errorResult;
} return Ok();
} protected override void Dispose(bool disposing)
{
if (disposing)
{
_authRepository.Dispose();
} base.Dispose(disposing);
} private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
} if (!result.Succeeded)
{
if (result.Errors != null)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
} if (ModelState.IsValid)
{ // No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
} return BadRequest(ModelState);
} return null;
}
}
}
认证策略的类:
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web; namespace Owin2.Auth
{
public class SimpleAuthorizationServerProvider: OAuthAuthorizationServerProvider
{ /// <summary>
/// ValidateClientAuthentication方法用来对third party application 认证,
/// 具体的做法是为third party application颁发appKey和appSecrect,
/// 在本例中我们省略了颁发appKey和appSecrect的环节,
/// 我们认为所有的third party application都是合法的,context.Validated();
/// 表示所有允许此third party application请求。
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult<object>(null);
} /// <summary>
/// GrantResourceOwnerCredentials方法则
/// 是resource owner password credentials模式的重点
/// 由于客户端发送了用户的用户名和密码,
/// 所以我们在这里验证用户名和密码是否正确,
/// 后面的代码采用了ClaimsIdentity认证方式,
/// 其实我们可以把他当作一个NameValueCollection看待。
/// 最后context.Validated(ticket); 表明认证通过
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password); if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
} var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
identity.AddClaim(new Claim("sub", context.UserName)); var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id",context.ClientId ?? string.Empty
},
{
"userName",context.UserName
}
}); var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
} /// <summary>
/// TokenEndpoint方法将会把Context中的属性加入到token中。
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
} return Task.FromResult<object>(null);
} }
}
OAuth2服务已经搭建好了,建立客户端来测试。
第七步:建立客户端(新建另外一个api程序),并且配置Startup.cs

第八步:配置web api.config

第九步:建立测试api控制器

1.先注册
2.通过用户名和密码获取token

3.通过token请求api

客户端和服务端通过配置文件关联。

OAuth2建立webapi认证服务供自己的客户端使用--密码模式的更多相关文章
- 使用OAuth打造webapi认证服务供自己的客户端使用
一.什么是OAuth OAuth是一个关于授权(Authorization)的开放网络标准,目前的版本是2.0版.注意是Authorization(授权),而不是Authentication(认证). ...
- 使用OAuth打造webapi认证服务供自己的客户端使用(二)
在上一篇”使用OAuth打造webapi认证服务供自己的客户端使用“的文章中我们实现了一个采用了OAuth流程3-密码模式(resource owner password credentials)的W ...
- OAuth打造webapi认证服务
使用OAuth打造webapi认证服务供自己的客户端使用 一.什么是OAuth OAuth是一个关于授权(Authorization)的开放网络标准,目前的版本是2.0版.注意是Authorizati ...
- Spring Boot Security Oauth2之客户端模式及密码模式实现
Spring Boot Security Oauth2之客户端模式及密码模式实现 示例主要内容 1.多认证模式(密码模式.客户端模式) 2.token存到redis支持 3.资源保护 4.密码模式用户 ...
- SpringBootSecurity学习(17)前后端分离版之 OAuth2.0 数据库(JDBC)存储客户端
自动批准授权码 前面我们授权的流程中,第一步获取授权码的时候,都会经历一个授权是否同意页面: 这个流程就像第三方登录成功后,提问是否允许获取昵称和头像信息的页面一样,这个过程其实是可以自动同意的,需要 ...
- Core篇——初探IdentityServer4(客户端模式,密码模式)
Core篇——初探IdentityServer4(客户端模式,密码模式) 目录 1.Oatuth2协议的客户端模式介绍2.IdentityServer4客户端模式实现3.Oatuth2协议的密码模式介 ...
- postgres(pgAdmin) 客户端保存密码
pgAdmin 大象客户端保存密码后连接服务器,删除掉当前连接,建立一个新的连接不用输入密码也能连接上,其实是客户端保存了密码,让人误以为是空密码可登录.可以通过右键连接,选择重载服务配置,再次连接就 ...
- 在线建立或重做mysql主从复制架构方法(传统模式和GTID模式)【转】
mysql主从复制架构,是mysql数据库主要特色之一,绝大多数公司都有用到. 而GTID模式是基于事务的复制模式的意思,发展到现在也是越来越多人用. 以前很多文章,介绍搭建mysql主从复制架构,是 ...
- Security-OAuth2.0 密码模式之客户端实现
我的OAuth2.0 客户端项目目录 pom 的配置 <?xml version="1.0" encoding="UTF-8"?> <proj ...
随机推荐
- (转) RabbitMQ学习之远程过程调用(RPC)(java)
http://blog.csdn.net/zhu_tianwei/article/details/40887885 在一般使用RabbitMQ做RPC很容易.客户端发送一个请求消息然后服务器回复一个响 ...
- C# 生成Model和DAL
using Model; using System.Collections.Generic; using System.Text; public class Class1 { #region 生成Mo ...
- 优动漫PAINT(clip studio paint)怎么画一幅水墨竹子图
今天小编分享使用优动漫PAINT绘制一个水墨竹子教程,绘画的过程中我只用到了两个笔刷,即钢笔模式下的“美术字”和“效果线专用”,并且全程鼠标绘制哦,所以生疏的笔触效果大家见谅,没有数位板的小伙伴不妨试 ...
- SaltStact自动化运维工具02
Grains基础:• Grains是saltstack最重要的组件之一• 存储minion端的基本信息,这些信息一般都是静态的,如CPU.内核.操作系统等• Grains存储在minion本地• 管 ...
- Asp 6种页面转向方法
asp.net 页面转向方法其实就是两种 服务器端转向和客户端转向 客户端转向实质上是指由浏览器直接向服务器端重新发送一个请求. 而服务器端转向是指服务器内部进行页面的跳转. 服务器端转向和客户端转向 ...
- 【JavaScript框架封装】使用Prototype给Array,String,Function对象的方法扩充
/* * @Author: 我爱科技论坛* @Time: 20180705 * @Desc: 实现一个类似于JQuery功能的框架* V 1.0: 实现了基础框架.事件框架.CSS框架.属性框架.内容 ...
- 使用shell脚本定时执行备份mysql数据库
使用shell脚本定时执行备份mysql数据库 #!/bin/bash ############### common file ################ #本机备份文件存放目录 MYSQLBA ...
- CentOS 笔记(五) 常用工具
远程 :XShell6 ,PuTTy FPT:Xfpt ,pscp.exe
- 运用cat EOF添加文件
[root@fyc14 nginx1]# cat <<EOF > /etc/yum.repos.d/nginx.repo> [nginx]> name=nginx rep ...
- 题解 ZOJ3203 Light Bulb
也就是loj上的#10016灯泡了... 先上原图: 因为长度肯定是个开口向下的二次函数,所以先是确定用三分来找位置,然后想办法求出当前阴影长度 看到这条斜线,就想到了一次函数,所以就建了一个系,没想 ...
