简体   繁体   中英

Can't get the token in identity server3

I'm new in identity server3.

I can access to my token in other projects but i just can't get it in my identity project.

Here is my client class

new Client
{
    Enabled = true,
    ClientName = "Web Application1",
    ClientId = "WebApplication1",
    Flow = Flows.Implicit,
    RequireConsent = false,
    AllowRememberConsent = true,
    RedirectUris = new List<string>
    {
        "http://localhost:52249/"
    },
    PostLogoutRedirectUris = new List<string>
    {
        "http://localhost:52249/"
    },
    IdentityTokenLifetime = 360,
    AccessTokenLifetime = 3600,
    AllowedScopes = new List<string>() { "openid", "profile" , "roles", "WebAPI" }
},
new Client
{
    Enabled = true,
    ClientName = "Identity 2",
    ClientId = "Identity",
    Flow = Flows.Implicit,
    RequireConsent = false,
    AllowRememberConsent = true,
    RedirectUris = new List<string>
    {
        "https://localhost:44396/"
    },
    PostLogoutRedirectUris = new List<string>
    {
        "https://localhost:44396/"
    },
    IdentityTokenLifetime = 360,
    AccessTokenLifetime = 3600,
    AllowedScopes = new List<string>() { "openid", "profile" , "roles", "WebAPI" }
},

and my scopes class:

var scopes = new List<Scope>
{
    new Scope
    {
        Enabled = true,
        Name = "roles",
        Type = ScopeType.Identity,
        Claims = new List<ScopeClaim>
        {
            new ScopeClaim("role")
        }
    },
    new Scope
    {
        Enabled = true,
        DisplayName = "WebAPI",
        Name = "WebAPI",
        Description = "Secure WebAPI",
        Type = ScopeType.Resource,
        Claims = new List<ScopeClaim>
        {
            new ScopeClaim(Constants.ClaimTypes.Name),
            new ScopeClaim(Constants.ClaimTypes.Role),
        }
    }};

    scopes.AddRange(StandardScopes.All);
    return scopes;
}}

and user class:

IdentityContext db = new IdentityContext();
var AllUsers = db.Users.ToList();
List<InMemoryUser> UsersList = new List<InMemoryUser>();
foreach (var item in AllUsers)
{
    InMemoryUser UserInMemory = new InMemoryUser();
    UserInMemory.Username = item.UserName;
    UserInMemory.Password = item.Password;
    UserInMemory.Subject = item.Id.ToString();
    UserInMemory.Claims = new Claim[]
    {
        new Claim(Constants.ClaimTypes.PreferredUserName, item.UserName),
    };
}
return UsersList;

and my startup class in my identity project:

public void Configuration(IAppBuilder app)
{
    app.Map("/identity", idsrvApp =>
    {
        var factory =
            new IdentityServerServiceFactory().UseInMemoryClients(Clients.Get())
                                              .UseInMemoryScopes(Scopes.Get())
                                              .UseInMemoryUsers(Users.Get());

        var userService = new UserService();

        factory.UserService = new Registration<IUserService>(reslove => userService);
        var viewOptions = new DefaultViewServiceOptions();
        //viewOptions.Stylesheets.Add("/Content/Site.css");
        viewOptions.Stylesheets.Add("/Content/bootstrap-rtl.css");
        viewOptions.CacheViews = false;
        factory.ConfigureDefaultViewService(viewOptions);
        var options = new IdentityServerOptions
        {
            SiteName = "IdentityServer3 - Configuring DefaultViewService",

            SigningCertificate = LoadCertificate(),
            Factory = factory,

            AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
            {
                //   IdentityProviders = ConfigureAdditionalIdentityProviders,
            }
        };

        idsrvApp.UseIdentityServer(options);
    });

    Serilog.Log.Logger =
        new LoggerConfiguration().MinimumLevel.Debug()
            .WriteTo.RollingFile(pathFormat: @"c:\logs\IdSvrAdmin-{Date}.log")
            .CreateLogger();
    }

    X509Certificate2 LoadCertificate()
    {
        return new X509Certificate2(
            $"{AppDomain.CurrentDomain.BaseDirectory}\\bin\\idsrv3test.pfx", "idsrv3test");
    }

Please help me. Thanks.!

I think this helpful and you can get an idea to solve this problem.

public HttpRequestWrapper TokenizeRequest(User user, string clientid)
{
    var token = GetToken(user, clientid).Result;
    _request.AddHeader("Authorization", $"Bearer {token.AccessToken}");
    return this;
}

private async Task<TokenResponse> GetToken(User user, string clientid)
{
    var client = new TokenClient(Constants.TokenEndpoint, clientid, SecretApi);

    return  client.RequestResourceOwnerPasswordAsync
           (user.UserName, user.Password, "WebAPI").Result;
}

Reference : https://www.codeproject.com/Articles/1163131/IdentityServer-WebAPI-MVC-ASP-NET-Identity-Specflo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM