1

我正在开发一个示例 SPA 应用程序以使用 ASP.NET 5。我正在使用 Visual Studio Community 2015 RC。

我被困在不记名令牌生成上。我需要为 AngularJS 应用程序生成一个令牌,以便我可以调用和验证 API。

4

2 回答 2

0

看看这个类似的问题Token Based Authentication in ASP.NET Core

Matt DeKrey的回答可能会解决您的问题。

于 2015-05-20T20:56:07.987 回答
0

您可以实现基于声明的身份验证,如下所示;

在 Startup.cs 中添加方法

     public void ConfigureAuthentication(IServiceCollection services)
        {
            var key = Encoding.ASCII.GetBytes("very-secret-much-complex-secret");
            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                // Validate the JWT issuer (Iss) claim
                ValidateIssuer = false,
                //ValidIssuers = validIssuerList,

                // Validate the JWT audience (Aud) claim
                ValidateAudience = false,
                //ValidAudiences = validAudienceList,

                // Validate token expiration
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            })
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
            });
        }

ConfigureServices并在方法 on中调用此方法Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            //DI Injections
            services.AddScoped<IAuthService, AuthService>();
            services.AddScoped<IAudienceService, AudienceService>();


            ConfigureAuthentication(services);
            services.AddMvc(
               options =>
               {
                   var policy = new AuthorizationPolicyBuilder()
                                       .RequireAuthenticatedUser()
                                       .Build();
                   options.Filters.Add(new AuthorizeFilter(policy));
               });
        }

Configure然后,在方法中使用UseAuthentication

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }


            app.UseAuthentication();

            app.UseHttpsRedirection();
            app.UseMvc();
        }

上面我们将 API 配置为使用 JWT 身份验证作为授权层。让我们看看我们如何在下面生成一个有效的令牌;

  public async Task<string> Authenticate(string apiKey, string sharedSecret)
        {
            //get audience by apikey and password from database
            //create token from createdobject 
            var audience = await audienceService.GetByCredentials(apiKey, sharedSecret);
            // return null if auudience not found
            if (audience == null)
                return null;

            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("very-secret-much-complex-secret");
            var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);

            //arange claims from permissions
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, audience.Name),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };
            claims.AddRange(audience.Permissions.Where(p => p.Value).Select(p => new Claim(ClaimsIdentity.DefaultRoleClaimType, p.Key.GetHashCode().ToString())));

            var token = new JwtSecurityToken(
                audience.Name,
                audience.Name,
                claims,
                expires: DateTime.UtcNow.AddDays(7),
                signingCredentials: signingCredentials
                );
            return new JwtSecurityTokenHandler().WriteToken(token);

        }

您可以在我的 GitHub 存储库中找到整个项目:https ://github.com/ilkerkaran/simple-claim-based-auth

于 2019-06-26T11:25:17.950 回答