jwt – ASP.NET 5 OAuthBearerAuthentication:以下认证方案未被接受:承载

前端之家收集整理的这篇文章主要介绍了jwt – ASP.NET 5 OAuthBearerAuthentication:以下认证方案未被接受:承载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
更新:

Pinpoint帮助我把这个原型放在发射台上 – 我非常接近,除了:

>我需要根据these instructions升级到beta6 SDK.Global.json现在显示如下:

  1. {
  2. "projects": [ "src","test" ],"sdk": {
  3. "version": "1.0.0-beta6"
  4. }
  5. }

>我更新了project.json中的引用:

  1. {
  2. "webroot": "wwwroot","version": "1.0.0-*","dependencies": {
  3. "Microsoft.AspNet.Mvc": "6.0.0-beta6","Microsoft.AspNet.Server.IIS": "1.0.0-beta6","Microsoft.AspNet.Server.WebListener": "1.0.0-beta6","Microsoft.AspNet.StaticFiles": "1.0.0-beta6","System.IdentityModel.Tokens": "5.0.0-beta6-207211625","Serilog.Framework.Logging": "1.0.0-beta-43","Microsoft.AspNet.Authentication.OAuthBearer": "1.0.0-beta6"
  4. },"commands": {
  5. "web": "Microsoft.AspNet.Hosting --config hosting.ini"
  6. },"frameworks": {
  7. "dnx451": { }
  8. },"exclude": [
  9. "wwwroot","node_modules","bower_components"
  10. ],"publishExclude": [
  11. "node_modules","bower_components","**.xproj","**.user","**.vspscc"
  12. ]
  13. }

>启动配置方法中的中间件顺序很重要. USEOAuthBearerAuthentication需要在UseMvc之前使用. Startup.cs中的Configure方法现在显示如下:

  1. public void Configure(IApplicationBuilder app,IHostingEnvironment env)
  2. {
  3. app.USEOAuthBearerAuthentication();
  4.  
  5. app.UseMvc();
  6. }

我正在使用ASP.NET 5,并试图实现一个非常简单的概念证明来生成和使用JWT令牌.我已经阅读了文章here,@L_404_2@和here,但this one最符合我的需求.

为此,我非常仔细地阅读文章,重新阅读,内部化所有的评论,然后站起来一个简单的例子.我现在可以生成一个JWT令牌,但是当我尝试使用授权属性[Authorize(“Bearer”)]来调用我的控制器操作时,我收到以下消息:

The following authentication scheme was not accepted: Bearer

由于我没有看到如何做到这一点的高保真A到Z的例子,请考虑以下步骤来重现:

>在Visual Studio 2015中创建一个新的Web API项目(我正在使用Enterprise),选择“新建项目… Web … ASP.NET Web应用程序”,然后选择“ASP.NET 5”下的“Web API”选项预览模板“
>使用beta 5 SDK,global.json如下所示:

  1. {
  2. "projects": [ "src","sdk": {
  3. "version": "1.0.0-beta5","runtime": "clr","architecture": "x86"
  4. }
  5. }

>引入JWT令牌所需的依赖项,project.json如下所示:

  1. {
  2. "webroot": "wwwroot","dependencies": {
  3. "Microsoft.AspNet.Mvc": "6.0.0-beta6","System.IdentityModel.Tokens": "5.0.0-beta5-206011020","Microsoft.AspNet.Authentication.OAuthBearer": "1.0.0-beta5"
  4. },"commands": {
  5. "web": "Microsoft.AspNet.Hosting --config hosting.ini"
  6. },"frameworks": {
  7. "dnx451": { }
  8. },"exclude": [
  9. "wwwroot","bower_components"
  10. ],"publishExclude": [
  11. "node_modules","**.vspscc"
  12. ]
  13. }

> Startup.cs(这是不适合生产的示例)

  1. public class Startup
  2. {
  3. const string _TokenIssuer = "contoso.com" ;
  4. const string _TokenAudience = "contoso.com/resources" ;
  5. RsaSecurityKey _key = null ;
  6. SigningCredentials _signingCredentials = null ;
  7.  
  8. public Startup(IHostingEnvironment env)
  9. {
  10. GenerateRsaKeys();
  11. }
  12.  
  13. public void ConfigureServices(IServiceCollection services)
  14. {
  15. services.AddInstance(_signingCredentials);
  16.  
  17. services.ConfigureOAuthBearerAuthentication
  18. (
  19. options =>
  20. {
  21. options.AutomaticAuthentication = true;
  22. options.TokenValidationParameters.IssuerSigningKey = _key ;
  23. options.TokenValidationParameters.ValidAudience = _TokenAudience;
  24. options.TokenValidationParameters.ValidIssuer = _TokenIssuer ;
  25. }
  26. );
  27.  
  28. services.ConfigureAuthorization
  29. (
  30. options =>
  31. {
  32. options.
  33. AddPolicy
  34. (
  35. "Bearer",new AuthorizationPolicyBuilder().
  36. AddAuthenticationSchemes(OAuthBearerAuthenticationDefaults.AuthenticationScheme).
  37. RequireAuthenticatedUser().
  38. Build()
  39. );
  40. }
  41. );
  42.  
  43. services.AddMvc();
  44. }
  45.  
  46. public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerfactory)
  47. {
  48. app.UseMvc();
  49.  
  50. app.USEOAuthBearerAuthentication();
  51. }
  52.  
  53. void GenerateRsaKeys()
  54. {
  55. using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
  56. {
  57. _key = new RsaSecurityKey(rsa.ExportParameters(true));
  58.  
  59. _signingCredentials =
  60. new SigningCredentials
  61. (
  62. _key,SecurityAlgorithms.RsaSha256Signature,SecurityAlgorithms.Sha256Digest,"secret"
  63. );
  64.  
  65. rsa.PersistKeyInCsp = false;
  66. }
  67. }
  68. }

