コード例 #1
0
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            // 路由配置
            context.Services.AddRouting(options =>
            {
                // 设置URL为小写
                options.LowercaseUrls = true;
                // 在生成的URL后面添加斜杠
                options.AppendTrailingSlash = true;
            });

            // 认证
            context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ClockSkew                = TimeSpan.FromSeconds(30),
                    ValidateIssuerSigningKey = true,
                    ValidAudience            = AppSettings.JWT.Domain,
                    ValidIssuer              = AppSettings.JWT.Domain,
                    IssuerSigningKey         = new SymmetricSecurityKey(AppSettings.JWT.SecurityKey.GetBytes())
                };
                options.Events = new JwtBearerEvents
                {
                    OnChallenge = async context =>
                    {
                        // 跳过默认的处理逻辑,返回下面的模型数据
                        context.HandleResponse();

                        context.Response.ContentType = "application/json;charset=utf-8";
                        context.Response.StatusCode  = StatusCodes.Status200OK;

                        var result = new ServiceResult();
                        result.IsFailed("UnAuthorized");

                        await context.Response.WriteAsync(result.ToJson());
                    }
                };
            });

            // 授权
            context.Services.AddAuthorization();

            // Http请求
            context.Services.AddHttpClient();

            Configure <MvcOptions>(options =>
            {
                var filterMetadata = options.Filters.FirstOrDefault(x => x is ServiceFilterAttribute attribute && attribute.ServiceType.Equals(typeof(AbpExceptionFilter)));

                // 移除 AbpExceptionFilter
                options.Filters.Remove(filterMetadata);
                // 添加自己实现的 BlogExceptionFilter
                options.Filters.Add(typeof(BlogExceptionFilter));
            });
        }
コード例 #2
0
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            Configure <AbpLocalizationOptions>(options =>
            {
                options.Resources
                .Get <LearnResource>()
                .AddBaseTypes(typeof(AbpUiResource));
            });
            var configuration = context.Services.GetConfiguration();

            context.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;

                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidAudience            = configuration.GetValue <string>("JwtAuth:Audience"),
                    ValidIssuer      = configuration.GetValue <string>("JwtAuth:Issuer"),
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration.GetValue <string>("JwtAuth:SecurityKey")))
                };
                options.Events = new JwtBearerEvents
                {
                    OnChallenge = context =>
                    {
                        //此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦,必须
                        context.HandleResponse();
                        var payload = "{\"ret\":401,\"err\":\"无登录信息或登录信息已失效,请重新登录。\"}";
                        //自定义返回的数据类型
                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode  = StatusCodes.Status200OK;
                        context.Response.WriteAsync(payload);
                        return(Task.FromResult(0));
                    }
                };
            });
        }
コード例 #3
0
        private void ConfigureAuthentication(ServiceConfigurationContext context)
        {
            context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ClockSkew                = TimeSpan.FromSeconds(AppSettings.JWT.ClockSkew),
                    ValidateIssuerSigningKey = true,
                    ValidAudience            = AppSettings.JWT.ValidAudience,
                    ValidIssuer              = AppSettings.JWT.ValidIssuer,
                    IssuerSigningKey         = new SymmetricSecurityKey(AppSettings.JWT.IssuerSigningKey.GetBytes())
                };

                options.Events = new JwtBearerEvents
                {
                    OnChallenge = async context =>
                    {
                        context.HandleResponse();

                        context.Response.ContentType = "application/json;charset=utf-8";
                        context.Response.StatusCode  = StatusCodes.Status401Unauthorized;

                        var result = new ServiceResult();
                        result.IsFailed(nameof(HttpStatusCode.Unauthorized));

                        await context.Response.WriteAsync(result.ToJson());
                    },
                    OnMessageReceived = async context =>
                    {
                        context.Token = context.Request.Query["token"];

                        await Task.CompletedTask;
                    }
                };
            });

            context.Services.AddAuthorization();
        }
