asp.net-web-api – 在没有Identity的情况下使用Bearer / Jwt授
发布时间:2020-12-16 03:17:15 所属栏目:asp.Net 来源:网络整理
导读:我想用Asp 5开发Web API并阅读一些关于Web API的文档,我知道我需要Bearer授权. 搜索后,我发现没有Aspnet.Identity使用授权的任何文件或样本.我有自己的会员资格,我不想使用Identity 我应该使用身份库吗?或者有没有办法在我的会员资格中实施授权. 一个小问题
我想用Asp 5开发Web API并阅读一些关于Web API的文档,我知道我需要Bearer授权.
搜索后,我发现没有Aspnet.Identity使用授权的任何文件或样本.我有自己的会员资格,我不想使用Identity 我应该使用身份库吗?或者有没有办法在我的会员资格中实施授权. 一个小问题: 解决方法
要发布自己的JWT令牌,可以使用
OpenIddict:
project.json { "dependencies": { // ... "AspNet.Security.OAuth.Validation": "1.0.0-*","OpenIddict": "1.0.0-*","OpenIddict.EntityFrameworkCore": "1.0.0-*","OpenIddict.Mvc": "1.0.0-*" } } Startup.cs public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDbContext<DbContext>(options => { // Configure the context to use an in-memory store. options.UseInMemoryDatabase(); // Register the entity sets needed by OpenIddict. // Note: use the generic overload if you need // to replace the default OpenIddict entities. options.USEOpenIddict(); }); services.AddOpenIddict(options => { // Register the Entity Framework stores. options.AddEntityFrameworkCoreStores<DbContext>(); // Register the ASP.NET Core MVC binder used by OpenIddict. // Note: if you don't call this method,you won't be able to // bind OpenIdConnectRequest or OpenIdConnectResponse parameters. options.AddMvcBinders(); // Enable the token endpoint. options.EnableTokenEndpoint("/connect/token"); // Enable the password flow. options.AllowPasswordFlow(); // During development,you can disable the HTTPS requirement. options.DisableHttpsRequirement(); }); } public void Configure(IApplicationBuilder app) { // Register the validation middleware,that is used to decrypt // the access tokens and populate the HttpContext.User property. app.USEOAuthValidation(); // Register the OpenIddict middleware. app.USEOpenIddict(); app.UseMvcWithDefaultRoute(); } } AuthorizationController.cs public class AuthorizationController : Controller { [HttpPost("~/connect/token"),Produces("application/json")] public IActionResult Exchange(OpenIdConnectRequest request) { if (request.IsPasswordGrantType()) { // Validate the user credentials. // Note: to mitigate brute force attacks,you SHOULD strongly consider // applying a key derivation function like PBKDF2 to slow down // the password validation process. You SHOULD also consider // using a time-constant comparer to prevent timing attacks. if (request.Username != "alice@wonderland.com" || request.Password != "P@ssw0rd") { return Forbid(OpenIdConnectServerDefaults.AuthenticationScheme); } // Create a new ClaimsIdentity holding the user identity. var identity = new ClaimsIdentity( OpenIdConnectServerDefaults.AuthenticationScheme,OpenIdConnectConstants.Claims.Name,OpenIdConnectConstants.Claims.Role); // Add a "sub" claim containing the user identifier,and attach // the "access_token" destination to allow OpenIddict to store it // in the access token,so it can be retrieved from your controllers. identity.AddClaim(OpenIdConnectConstants.Claims.Subject,"71346D62-9BA5-4B6D-9ECA-755574D628D8",OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.Name,"Alice",OpenIdConnectConstants.Destinations.AccessToken); // ... add other claims,if necessary. var principal = new ClaimsPrincipal(identity); // Ask OpenIddict to generate a new token and return an OAuth2 token response. return SignIn(principal,OpenIdConnectServerDefaults.AuthenticationScheme); } throw new InvalidOperationException("The specified grant type is not supported."); } } 请求 POST /connect/token HTTP/1.1 Host: localhost:7096 Content-Type: application/x-www-form-urlencoded grant_type=password&username=alice%40wonderland.com&password=P%40ssw0rd 响应 { "token_type": "Bearer","access_token": "CfDJ8Ec0ZpniaHhGg0e0UUvOH9BWZSGrPoEwGd0_Lq2cse-T29YOq985IBiT5fEe5tTSgY1vxq2Z2ZJ7Ikwlpmh0Lrc4x9pqhqHBziUzsP_rkGZkn47TkNkOkzKCwZJZK5x-irH3HROwClFFTq0rgWdb8rZ2xriffNzsby4VwhxhN5soFD435KzmVYkdv-VuaLYo3QiSuexbRi2USVO9LK30vomAG6h2SAxZ7R-jYsXgf0f5gAmdYxg7w3yicv9v8DpUSBiGGRRfymTOnvGEsFJjGuuP8OlY5qzMs6wGaRWkOvCyV2CK_RZF_3TMs7LYCdMQ-dqWY5A03-03OmP8blKzlrKJMDZfrPQHuysbS931xxy8b3kjicfjNLmMHqzQzbUO4fecm4kY8PFnKozojDtqajfTp2bYhxS65bmVYROrswYeUWEKYR6LSdS1K__IDaLoMlLa-Wf6x1wjM2CchzgqbHRF0KEtdL5Ks88dAS44mp9BM6iUOEWyL7VkbazsBdlNciM5ZZB1_6qunufDW_tcaR8","expires_in": 3600 } 有关更多信息,请阅读我撰写的关于OpenIddict:http://kevinchalet.com/2017/01/30/implementing-simple-token-authentication-in-aspnet-core-with-openiddict/的博客文章 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – C# – 一次将多个记录插入AS400
- 如何在ASP.net MVC中正确执行异步方法?
- asp.net-mvc – 使用jquery Ajax加载PartialView?
- 异常处理 – 如何处理WebAPI中的控制器构造函数中的异常?
- asp.net – 确定对IIS施加压力的因素
- ADO.NET实用经验 转载
- asp.net-mvc – ASP.NET MVC3 IIS7.5:Cache-Control maxag
- asp.net-mvc – JsonSerializer – 使用’N2’格式序列化小
- Asp.net复选框和html数据属性
- ASP.NET Core 开源GitServer 实现自己的GitHub
推荐文章
站长推荐
- asp.net – WCF:是否有一个属性要在OperationCo
- 如何下载特定版本的ASP.NET MVC 5源代码
- asp.net – GridView上的滚动条
- asp.net – UpdatePanel异常处理
- asp.net-mvc – 当model是父模型上的属性且为nul
- IIS7集成vs经典流水线 – 哪些使用更多的ASP.NET
- .net – SqlConnection的Dispose方法是否会干扰连
- 尝试调试我迁移的ASP.NET(WebForms)应用程序时出
- asp.net – 在用户表或单独的配置文件表中存储用
- asp.net-mvc – 版本弃用Facebook Graph API v2.
热点阅读