>一些型号:

Credentials.cs

  1. public class Credentials
  2. {
  3. public string user { set;get;}
  4. public string password { set;get;}
  5. }

JwtToken.cs

  1. public class JwtToken
  2. {
  3. public string access_token { set; get; }
  4. public string token_type { set; get; }
  5. }

>用于提取令牌的令牌控制器(这是不适合生产的示例),TokenController.cs:

  1. [ Route("[controller]") ]
  2. public class TokenController : Controller
  3. {
  4. private readonly OAuthBearerAuthenticationOptions _bearerOptions ;
  5. private readonly SigningCredentials _signingCredentials ;
  6.  
  7. public TokenController
  8. (
  9. IOptions<OAuthBearerAuthenticationOptions> bearerOptions,SigningCredentials signingCredentials
  10. )
  11. {
  12. _bearerOptions = bearerOptions.Options ;
  13. _signingCredentials = signingCredentials ;
  14. }
  15.  
  16. // POST: /token
  17. [HttpPost()]
  18. public JwtToken Token([FromBody] Credentials credentials)
  19. {
  20. // Pretend to validate credentials...
  21.  
  22. JwtSecurityTokenHandler handler =
  23. _bearerOptions .
  24. SecurityTokenValidators .
  25. OfType<JwtSecurityTokenHandler>() .
  26. First();
  27.  
  28. JwtSecurityToken securityToken =
  29. handler .
  30. CreateToken
  31. (
  32. issuer : _bearerOptions.TokenValidationParameters.ValidIssuer,audience : _bearerOptions.TokenValidationParameters.ValidAudience,signingCredentials : _signingCredentials,subject : new ClaimsIdentity
  33. (
  34. new Claim []
  35. {
  36. new Claim(ClaimTypes.Name,"somebody"),new Claim(ClaimTypes.Role,"admin" ),"teacher" ),}
  37. ),expires : DateTime.Today.AddDays(1)
  38. );
  39.  
  40. string token = handler.WriteToken(securityToken);
  41.  
  42. return new JwtToken()
  43. {
  44. access_token = token,token_type = "bearer"
  45. };
  46. }
  47. }

>一个值控制器来演示摄取令牌ValuesController.cs:

  1. [Route("api/[controller]")]
  2. public class ValuesController : Controller
  3. {
  4. // GET: api/values
  5. [Authorize("Bearer")]
  6. [HttpGet]
  7. public IEnumerable<string> Get()
  8. {
  9. return new string[] { "value1","value2" };
  10. }
  11.  
  12. // GET api/values/5
  13. [HttpGet("{id}")]
  14. public string Get(int id)
  15. {
  16. return "value";
  17. }
  18. }

>启动postman(或您最喜欢的REST客户端)的副本,在Visual Studio下启动示例应用程序,并使用与JSON主体类似的http:// localhost:22553 / token /

  1. {
  2. "user" : "user","password" : "secret"
  3. }

