Guest User

Untitled

a guest
Dec 16th, 2017
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.61 KB | None | 0 0
  1. // Configure the application for OAuth based flow
  2. PublicClientId = "self";
  3. OAuthOptions = new OAuthAuthorizationServerOptions
  4. {
  5. TokenEndpointPath = new PathString("/Token"),
  6. Provider = new ApplicationOAuthProvider(PublicClientId),
  7. AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
  8. };
  9.  
  10. public void Configure(IApplicationBuilder app)
  11. {
  12. app.UseOAuthBearerAuthentication(options =>
  13. {
  14. options.MetadataAddress = "meta";
  15. });
  16.  
  17. // if this isn't here, we just get a 404
  18. app.Run(async context =>
  19. {
  20. await context.Response.WriteAsync("Hello World.");
  21. });
  22. }
  23.  
  24. public void Configure(IApplicationBuilder app)
  25. {
  26. app.UseOAuthAuthentication("What is this?", options =>
  27. {
  28. options.TokenEndpoint = "/token";
  29. options.AuthorizationEndpoint = "/oauth";
  30. options.ClientId = "What is this?";
  31. options.ClientSecret = "What is this?";
  32. options.SignInScheme = "What is this?";
  33. options.AutomaticAuthentication = true;
  34. });
  35.  
  36. // if this isn't here, we just get a 404
  37. app.Run(async context =>
  38. {
  39. await context.Response.WriteAsync("Hello World.");
  40. });
  41. }
  42.  
  43. // Add a new middleware validating access tokens issued by the server.
  44. app.UseOAuthValidation();
  45.  
  46. // Add a new middleware issuing tokens.
  47. app.UseOpenIdConnectServer(options =>
  48. {
  49. options.TokenEndpointPath = "/connect/token";
  50.  
  51. // Create your own `OpenIdConnectServerProvider` and override
  52. // ValidateTokenRequest/HandleTokenRequest to support the resource
  53. // owner password flow exactly like you did with the OAuth2 middleware.
  54. options.Provider = new AuthorizationProvider();
  55. });
  56.  
  57. // Add a new middleware validating access tokens issued by the server.
  58. services.AddAuthentication()
  59. .AddOAuthValidation()
  60.  
  61. // Add a new middleware issuing tokens.
  62. .AddOpenIdConnectServer(options =>
  63. {
  64. options.TokenEndpointPath = "/connect/token";
  65.  
  66. // Create your own `OpenIdConnectServerProvider` and override
  67. // ValidateTokenRequest/HandleTokenRequest to support the resource
  68. // owner password flow exactly like you did with the OAuth2 middleware.
  69. options.Provider = new AuthorizationProvider();
  70. });
  71.  
  72. POST http://localhost:50000/connect/token HTTP/1.1
  73. User-Agent: Fiddler
  74. Host: localhost:50000
  75. Content-Length: 61
  76. Content-Type: application/x-www-form-urlencoded
  77.  
  78. grant_type=password&username=my_username&password=my_password
  79.  
  80. HTTP/1.1 200 OK
  81. Cache-Control: no-cache
  82. Pragma: no-cache
  83. Content-Length: 1687
  84. Content-Type: application/json;charset=UTF-8
  85. Expires: -1
  86. X-Powered-By: ASP.NET
  87. Date: Tue, 16 Jun 2015 01:24:42 GMT
  88.  
  89. {
  90. "access_token" : "eyJ0eXAiOi ... 5UVACg",
  91. "expires_in" : 3600,
  92. "token_type" : "bearer"
  93. }
  94.  
  95. ResourceOwnerPasswordFlow
  96. Providers
  97. AuthorizationProvider.cs
  98. project.json
  99. Startup.cs
  100.  
  101. public partial class Startup
  102. {
  103. public void ConfigureServices(IServiceCollection services)
  104. {
  105. services.AddAuthentication();
  106. }
  107. }
  108.  
  109. public partial class Startup
  110. {
  111. public void Configure(IApplicationBuilder app)
  112. {
  113. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
  114. JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
  115.  
  116. // Add a new middleware validating access tokens issued by the server.
  117. app.UseJwtBearerAuthentication(new JwtBearerOptions
  118. {
  119. AutomaticAuthenticate = true,
  120. AutomaticChallenge = true,
  121. Audience = "resource_server_1",
  122. Authority = "http://localhost:50000/",
  123. RequireHttpsMetadata = false
  124. });
  125.  
  126. // Add a new middleware issuing tokens.
  127. app.UseOpenIdConnectServer(options =>
  128. {
  129. // Disable the HTTPS requirement.
  130. options.AllowInsecureHttp = true;
  131.  
  132. // Enable the token endpoint.
  133. options.TokenEndpointPath = "/connect/token";
  134.  
  135. options.Provider = new AuthorizationProvider();
  136.  
  137. // Force the OpenID Connect server middleware to use JWT
  138. // instead of the default opaque/encrypted format.
  139. options.AccessTokenHandler = new JwtSecurityTokenHandler
  140. {
  141. InboundClaimTypeMap = new Dictionary<string, string>(),
  142. OutboundClaimTypeMap = new Dictionary<string, string>()
  143. };
  144.  
  145. // Register an ephemeral signing key, used to protect the JWT tokens.
  146. // On production, you'd likely prefer using a signing certificate.
  147. options.SigningCredentials.AddEphemeralKey();
  148. });
  149.  
  150. app.UseMvc();
  151.  
  152. app.Run(async context =>
  153. {
  154. await context.Response.WriteAsync("Hello World!");
  155. });
  156. }
  157. }
  158.  
  159. public sealed class AuthorizationProvider : OpenIdConnectServerProvider
  160. {
  161. public override Task ValidateTokenRequest(ValidateTokenRequestContext context)
  162. {
  163. // Reject the token requests that don't use
  164. // grant_type=password or grant_type=refresh_token.
  165. if (!context.Request.IsPasswordGrantType() &&
  166. !context.Request.IsRefreshTokenGrantType())
  167. {
  168. context.Reject(
  169. error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
  170. description: "Only grant_type=password and refresh_token " +
  171. "requests are accepted by this server.");
  172.  
  173. return Task.FromResult(0);
  174. }
  175.  
  176. // Since there's only one application and since it's a public client
  177. // (i.e a client that cannot keep its credentials private), call Skip()
  178. // to inform the server that the request should be accepted without
  179. // enforcing client authentication.
  180. context.Skip();
  181.  
  182. return Task.FromResult(0);
  183. }
  184.  
  185. public override Task HandleTokenRequest(HandleTokenRequestContext context)
  186. {
  187. // Only handle grant_type=password token requests and let the
  188. // OpenID Connect server middleware handle the other grant types.
  189. if (context.Request.IsPasswordGrantType())
  190. {
  191. // Validate the credentials here (e.g using ASP.NET Core Identity).
  192. // You can call Reject() with an error code/description to reject
  193. // the request and return a message to the caller.
  194.  
  195. var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
  196. identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique identifier]");
  197.  
  198. // By default, claims are not serialized in the access and identity tokens.
  199. // Use the overload taking a "destinations" parameter to make sure
  200. // your claims are correctly serialized in the appropriate tokens.
  201. identity.AddClaim("urn:customclaim", "value",
  202. OpenIdConnectConstants.Destinations.AccessToken,
  203. OpenIdConnectConstants.Destinations.IdentityToken);
  204.  
  205. var ticket = new AuthenticationTicket(
  206. new ClaimsPrincipal(identity),
  207. new AuthenticationProperties(),
  208. context.Options.AuthenticationScheme);
  209.  
  210. // Call SetResources with the list of resource servers
  211. // the access token should be issued for.
  212. ticket.SetResources("resource_server_1");
  213.  
  214. // Call SetScopes with the list of scopes you want to grant
  215. // (specify offline_access to issue a refresh token).
  216. ticket.SetScopes("profile", "offline_access");
  217.  
  218. context.Validate(ticket);
  219. }
  220.  
  221. return Task.FromResult(0);
  222. }
  223. }
  224.  
  225. {
  226. "dependencies": {
  227. "AspNet.Security.OpenIdConnect.Server": "1.0.0",
  228. "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0",
  229. "Microsoft.AspNetCore.Mvc": "1.0.0",
  230. }
  231.  
  232. // other code omitted
  233. }
Add Comment
Please, Sign In to add comment