首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IdentityServer4 API密钥支持

IdentityServer4 API密钥支持
EN

Stack Overflow用户
提问于 2017-03-02 00:18:58
回答 1查看 8.4K关注 0票数 4

我在Visual中有3个项目。

  1. 身份服务器
  2. API站点
  3. 角2前端

我使用IdentityServer4和ASP.NET核心标识和实体框架。到目前为止一切都很顺利。

现在,我想增加用户生成API密钥的能力,这样用户就可以通过他们的服务器调用我们的API服务器,只需传递API密钥。然后(以某种方式)对用户进行身份验证,并生成我的API用于授权的访问令牌。IdentityServer4是否支持为每个用户生成API密钥?我知道有一些客户端的秘密,我已经实现了,但这只能识别客户端。我也需要了解用户,所以我知道用户被授权做什么(现在就使用角色)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-02 21:26:41

IdentityServer是一个框架和一个可驻留的组件,它允许使用OpenID连接和OAuth2等协议为现代web应用程序和API实现单点登录和访问控制。它支持广泛的客户端,如移动、web、SPAs和桌面应用程序,并且是可扩展的,可以在新的和现有的体系结构中进行集成。在你的创业课上:

代码语言:javascript
复制
     public void ConfigureServices(IServiceCollection services)
                {
                    var source = System.IO.File.ReadAllText("MyCertificate.b64cert");
                    var certBytes = Convert.FromBase64String(source);
                    var certificate = new X509Certificate2(certBytes, "password");

                    var builder = services.AddIdentityServer(options =>
                    {
                        options.SigningCertificate = certificate;
                        options.RequireSsl = false; // should be true
                    });
             JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        app.UseIdentityServerAuthentication(options =>
        {
            options.Authority = "http://localhost:5000";
            options.ScopeName = "openid";
            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;
        });
                    builder.AddInMemoryClients(Clients.Get());
                    builder.AddInMemoryScopes(Scopes.Get());
                    builder.AddInMemoryUsers(Users.Get());
                }

            public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
                    {
                        loggerFactory.AddConsole(LogLevel.Verbose);
                        loggerFactory.AddDebug(LogLevel.Verbose);
                        app.UseIdentityServer();
                    }

创建客户端类

代码语言:javascript
复制
public class Clients
{
    public static IEnumerable<Client> Get()
    {
        return new[]
        {
            new Client
            {
                ClientId = "myapi",
                ClientSecrets = new List<Secret>
                {
                    new Secret("secret".Sha256())
                },
                ClientName = "your api",
                Flow = Flows.ResourceOwner,
                AllowedScopes =
                {
                    Constants.StandardScopes.OpenId,
                    "read"
                },
                Enabled = true
            }
        };
    }
}

范围

代码语言:javascript
复制
public class Scopes
{
    public static IEnumerable<Scope> Get()
    {
        return new[]
        {
            StandardScopes.OpenId,
            StandardScopes.Profile,
            StandardScopes.OfflineAccess,
            new Scope {Name = "advanced", DisplayName = "Advanced Options"}
        };
    }
}

控制器

代码语言:javascript
复制
[Route("api/[controller]")]
public class SomeController : Controller
{
    [HttpGet]
    [Authorize]
    public IEnumerable<string> Get()
    {
        return new[] { "value1", "value2" };
    }

    [HttpGet("{id}")]
    [Authorize]
    public string Get(int id)
    {
        return "value";
    }
}

一旦安装完毕,您就可以发出JWT身份验证令牌,然后用户可以在其授权头中使用该令牌

创建生成类

代码语言:javascript
复制
private async Task GenerateToken(HttpContext context)
{
    var username = context.Request.Form["username"];
    var password = context.Request.Form["password"];

    var identity = await GetIdentity(username, password);
    if (identity == null)
    {
        context.Response.StatusCode = 400;
        await context.Response.WriteAsync("Invalid username or password.");
        return;
    }

    var now = DateTime.UtcNow;

    // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
    // You can add other claims here, if you want:
    var claims = new Claim[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, username),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
    };

    // Create the JWT and write it to a string
    var jwt = new JwtSecurityToken(
        issuer: _options.Issuer,
        audience: _options.Audience,
        claims: claims,
        notBefore: now,
        expires: now.Add(_options.Expiration),
        signingCredentials: _options.SigningCredentials);
    var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

    var response = new
    {
        access_token = encodedJwt,
        expires_in = (int)_options.Expiration.TotalSeconds
    };

    // Serialize and return the response
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }));
}

创建您的中间件:

代码语言:javascript
复制
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace SimpleTokenProvider
{
    public class TokenProviderMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly TokenProviderOptions _options;

        public TokenProviderMiddleware(
            RequestDelegate next,
            IOptions<TokenProviderOptions> options)
        {
            _next = next;
            _options = options.Value;
        }

        public Task Invoke(HttpContext context)
        {
            // If the request path doesn't match, skip
            if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
            {
                return _next(context);
            }

            // Request must be POST with Content-Type: application/x-www-form-urlencoded
            if (!context.Request.Method.Equals("POST")
               || !context.Request.HasFormContentType)
            {
                context.Response.StatusCode = 400;
                return context.Response.WriteAsync("Bad request.");
            }

            return GenerateToken(context);
        }
    }
}

最后,将中间件连接起来,以生成startup.cs中的令牌

代码语言:javascript
复制
app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42544654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档