Using Bearer / Jwt authorization without ID

I am developing a Web API with Asp 5 and, reading some documents about the Web API, I understand that I need bearer authorization.

After searching, I can not find any document or sample that use authorization without Aspnet.Identity . I have my own membership and I do not want to use Identity
Should I use the Identity library? or is there a way to implement authorization in my membership.

One small side question:
if I have to use Identity, how can I change EntityFramework to something like Dapper or ADO.NET for my DBContext ?

+5
asp.net-web-api asp.net-core jwt
source share
2 answers

To issue your own JWT tokens, you can use 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."); } } 

Request

 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 

response

 { "token_type": "Bearer", "access_token": "CfDJ8Ec0ZpniaHhGg0e0UUvOH9BWZSGrPoEwGd0_Lq2cse-T29YOq985IBiT5fEe5tTSgY1vxq2Z2ZJ7Ikwlpmh0Lrc4x9pqhqHBziUzsP_rkGZkn47TkNkOkzKCwZJZK5x-irH3HROwClFFTq0rgWdb8rZ2xriffNzsby4VwhxhN5soFD435KzmVYkdv-VuaLYo3QiSuexbRi2USVO9LK30vomAG6h2SAxZ7R-jYsXgf0f5gAmdYxg7w3yicv9v8DpUSBiGGRRfymTOnvGEsFJjGuuP8OlY5qzMs6wGaRWkOvCyV2CK_RZF_3TMs7LYCdMQ-dqWY5A03-03OmP8blKzlrKJMDZfrPQHuysbS931xxy8b3kjicfjNLmMHqzQzbUO4fecm4kY8PFnKozojDtqajfTp2bYhxS65bmVYROrswYeUWEKYR6LSdS1K__IDaLoMlLa-Wf6x1wjM2CchzgqbHRF0KEtdL5Ks88dAS44mp9BM6iUOEWyL7VkbazsBdlNciM5ZZB1_6qunufDW_tcaR8", "expires_in": 3600 } -irH3HROwClFFTq0rgWdb8rZ2xriffNzsby4VwhxhN5soFD435KzmVYkdv-VuaLYo3QiSuexbRi2USVO9LK30vomAG6h2SAxZ7R-jYsXgf0f5gAmdYxg7w3yicv9v8DpUSBiGGRRfymTOnvGEsFJjGuuP8OlY5qzMs6wGaRWkOvCyV2CK_RZF_3TMs7LYCdMQ-dqWY5A03-03OmP8blKzlrKJMDZfrPQHuysbS931xxy8b3kjicfjNLmMHqzQzbUO4fecm4kY8PFnKozojDtqajfTp2bYhxS65bmVYROrswYeUWEKYR6LSdS1K__IDaLoMlLa-Wf6x1wjM2CchzgqbHRF0KEtdL5Ks88dAS44mp9BM6iUOEWyL7VkbazsBdlNciM5ZZB1_6qunufDW_tcaR8", { "token_type": "Bearer", "access_token": "CfDJ8Ec0ZpniaHhGg0e0UUvOH9BWZSGrPoEwGd0_Lq2cse-T29YOq985IBiT5fEe5tTSgY1vxq2Z2ZJ7Ikwlpmh0Lrc4x9pqhqHBziUzsP_rkGZkn47TkNkOkzKCwZJZK5x-irH3HROwClFFTq0rgWdb8rZ2xriffNzsby4VwhxhN5soFD435KzmVYkdv-VuaLYo3QiSuexbRi2USVO9LK30vomAG6h2SAxZ7R-jYsXgf0f5gAmdYxg7w3yicv9v8DpUSBiGGRRfymTOnvGEsFJjGuuP8OlY5qzMs6wGaRWkOvCyV2CK_RZF_3TMs7LYCdMQ-dqWY5A03-03OmP8blKzlrKJMDZfrPQHuysbS931xxy8b3kjicfjNLmMHqzQzbUO4fecm4kY8PFnKozojDtqajfTp2bYhxS65bmVYROrswYeUWEKYR6LSdS1K__IDaLoMlLa-Wf6x1wjM2CchzgqbHRF0KEtdL5Ks88dAS44mp9BM6iUOEWyL7VkbazsBdlNciM5ZZB1_6qunufDW_tcaR8", "expires_in": 3600 } 

For more information, you can read this blog post that I wrote about OpenIddict: http://kevinchalet.com/2017/01/30/implementing-simple-token-authentication-in-aspnet-core-with-openiddict/

+1
source share

There is already JWT Bearer middleware , you just need to write something that issues media tokens. This is a bit more complicated, depending on what you use as the credential for credentials, and as you point out something non-standard, it's hard to recommend any approach. Creating JWT tokens is not that difficult;

 var now = DateTime.UtcNow; // Creates new keys automatically, you'd want to store these somewhere var aes = new AesCryptoServiceProvider(); var signingTokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity( new[] { new Claim(JwtRegisteredClaimNames.Aud, "YOURWEBSITEURL") }), TokenIssuerName = "YourWebSite", Lifetime = new Lifetime(now, now.AddHours(1)), SigningCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(aes.Key), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256") }; var token = signingTokenHandler.CreateToken(tokenDescriptor); var tokenAsString = signingTokenHandler.WriteToken(token); 

Not a single part of the authorization is dependent on membership in general; they will work with any middleware authentication. None of the authorization documents at all relate to Identity.

There an authorization workshop is available. You can see in the source that no one has an identity, he creates user principals on the fly and then saves them in cookies.

0
source share

All Articles