當前位置:首頁 » 密碼管理 » webapi數據傳輸加密

webapi數據傳輸加密

發布時間: 2022-08-23 02:45:35

❶ 如何使用 Web API 來對 MVC 應用程序進行身份驗證

首先,讓我們先更新 API 項目

我們將先對 API 項目進行必要的修改,修改完成之後再切換到 Web 項目對客戶端進行更新。

第1步:我們需要一個資料庫

在能做任何操作之前我們需要先創建一個資料庫。本例中將使用 sql Server Express。如果你沒有安裝,可以從這里下載 SQL Server Express。安裝完成之後,創建一個名為 CallingWebApiFromMvc 的資料庫。這就是第一步要做的。

Api 項目還需要一個資料庫連接字元串,否則我們寸步難行。把下面這段代碼插入到 Api 項目的Web.config 文件中:

<connectionStrings>
<add name="ApiFromMvcConnection" connectionString="Data Source=(local);Initial Catalog=CallingWebApiFromMvc;Integrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings>

認證(Identity)框架會自動創建我們管理用戶所需要的成員關系表,現在不需要擔心去提前創建它們。

第2步:添加相關的Nuget包

接下來我們添加用於OWIN和Windows認證的Nuget包。打開包管理控制台,切換Api項目為預設項目,輸入以下命令:

Install-Package Microsoft.AspNet.WebApi.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.AspNet.Identity.EntityFramework
Install-Package Microsoft.AspNet.Identity.Owin

使用這些包可以在我們的應用中啟動一個OWIN伺服器,然後通過EntityFramework把我們的用戶保存到SQL Server。

第3步:添加管理用戶的Identity類

我們使用基於Windows認證機制之上的Entity框架來管理資料庫相關的業務。首先我們需要添加一些用於處理的類。在Api項目里添加一個Identity目錄作為我們要添加類的命名空間。然後添加如下的類:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{ public ApplicationDbContext() : base("ApiFromMvcConnection") {}
public static ApplicationDbContext Create()
{ return new ApplicationDbContext();
}
}

注意我們傳給基類構造函數的參數ApiFromMvcConnection要和Web.config中的連接字元串中的name相匹配。

public class ApplicationUserManager : UserManager<ApplicationUser>
{ public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store)
{
} public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{ var manager = new ApplicationUserManager(new UserStore<ApplicationUser> (context.Get<ApplicationDbContext> ()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser> (manager)
{
= false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
}; var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser> (dataProtectionProvider.Create("ASP.NET Identity"));
} return manager;
}
}

第4步:添加OWIN啟動類

為了讓我們的應用程序作為OWIN伺服器上運行,我們需要在應用程序啟動時初始化。我們可以通過一個啟動類做到這一點。我們將裝點這個類的
OwinStartup屬性,因此在應用程序啟動時觸發。這也意味著,我們可以擺脫的Global.asax和移動它們的
Application_Start代碼轉換成我們新的啟動類。

using Microsoft.Owin;

[assembly: OwinStartup(typeof(Levelnis.Learning.CallingWebApiFromMvc.Api.Startup))]
namespace Levelnis.Learning.CallingWebApiFromMvc.Api
{
using System;
using System.Web.Http;
using Identity;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Providers;
public class Startup
{ public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager> (ApplicationUserManager.Create); var oAuthOptions = new
{
TokenEndpointPath = new PathString("/api/token"),
Provider = new ApplicationOAuthProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(oAuthOptions);
}
}
}

在應用程序啟動時,我們正在建立自己的伺服器。在這里,我們配置令牌端點並設置自己的自定義提供商,我們用我們的用戶進行身份驗證。在我們的例子中,我們使用了ApplicationOAuthProvider類。讓我們來看看現在:

第5步:添加OAuth的提供商

public class ApplicationOAuthProvider :
{ public override Task ValidateClientAuthentication( context)
{
context.Validated();
return Task.FromResult<object> (null);
}
public override async Task GrantResourceOwnerCredentials( context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager> ();
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect."); return;
}
var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); var cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); var properties = CreateProperties(user.UserName); var ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
private static AuthenticationProperties CreateProperties(string userName)
{
var data = new Dictionary<string, string>
{
{
"userName", userName
}
};
return new AuthenticationProperties(data);
}
}

我們感興趣的是這里2種方法。第一,ValidateClientAuthentication,只是驗證客戶端。我們有一個客戶端,所以返回成
功。這是一個非同步方法簽名但沒有非同步調用發生。正因為如此,我們可以離開了非同步修改,但我們必須返回一個任務自己。我們增加了一個名為
GenerateUserIdentityAsync的ApplicationUser,它看起來像這樣的方法:

public class ApplicationUser : IdentityUser
{ public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
return userIdentity;
}
}

