close

之前實做到Net Core

覺得這篇寫得很詳細了   .Net Core 使用JWT权限验证 

 

LoginController.cs

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MODEL.MCommon;
using System;
using NWEAPI.HelperTool;
using IServices.IEST;

namespace API.Controllers.TEST
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {

        public ILoginService _loginService;
        public IConfiguration _configuration;
        public LoginController(ILoginService login, IConfiguration configuration)
        {
            _loginService = login;
            _configuration = configuration;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Login"></param>
        /// <returns></returns>
        [HttpPost]
        [EnableCors("any")]
        public ReturnMessageModel onLogin([FromBody] JObject Login)//UserID, Password
        {
            ReturnMessageModel returnmessagemodel = new ReturnMessageModel();
            try
            {
                var issuer = _configuration["Jwt:Issuer"];
                var audience = _configuration["Jwt:Audience"];
                var signKey = _configuration["Jwt:SignKey"]; // 請換成至少 16 字元以上的安全亂碼
                var expires = Convert.ToInt32(_configuration["Jwt:Expires"]); // 單位: 分鐘
                var tokn = JwtHelpers.GenerateToken(issuer, audience, signKey, Login, expires);
                returnmessagemodel = _loginService.onLogin(Login);
                returnmessagemodel.Tokn = tokn;
                return returnmessagemodel;
            }
            catch (Exception ex)
            {
                returnmessagemodel.Status = "1";
                returnmessagemodel.Message = "異常";
                return returnmessagemodel;
            }
        }

    }
}

 

Startup.cs

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using NWEAPI.HelperTool;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace API
{
    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        private string OAuth = "";//是否需啟用OAuth2.0驗證
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            OAuth = Configuration["OAuth"];
        }
        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //JSON大小寫
            services.AddMvc().AddJsonOptions(
                op => op.SerializerSettings.ContractResolver =
                new Newtonsoft.Json.Serialization.DefaultContractResolver());
            
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddCors(options =>

            {

                options.AddPolicy("any", builder =>

                {

                    builder.AllowAnyOrigin() //允许任何来源的主机访问

                    .AllowAnyMethod()

                    .AllowAnyHeader()

                    .AllowCredentials();//指定处理cookie

                });

            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",
                    new Info
                    {
                        Version = "v1",
                        Title = "Api",
                        Description = "ASP.NET Core Web API",
                    });
                

                var basePath = AppContext.BaseDirectory;
                var xmlPath = Path.Combine(basePath, "API.xml");
                c.IncludeXmlComments(xmlPath, true);
                //#region Token绑定到ConfigureServices
                ////添加Header验证信息
                var security = new Dictionary<string, IEnumerable<string>> { { "API", new string[] { } }, };
                c.AddSecurityRequirement(security);
                //方案名称“HRSystemMicroApi”可自定义,上下一致即可
                c.AddSecurityDefinition("MesAPI", new ApiKeyScheme
                {
                    Description = "直接在下框中输入token",
                    Name = "Authorization",
                    In = "Header",//存放token位置
                    Type = "apiKey"
                });
                //#endregion
            });

            //// #region Token服务注册
            //JWT
            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {

                    // 一般我們都會驗證 Issuer
                    ValidateIssuer = true,
                    // 若是單一伺服器通常不太需要驗證 Audience
                    ValidateAudience = true,
                    // 一般我們都會驗證 Token 的有效期間
                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.FromMinutes(Convert.ToInt32(Configuration["Jwt:Expires"])),
                    // 如果 Token 中包含 key 才需要驗證,一般都只有簽章而已
                    ValidateIssuerSigningKey = true,
                    ValidAudience = Configuration["Jwt:Audience"],
                    ValidIssuer = Configuration["Jwt:Issuer"], // 從 IConfiguration 取得
                    //應該從 IConfiguration 取得
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:signKey"]))

                };
            });
            //IP使用
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //使用Autofac實現IOC
            var containerBuilder = new ContainerBuilder();
            //模塊化注入
            containerBuilder.RegisterModule<HelperTool.AutofacModuleRegister>();
            containerBuilder.Populate(services);
            var container = containerBuilder.Build();
            return new AutofacServiceProvider(container);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            //允许跨域设置
            //app.UseCors("AllRequests");

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");

            });

            app.Use(async (context, next) =>
            {
                context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
                await next();
            });
            //啟用OAuth
            if (OAuth == "Yes")
            {

                app.UseMiddleware<OAuth.TokenAuth>();
            }
            app.UseMvc();
        }
    }
}


 

appSetting.json

"Jwt": {
    "Issuer": "EPIApi",
    "SignKey": "20LKDoCFUguvJf6ktmwTcA==",
    "Audience": "NWEAPI",
    "Expires": "60"
  }

之後其他方法添加[Authorize] 即可

/// <summary>
/// 
/// </summary>
/// <returns></returns>
[HttpGet]
[Authorize]
public string exmple()
{
    return "OK";
}

前台Web呼叫

$.ajax({
                headers: {
                    Authorization: $.cookie("
Token")
                },
                type: "GET",
                async: true,
                dataType: "json",
                contentType: 'application/json;charset=UTF-8',
                url: "",
                data: { },
                success: function (msg) {}
                , complete: function () {
                    $("#loadingScreen").toggle();
                }, statusCode: {
                                   401: function (error, response, body) {

                                    return;
                    }
                }
            });

 

arrow
arrow
    文章標籤
    .NET Core OAuth
    全站熱搜

    程式小試身手 發表在 痞客邦 留言(0) 人氣()