该应用程序使用令牌进行响应:

  1. {
  2. "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6bnVsbH0.eyJ1bmlxdWVfbmFtZSI6InNvbWVib2R5Iiwicm9sZSI6WyJhZG1pbiIsInRlYWNoZXIiXSwiaXNzIjoiY29udG9zby5jb20iLCJhdWQiOiJjb250b3NvLmNvbS9yZXNvdXJjZXMiLCJleHAiOjE0Mzk1MzU2MDB9.anRgL10XFG_bKDDxY3D2xQSfhPRLGMjUTreQNsP1jDA6eRKwXHf3jtpCwm_saoWyUDFFA2TMI9e_LbP6F5l7vtozCluziE_GQkPkspUSWuWIpQJLPRTTPPZHGKmPmK4MLEl1zPPrggJWbvF9RBw3mMQ0KoMfjSL0vUQ8kZ7VXAel8dnYJccd-CFdnB6aDe79x2E9Se2iLxdhr--R_qgvfz1Fa6tR1dstqLQ-UjYqPWY4SOgBjM3abtjfLLVEzeQMVyezX7Cx9ObMXAGbGvQL6GB_T5RlfAoXWME4jM8Bzhd-07wwd732bBws4OXivj1sSz-qawNTnXmnuccLRtI1uA","token_type": "bearer"
  3. }

>从先前的POST复制令牌,然后在邮递员中创建一个类似于http:// localhost:22553 / api / values的GET请求,注意添加一个授权头,其值为“bearer YOURTOKEN”(例如承载权限为yeetok .)
>请注意,该应用程序响应错误

System.InvalidOperationException
The following authentication scheme was not accepted: Bearer

堆栈跟踪如下:

  1. at Microsoft.AspNet.Http.Authentication.Internal.DefaultAuthenticationManager.< AuthenticateAsync> d__9.MoveNext()
  2. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  3. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  4. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  5. at Microsoft.AspNet.Http.Authentication.AuthenticationManager.< AuthenticateAsync> d__2.MoveNext()
  6. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  7. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  8. at System.Runtime.CompilerServices.TaskAwaiter< TResult> .GetResult()
  9. at Microsoft.AspNet.Mvc.AuthorizeFilter.< OnAuthorizationAsync> d__5.MoveNext()
  10. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  11. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  12. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  13. at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.< InvokeAuthorizationFilterAsync> d__43.MoveNext()
  14. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  15. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  16. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  17. at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.< InvokeAllAuthorizationFiltersAsync> d__42.MoveNext()
  18. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  19. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  20. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  21. at Microsoft.AspNet.Mvc.Core.FilterActionInvoker.< InvokeAsync> d__40.MoveNext()
  22. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  23. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  24. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  25. at Microsoft.AspNet.Mvc.MvcRouteHandler.< InvokeActionAsync> d__4.MoveNext()
  26. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  27. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  28. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  29. at Microsoft.AspNet.Mvc.MvcRouteHandler.< RouteAsync> d__3.MoveNext()
  30. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  31. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  32. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  33. at Microsoft.AspNet.Mvc.Routing.InnerAttributeRoute.< RouteAsync> d__10.MoveNext()
  34. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  35. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  36. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  37. at Microsoft.AspNet.Routing.RouteCollection.< RouteAsync> d__9.MoveNext()
  38. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  39. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  40. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  41. at Microsoft.AspNet.Builder.RouterMiddleware.< Invoke> d__4.MoveNext()
  42. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  43. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  44. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  45. at Microsoft.AspNet.Hosting.Internal.RequestServicesContainerMiddleware.< Invoke> d__3.MoveNext()
  46. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  47. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  48. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  49. at Microsoft.AspNet.Hosting.Internal.HostingEngine.< > c__DisplayClass29_0.< < Start> b__0> d.MoveNext()
  50. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  51. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  52. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  53. at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.< ProcessRequestAsyncImpl> d__10.MoveNext()
  54. --- exception rethrown ---
  55. at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.< ProcessRequestAsyncImpl> d__10.MoveNext()
  56. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  57. at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  58. at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
  59. at Microsoft.AspNet.Loader.IIS.HttpApplicationBase.< InvokeProcessRequestAsyncImpl> d__9.MoveNext()

请注意,添加日志记录几乎不会增加其他洞察力,因为以下日志显示

  1. 2015-08-13 13:32:35.969 -07:00 [Information] Request successfully matched the route with name 'null' and template '"api/Values"'.
  2. Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNet.Http.dll
  3. 2015-08-13 13:32:36.247 -07:00 [Error] An error occurred while handling the request.
  4. 2015-08-13 13:32:36.247 -07:00 System.InvalidOperationException: The following authentication scheme was not accepted: Bearer

我希望有人可能会了解这个例子发生的故障.

解决方法

您必须在MVC之前注册OAuth2承载认证中间件,否则您的用户在达到MVC时将被未认证:
  1. public class Startup {
  2. public void Configure(IApplicationBuilder app) {
  3. app.UseJwtBearerAuthentication(new JwtBearerOptions {
  4. // Your JWT bearer options.
  5. });
  6.  
  7. app.UseMvc();
  8. }
  9. }

猜你在找的asp.Net相关文章