如何在MVC 6 API vNext中实现Bearer Token?

问题描述 投票:1回答:2

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

我被困在Bearer令牌生成上。我需要为AngularJS app生成一个令牌,以便我可以调用和验证API。

asp.net-core asp.net-core-mvc bearer-token
2个回答
0
投票

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

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


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上的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

© www.soinside.com 2019 - 2024. All rights reserved.