使用不带身份的承载/ Jwt授权

Rai*_*ika 5 jwt asp.net-web-api asp.net-core

我想开发一个Aspnet.IdentityIdentity和阅读一些文件Identity意识到我需要的DBContext.
搜索后,我找不到任何使用授权的文件或样本Aspnet.Identity.我有自己的会员资格,我不想使用Identity
我应该使用Identity图书馆吗?或者有没有办法在我的会员资格中实施授权.

一个小方问题:
如果我被迫使用身份如何更改DBContext为类似Aspnet.IdentityIdentity对我Identity

Kév*_*let 0

要发行您自己的 JWT 令牌,您可以使用OpenIddict

项目.json

{
  "dependencies": {
    // ...
    "AspNet.Security.OAuth.Validation": "1.0.0-*",
    "OpenIddict": "1.0.0-*",
    "OpenIddict.EntityFrameworkCore": "1.0.0-*",
    "OpenIddict.Mvc": "1.0.0-*"
  }
}
Run Code Online (Sandbox Code Playgroud)

启动.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

授权控制器.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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

要求

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
Run Code Online (Sandbox Code Playgroud)

回复

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
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以阅读我写的有关 OpenIddict 的博客文章:http://kevinchalet.com/2017/01/30/implementing-simple-token-authentication-in-aspnet-core-with-openiddict/