【问题标题】:How can I implement Bearer Token in MVC 6 API vNext?如何在 MVC 6 API vNext 中实现承载令牌?
【发布时间】:2015-05-20 03:49:13
【问题描述】:

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

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

【问题讨论】:

  • 只是好奇,为什么需要 Bearer 令牌,OWIN + Basic 身份验证还不够用?
  • 考虑到我必须根据角色授权控制器,将 MVC 6 Web API 用于 AngularJs 的最佳方法是什么?
  • 如果你的web api是从同一主机上的angularjs调用的,你可以使用OWIN cookie认证中间件。
  • 感谢您的回复。没有 API 将托管在不同的主机上。在那种情况下必须有一些东西可以使用..
  • 所以你的情况,使用 OWIN 是最简单的,它的工作方式类似于之前使用 cookie 的表单身份验证。但是,如果将来您必须支持本地客户端或移动应用程序,请在 owin cookie 身份验证之外使用基本身份验证。 Oauth2 会更复杂,我认为,我只需要 OAuth2 进行单点登录。

标签: asp.net-core asp.net-core-mvc bearer-token


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以像下面这样实现基于声明的身份验证;

    在 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;
                });
            }
    

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

    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 方法中使用身份验证

       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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2017-01-09
      • 2014-10-06
      • 2018-06-11
      • 2017-01-01
      • 1970-01-01
      相关资源
      最近更新 更多