具有JWT访问令牌的安全API

时间:2018-09-21 10:45:31

标签: asp.net-core openid-connect openiddict

我正在处理openiddict授权代码流示例,并且一切正常。

https://github.com/openiddict/openiddict-samples/tree/dev/samples/CodeFlow

但是,我想进行某些更改,而我正为此而努力。我想配置为使用JWT令牌而不是默认的不透明令牌,并且还分为授权服务器和资源服务器。我也有一个MCV Web应用程序,它将通过httpClient与资源服务器进行通信。

Auth Server.Startup

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
                options.UseOpenIddict();
            });

            // Register the Identity services.
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            });

            services.AddOpenIddict()

                .AddCore(options =>

                    options.UseEntityFrameworkCore()
                           .UseDbContext<ApplicationDbContext>();
                })

                // Register the OpenIddict server handler.
                .AddServer(options =>
                {
                    options.UseMvc();

                    options.EnableAuthorizationEndpoint("/connect/authorize")
                           .EnableLogoutEndpoint("/connect/logout")
                           .EnableTokenEndpoint("/connect/token")
                           .EnableUserinfoEndpoint("/api/userinfo");

                    options.RegisterScopes(OpenIdConnectConstants.Scopes.Email,
                                           OpenIdConnectConstants.Scopes.Profile,
                                           OpenIddictConstants.Scopes.Roles);


                    options.AllowAuthorizationCodeFlow();
                    options.EnableRequestCaching();
                    options.DisableHttpsRequirement();
                    options.UseJsonWebTokens();
                    options.AddEphemeralSigningKey();
                });
        }

由于这不再是资源服务器,因此我删除了验证部分,因为我认为这不是必需的。当我想使用JWT时,我没有注释以下行:

options.UseJsonWebTokens();
options.AddEphemeralSigningKey();

授权端点返回与示例完全相同的SignIn结果,该结果将重定向到MVC应用,该应用随后发出身份验证cookie。我现在可以在MVC APP上访问受保护的资源。

MVC APP启动

  public void ConfigureServices(IServiceCollection services)
        {

            services.Configure<PortalDetails>(options => Configuration.GetSection("PortalDetails").Bind(options));

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(opts =>
            {
                opts.LoginPath = "/login";
                opts.LogoutPath = "/logout";
            })

            .AddJwtBearer(options =>
            {
                //Authority must be a url. It does not have a default value.
                options.Authority = "http://localhost:54540/";
                options.Audience = "mvc"; //This must be included in ticket creation
                options.RequireHttpsMetadata = false;
                options.IncludeErrorDetails = true; //
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType = "sub",
                    RoleClaimType = "role"
                };
            })

            .AddOpenIdConnect(options =>
            {
                // Note: these settings must match the application details
                // inserted in the database at the server level.
                options.ClientId = "mvc";
                options.ClientSecret = "901564A5-E7FE-42CB-B10D-61EF6A8F3654";

                options.RequireHttpsMetadata = false;
                options.GetClaimsFromUserInfoEndpoint = false; // TODO: If this if true then it doesnt work??
                options.SaveTokens = true;

                // Use the authorization code flow.
                options.ResponseType = OpenIdConnectResponseType.Code;
                options.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet;

                // Note: setting the Authority allows the OIDC client middleware to automatically
                // retrieve the identity provider's configuration and spare you from setting
                // the different endpoints URIs or the token validation parameters explicitly.
                options.Authority = "http://localhost:54540/";

                options.Scope.Add("email");
                options.Scope.Add("roles");

                options.SecurityTokenValidator = new JwtSecurityTokenHandler
                {
                    // Disable the built-in JWT claims mapping feature.,
                    InboundClaimTypeMap = new Dictionary<string, string>()
                };

                options.TokenValidationParameters.NameClaimType = "name";
                options.TokenValidationParameters.RoleClaimType = "role";
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddHttpClient<IApiGatewayClient, ApiGatewayClient>();
            services.AddSingleton<ITokenProvider, TokenProvider>();
        }

在调用资源服务器时,我使用:

string accessToken = await HttpContext.GetTokenAsync("access_token");

我可以看到一个访问令牌,我将其附加到我的http请求中:

_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“ Bearer”,令牌);

但结果被禁止。

最后,我有一个受保护的资源服务器:

Resource.Startup

  public void ConfigureServices(IServiceCollection services)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            //Add authentication and set default authentication scheme
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //same as "Bearer"
                .AddJwtBearer(options =>
                {
                    //Authority must be a url. It does not have a default value.
                    options.Authority = "http://localhost:54540";
                    options.Audience = "mvc"; //This must be included in ticket creation
                    options.RequireHttpsMetadata = false;
                    options.IncludeErrorDetails = true; //
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        NameClaimType = OpenIdConnectConstants.Claims.Subject,
                        RoleClaimType = OpenIdConnectConstants.Claims.Role,
                    };
                });

            services.AddMvc();
        }

我想知道这是否是我的方案的正确设置,因为我从资源服务器中获得了禁止的结果。

谢谢

1 个答案:

答案 0 :(得分:1)

这里是一个包

  • 轻松将JWT Bearer令牌安全性集成到您的Asp Net Core 2.0+应用中!
  • Azure Active Directory身份验证集成。
  • Facebook身份验证集成。
  • Twitter身份验证集成。
  • Google身份验证集成。
  • 此外,Swagger UI集成!

它称为 AspNetCore.Security.Jwt

GitHub:

https://github.com/VeritasSoftware/AspNetCore.Security.Jwt

该软件包将JWT承载令牌集成到您的应用程序中,如下所示:

1。在您的应用中实现IAuthentication界面

using AspNetCore.Security.Jwt;
using System.Threading.Tasks;

namespace XXX.API
{
    public class Authenticator : IAuthentication
    {        
        public async Task<bool> IsValidUser(string id, string password)
        {
            //Put your id authenication here.
            return true;
        }
    }
}

2。在您的Startup.cs

using AspNetCore.Security.Jwt;
using Swashbuckle.AspNetCore.Swagger;
.
.
public void ConfigureServices(IServiceCollection services)
{
    .
    .
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "XXX API", Version = "v1" });
    });

    services.AddSecurity<Authenticator>(this.Configuration, true);
    services.AddMvc().AddSecurity();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    .
    .
    .
    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "XXX API V1");
    });

    app.UseSecurity(true);

    app.UseMvc();
}

3。在您的appsettings.json

注意:-您可以使用“管理用户秘密”菜单(右键单击您的项目)将这些设置放入Secret Manager。

 {
     "SecuritySettings": {
        "Secret": "a secret that needs to be at least 16 characters long",
        "Issuer": "your app",
        "Audience": "the client of your app",
        "IdType":  "Name",
        "TokenExpiryInHours" :  2
    },
    .
    .
    .
}

然后您将自动获得端点:

  

/令牌

     

/ facebook

调用这些端点并成功进行身份验证后,您将获得JWT承载令牌。

在您要保护的控制器中

您必须使用Authorize属性将要保护的Controller或Action标记为:

    using Microsoft.AspNetCore.Mvc;
    .
    .
    .

    namespace XXX.API.Controllers
    {
        using Microsoft.AspNetCore.Authorization;

        [Authorize]
        [Route("api/[controller]")]
        public class XXXController : Controller
        {
            .
            .
            .
        }
    }

在Swagger用户界面中,您将自动看到这些端点。

Authentication endpoints