第6步:注冊一個新用戶 - API端
所以,我們有到位的所有Identity類管理用戶。讓我們來看看RegisterController,將新用戶保存到我們的資料庫。它接受一個RegisterApi模式,這是簡單的:

public class RegisterApiModel
{
[Required]
[EmailAddress] public string Email { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Password {
get; set;
}

[Required]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

控制器本身,如果注冊成功只是返回一個200 OK響應。如果驗證失敗,則返回401錯誤請求的響應。

public class RegisterController : ApiController
{ private ApplicationUserManager UserManager
{ get
{ return Request.GetOwinContext().GetUserManager<ApplicationUserManager> ();
}
} public IHttpActionResult Post(RegisterApiModel model)
{ if (!ModelState.IsValid)
{ return BadRequest(ModelState);
} var user = new ApplicationUser
{
Email = model.Email,
UserName = model.Email,
EmailConfirmed = true
};
var result = UserManager.Create(user, model.Password);
return result.Succeeded ? Ok() : GetErrorResult(result);
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (result.Errors != null)
{
foreach (var 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);
}
}

❷ 怎樣用webapi連接到資料庫的數據

先打開vs2010軟體,找到項目文件,雙擊web.config
vs2010中web.config配置資料庫連接
第一種:取連接字元串
string
connstring
=
system.web.configuration.webconfigurationmanager.connectionstrings["sqlconnstr"].connectionstring;
或者
protected
static
string
connectionstring
=
configurationmanager.connectionstrings["sqlconnstr"].connectionstring;
web.config文件:加在</configsections>後面
<connectionstrings>
<remove
name="localsqlserver"
/>
<add
name="sqlconnstr"
connectionstring="user
id=xx;password=xx;initial
catalog=database_name;data
source=.\sqlxxxx"
/>
</connectionstrings>
vs2010中web.config配置資料庫連接
第二種:取連接字元串:
string
myvar=configurationsettings.appsettings["connstring"];
web.config文件:加在<appsettings>和</appsettings>
之間
<appsettings>
<add
key="connstring"
value="uid=xx;pwd=xx;database=batabase_name;server=(local)"
/>
</appsettings>
據說兩者通用,但是第二種是asp.net2.0的新特性,建議使用第二種。其實我一直有個疑問,兩個字元串中的uid;pwd;和user
id;
password;是否等價。根據網上我查到的資料是可以互換通用的。
vs2010中web.config配置資料庫連接
連接sql
server資料庫的機制與連接access的機制沒有什麼太大的區別,只是改變了connection對象和連接字元串中的不同參數.
首先,連接sql
server使用的命名空間不是"system.data.oledb",而是"system.data.sqlclient".
其次就是他的連接字元串了,我們一個一個參數來介紹(注意:參數間用分號分隔):
"user
id=sa":連接資料庫的驗證用戶名為sa.他還有一個別名"uid",所以這句我們還可以寫成"uid=sa".
"password=":連接資料庫的驗證密碼為空.他的別名為"pwd",所以我們可以寫為"pwd=".
這里注意,你的sql
server必須已經設置了需要用戶名和密碼來登錄,否則不能用這樣的方式來登錄.如果你的sql
server設置為windows登錄,那麼在這里就不需要使用"user
id"和"password"這樣的方式來登錄,而需要使用"trusted_connection=sspi"來進行登錄.
initial
catalog=northwind":使用的數據源為"northwind"這個資料庫.他的別名為"database",本句可以寫成"database=northwind".
"server=yoursqlserver":使用名為"yoursqlserver"的伺服器.他的別名為"data
source","address","addr".如果使用的是本地資料庫且定義了實例名,則可以寫為"server=(local)\實例名";如果是遠程伺服器,則將"(local)"替換為遠程伺服器的名稱或ip地址.
"connect
timeout=30":連接超時時間為30秒.
在這里,建立連接對象用的構造函數為:sqlconnection.
7
最後要保存你所更改的文件,右鍵
保存(ctrl+s).

❸ WebAPI與傳統的WebService有哪些不同

在.net平台下,有大量的技術讓你創建一個HTTP服務,像Web Service,WCF,現在又出了Web API。在.net平台下,你有很多的選擇來構建一個HTTP Services。我分享一下我對Web Service、WCF以及Web API的看法。

Web Service

1、它是基於SOAP協議的,數據格式是XML

2、只支持HTTP協議

3、它不是開源的,但可以被任意一個了解XML的人使用

4、它只能部署在IIS上

WCF

1、這個也是基於SOAP的,數據格式是XML

2、這個是Web Service(ASMX)的進化版,可以支持各種各樣的協議,像TCP,HTTP,HTTPS,Named Pipes, MSMQ.

3、WCF的主要問題是,它配置起來特別的繁瑣

4、它不是開源的,但可以被任意一個了解XML的人使用

5、它可以部署應用程序中或者IIS上或者Windows服務中

WCF Rest

1、想使用WCF Rest service,你必須在WCF中使用webHttpBindings

2、它分別用[WebGet]和[WebInvoke]屬性,實現了HTTP的GET和POST動詞

3、要想使用其他的HTTP動詞,你需要在IIS中做一些配置,使.svc文件可以接受這些動詞的請求

4、使用WebGet通過參數傳輸數據,也需要配置。而且必須指定UriTemplate

5、它支持XML、JSON以及ATOM這些數據格式

Web API

1、這是一個簡單的構建HTTP服務的新框架

2、在.net平台上Web API 是一個開源的、理想的、構建REST-ful 服務的技術

3、不像WCF REST Service.它可以使用HTTP的全部特點(比如URIs、request/response頭,緩存,版本控制,多種內容格式)

4、它也支持MVC的特徵,像路由、控制器、action、filter、模型綁定、控制反轉(IOC)或依賴注入(DI),單元測試。這些可以使程序更簡單、更健壯

5、它可以部署在應用程序和IIS上

6、這是一個輕量級的框架,並且對限制帶寬的設備,比如智能手機等支持的很好

7、Response可以被Web API的MediaTypeFormatter轉換成Json、XML 或者任何你想轉換的格式。WCF和WEB API我該選擇哪個?

1、當你想創建一個支持消息、消息隊列、雙工通信的服務時,你應該選擇WCF

2、當你想創建一個服務,可以用更快速的傳輸通道時,像TCP、Named Pipes或者甚至是UDP(在WCF4.5中),在其他傳輸通道不可用的時候也可以支持HTTP。

3、當你想創建一個基於HTTP的面向資源的服務並且可以使用HTTP的全部特徵時(比如URIs、request/response頭,緩存,版本控制,多種內容格式),你應該選擇Web API

4、當你想讓你的服務用於瀏覽器、手機、iPhone和平板電腦時,你應該選擇Web API

❹ webapi做了authorizationfilterattribute驗證前端怎麼調用

取決於api的加密方式。

如加密方式為bearer token的方式。

調用一個需要驗證的api步驟是:

  1. POST請求介面:http://ip地址/api/token

    參數:{"username":"xxx","password":"xxx","grant_type":"password"} http請求頭:{"Content-Type":"application/x-www-form-urlencoded"}

  2. 第一個介面會返回一個"access_token"(以下稱為token)。請求需要驗證介面的api時,http頭上加入:{"Authorization:bearer [token]"}即可。

❺ 2018年10月微信小程序上傳文件的問題webapi方式

必須在微信公眾平台填寫請求,下載,上傳,websocket 域名,必須是SSL加密的

❻ 如何在 webApi 當中接收 Gzip 壓縮或者加密後的 請求消息內容

有許多情景當你的REST api提供的相應是非常長的,並且我們都知道傳遞速度和貸款在移動設備/網路上是多重要。當開發支持REST apis的移動app的時候,我認為首要的性能最優化的點就是需要解決。猜猜是什麼?因為響應式文本,因此我們能壓縮這些文本。而且隨著當前的只能手機和平板的能力,在客戶端解壓文本應該不是個大問題...因此在這篇文章中,如果你使用java的Jersey構建它,我將介紹你怎麼能有選擇性的壓縮REST API響應,這個Jersey事JAX-RS的映射實現(還有更多)... 1.Jersey過濾器和攔截器 啊,感謝Jersey的強大的過濾器和攔截器特性,這個實現是相當容易的。然後過濾器是主要打算來維護像HTTP headers,URIs和/或HTTP methods的request和response的參數,攔截器是維護實體,通過維護實體的...

熱點內容
html文件上傳表單 發布:2024-09-17 03:08:02 瀏覽:783
聊天軟體編程 發布:2024-09-17 03:00:07 瀏覽:725
linuxoracle安裝路徑 發布:2024-09-17 01:57:29 瀏覽:688
兩個安卓手機照片怎麼同步 發布:2024-09-17 01:51:53 瀏覽:207
cf編譯後沒有黑框跳出來 發布:2024-09-17 01:46:54 瀏覽:249
安卓怎麼禁用應用讀取列表 發布:2024-09-17 01:46:45 瀏覽:524
win10設密碼在哪裡 發布:2024-09-17 01:33:32 瀏覽:662
情逢敵手迅雷下載ftp 發布:2024-09-17 01:32:35 瀏覽:337
安卓如何讓軟體按照步驟自動運行 發布:2024-09-17 01:28:27 瀏覽:197
Z包解壓命令 發布:2024-09-17 01:27:51 瀏覽:221