コード例 #4
0
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            //base.ConfigureServices(context);

            Configure <MvcOptions>(options =>
            {
                var filterMetadata = options.Filters.FirstOrDefault(x => x is ServiceFilterAttribute attribute && attribute.ServiceType.Equals(typeof(AbpExceptionFilter)));

                // 移除 AbpExceptionFilter
                options.Filters.Remove(filterMetadata);

                // 添加自己实现的 JontyBlogExceptionFilter
                options.Filters.Add(typeof(JontyBlogExceptionFilter));
            });

            // 身份验证
            context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // 验证颁发者
                    ValidateIssuer = true,
                    // 验证访问群体
                    ValidateAudience = true,
                    // 验证生存期
                    ValidateLifetime = true,
                    // 验证Token时间偏移量
                    ClockSkew = TimeSpan.FromSeconds(30),
                    // 验证安全密匙
                    ValidateIssuerSigningKey = true,
                    // 访问群体
                    ValidAudience = AppSettings.JWT.Domain,
                    // 颁发者
                    ValidIssuer = AppSettings.JWT.Domain,
                    // 安全密匙
                    IssuerSigningKey = new SymmetricSecurityKey(AppSettings.JWT.SecurityKey.GetBytes())
                };

                //应用程序提供的对象,用于处理承载引发的事件,身份验证处理程序
                options.Events = new JwtBearerEvents
                {
                    OnChallenge = async context =>
                    {
                        // 跳过默认的处理逻辑,返回下面的模型数据
                        context.HandleResponse();

                        context.Response.ContentType = "application/json;charset=utf-8";
                        context.Response.StatusCode  = StatusCodes.Status200OK;

                        var result = new ServiceResult();
                        result.IsFailed("UnAuthorized");

                        await context.Response.WriteAsync(result.ToJson());
                    }
                };
            });

            // 认证授权
            context.Services.AddAuthentication();
            // Http请求
            context.Services.AddHttpClient();

            //异常处理
            Configure <MvcOptions>(options =>
            {
                var filterMetadata = options.Filters.FirstOrDefault(x => x is ServiceFilterAttribute attribute && attribute.ServiceType.Equals(typeof(AbpExceptionFilter)));

                // 移除 AbpExceptionFilter
                options.Filters.Remove(filterMetadata);

                // 添加JontyExceptionFilter
                options.Filters.Add(typeof(JontyBlogExceptionFilter));
            });

            //测试定时任务
            //context.Services.AddTransient<IHostedService, HelloWorldJob>();

            //路由规则配置
            context.Services.AddRouting(options =>
            {
                // 设置URL小写
                options.LowercaseUrls = true;
                // 在生成的URL后面添加斜杠
                options.AppendTrailingSlash = true;
            });
        }
コード例 #5
0
        /// <summary>
        /// 认证
        /// </summary>
        /// <param name="context"></param>
        /// <param name="configuration"></param>
        private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.Configure <JwtSetting>(configuration.GetSection("JwtSetting"));
            JwtSetting setting = configuration.GetSection("JwtSetting").Get <JwtSetting>();

            context.Services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.SaveToken                 = true;
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    //注意这是缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间,如果不配置,默认是5分钟
                    ClockSkew        = TimeSpan.FromMinutes(setting.ClockSkew),
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(setting.Secret)),
                    ValidIssuer      = setting.Issuer,
                    ValidAudience    = setting.AccessAudience,
                };
                // 应用程序提供的对象,用于处理承载引发的事件,身份验证处理程序
                options.Events = new JwtBearerEvents
                {
                    OnChallenge = async context =>
                    {
                        //token 验证失败
                        // 跳过默认的处理逻辑,返回下面的模型数据
                        context.HandleResponse();
                        context.Response.ContentType = "application/json;charset=utf-8";
                        context.Response.StatusCode  = StatusCodes.Status200OK;
                        var result = new Result <string>();

                        if (context.AuthenticateFailure?.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            //token过期
                            context.Response.Headers.Add("Token-Expired", "true");
                            result.Code    = ResultCode.TokenExpired;
                            result.Message = ResultCode.TokenExpired.ToString();
                        }
                        else
                        {
                            result.Code    = ResultCode.UnAuthorized;
                            result.Message = ResultCode.UnAuthorized.ToString();
                        }

                        await context.Response.WriteAsync(result.ToJson());
                    },
                    OnForbidden = async context =>
                    {
                        context.Response.ContentType = "application/json;charset=utf-8";
                        context.Response.StatusCode  = StatusCodes.Status200OK;
                        //权限不足,访问被拒绝
                        var result = new Result <string>
                        {
                            Code    = ResultCode.Forbidden,
                            Message = ResultCode.Forbidden.ToString()
                        };
                        await context.Response.WriteAsync(result.ToJson());
                    }
                };
            });
        }