【问题标题】:How can I implement PersistedGrantStore on a mongodb database?如何在 mongodb 数据库上实现 PersistedGrantStore?
【发布时间】:2018-04-10 10:52:04
【问题描述】:

我正在尝试在 mongodb 上实现 PersistedGrantStore。我见过类似的问题和答案,但到目前为止还没有运气(How can I implement PersistedGrantStore on my mongodb database)。

我创建了一个继承自 IPersistedGrantStore 的类,我使用 AddTransient 将其注入 DI,但在我的类中仍然没有调用。这是我在 startup.cs 的 ConfigureServices(IServiceCollection services) 函数中的一段代码

services.AddAuthentication(o =>
        {
            o.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
            o.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
        }).AddIdentityServerAuthentication(options =>
        {
            options.SaveToken = true;
            options.Authority = authorityServerURL;// "https://demo.identityserver.io";                    
                                                   //options.ApiName = "BWalle_API";
                                                   //options.ApiSecret = "Odsdffegfgdfgdfglq_";
            options.RequireHttpsMetadata = false;
            options.EnableCaching = false;                
            options.SupportedTokens = SupportedTokens.Jwt;
        });

var builder = services.AddIdentityServer(options =>
        {              
            options.Endpoints.EnableUserInfoEndpoint = true;
            options.Events = new EventsOptions()
            {
                RaiseErrorEvents = true,
                RaiseFailureEvents = true,
                RaiseInformationEvents = true,
                RaiseSuccessEvents = true
            };
        })
            .AddTestUsers(Config.GetUsers())
            .AddSigningCredential(new Microsoft.IdentityModel.Tokens.SigningCredentials(GetSecurityKey(), SecurityAlgorithms.RsaSha512Signature))                 
            .AddResourceStore<ResourceStore>()
            .AddClientStore<ClientStore>()                
            .AddProfileService<MongoDbProfileService>()
            .AddResourceOwnerValidator<MongoDbResourceOwnerPasswordValidator>()
            .AddJwtBearerClientAuthentication();

builder.Services.AddTransient<IPersistedGrantStore, PersistedGrantStore>();

这是 ClientStore 类:

public class ClientStore : IClientStore
{
    Task<Client> IClientStore.FindClientByIdAsync(string clientId)
    {
        Client client = new Client
        {
            ClientId = "BWalle_API",
            ClientName = "BWalle API Client",
            //AllowAccessTokensViaBrowser = true,
            //AlwaysSendClientClaims = true,                
            AllowedGrantTypes = new List<string>() {
                        GrantType.ResourceOwnerPassword,
                        GrantType.Hybrid,
                        GrantType.ClientCredentials                            
                    },
            ClientSecrets = new List<Secret>
                    {
                        new Secret("Odsdffegfgdfgdfglq_".Sha512())
                    },

            AllowedScopes = new List<string>
                    {
                        IdentityServer4.IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServer4.IdentityServerConstants.StandardScopes.Profile,
                        IdentityServer4.IdentityServerConstants.StandardScopes.Email,
                        IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
                        IdentityServer4.IdentityServerConstants.StandardScopes.Phone,
                        "BWalle_API"
                    },
            Enabled = true,
            //AllowedCorsOrigins = new List<string>
            //{
            //    "http://localhost:4200"
            //},                
            AllowOfflineAccess = true,
            AllowRememberConsent = false,                
            AccessTokenType = AccessTokenType.Jwt,
            IdentityTokenLifetime = 3600 * 24, // Lifetime to identity token in seconds (defaults to 300 seconds / 5 minutes)
            AccessTokenLifetime = 3600 * 24, //3600, // Lifetime of access token in seconds (defaults to 3600 seconds / 1 hour)
            AuthorizationCodeLifetime = 3600 * 24, // Lifetime of authorization code in seconds (defaults to 300 seconds / 5 minutes)
            RefreshTokenUsage = TokenUsage.ReUse,
            RefreshTokenExpiration = TokenExpiration.Sliding,
            UpdateAccessTokenClaimsOnRefresh = true,
            IncludeJwtId = true
        };

        return Task.FromResult<Client>(client);
    }
}

这是 PersistedGrantStore 类:

public class PersistedGrantStore : IPersistedGrantStore
{
    private readonly IAppRepository appRepository;

    public PersistedGrantStore(IAppRepository DBAppRepository)
    {
        this.appRepository = DBAppRepository;
    }


    public Task<IEnumerable<PersistedGrant>> GetAllAsync(string subjectId)
    {
        throw new NotImplementedException();
    }

    public Task<PersistedGrant> GetAsync(string key)
    {
        throw new NotImplementedException();            

    }

    public Task RemoveAllAsync(string subjectId, string clientId)
    {
        throw new NotImplementedException();            
    }

    public Task RemoveAllAsync(string subjectId, string clientId, string type)
    {
        throw new NotImplementedException();            
    }

    public Task RemoveAsync(string key)
    {
        throw new NotImplementedException();            
    }

    public Task StoreAsync(PersistedGrant grant)
    {
        throw new NotImplementedException();            
    }
}

我正在使用那些 nuget 包:

身份服务器4\2.1.3,

Identityserver4.AccessTokenValidation\2.5.0

Contrib.Microsoft.aspnetcore.identity.mongodb\2.0.5

我已经成功地使用 mongodb 来存储用户和客户端,现在我正在尝试存储授权而不是在内存授权存储中使用,但是在 PersistedGrantStore 类中没有调用。

我使用 ResourceOwner 作为 GrantType (JWT - Bearer Model)。

我看不到我缺少什么,任何帮助都会非常有帮助!!!

【问题讨论】:

    标签: c# mongodb asp.net-web-api2 identityserver4


    【解决方案1】:

    解决了!!!!缺少的是在从客户端向服务器发送对端点“/connect/token”的连接请求时将“offline_access”添加到范围内。

    正文中包含数据的帖子“/connect/token”示例:

    client_id=BWalle_API&client_secret=mysecretAPlq_&grant_type=password&scope=BWalle_API offline_access&username=undefined&password=undefined&rememberme=&VerCode=1820-0327-2104-0012

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 2021-05-07
      相关资源
      最近更新 更多