public static bool TokenValidation(string token) { try { //SystemIdentityModelToken.SecurityToken validatedToken; MicrosoftIdentityModelToken.SecurityToken validatedToken; var symmetricKey = GetBytes(communicationKey); var signingKey = new MicrosoftIdentityModelToken.SymmetricSecurityKey(Encoding.ASCII.GetBytes(communicationKey)); //var signingKey = new InMemorySymmetricSecurityKey(symmetricKey); MicrosoftIdentityModelToken.TokenValidationParameters validationParameters = new MicrosoftIdentityModelToken.TokenValidationParameters(); //SystemIdentityModelToken.TokenValidationParameters validationParameters = new SystemIdentityModelToken.TokenValidationParameters(); validationParameters.IssuerSigningKey = signingKey; validationParameters.AudienceValidator = AudienceValidator_; validationParameters.ValidateIssuer = false; var tokenC = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out validatedToken); return(true); } catch (Exception ex) { Logger.WriteError(ex); return(false); } }
public void AddServices(IServiceCollection services, IConfiguration configuration) { var jwtSettings = new Security.JWT.Models.JwtSettings(); configuration.Bind(nameof(jwtSettings), jwtSettings); services.AddSingleton(jwtSettings); var tokenValidationParams = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateAudience = false, ValidateIssuer = false, RequireExpirationTime = false, ValidateLifetime = true };; services.AddSingleton(tokenValidationParams); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cog => { cog.SaveToken = true; cog.TokenValidationParameters = tokenValidationParams; }); services.AddSingleton <IJWTHandler, JWTHandler>(); }
public static JWTUserModel GetUserFromToken(string token) { JWTUserModel user = null; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(IssuerSigningKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); try { var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidAudience = ValidAudience, ValidIssuer = ValidIssuer, IssuerSigningKey = creds.Key, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = false }; var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var identity = handler.ValidateToken(token, tokenValidationParameters, out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken); if (identity.Identity.IsAuthenticated) { user = GetJWTUser(identity.Claims); user.Access_Token = token; } } catch (Exception ex) { throw ex; } return(user); }
//authen private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration) { var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateIssuer = false, //k cho phep viec nhung nguoi khac nhau duoc cap chung 1 token IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890 a very long word")), ValidateAudience = false, //1 token không thể đc dùng cho nhiều site RequireExpirationTime = false, // không yêu cầu 1 token phải có exp time ValidateLifetime = true //xác thực lifetime }; context.Services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; //Bearer x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { //options.Authority = configuration["AuthServer:Authority"]; //options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]); //options.Audience = "blog"; options.TokenValidationParameters = tokenValidationParameters; options.SaveToken = true; }); }
public bool ValidateToken(string token) { JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); JwtSecurityToken securityToken = (JwtSecurityToken)handler.ReadToken(token); Microsoft.IdentityModel.Tokens.SecurityToken validatedToken; HMACSHA256 hmac = new HMACSHA256(); hmac.Key = Encoding.UTF8.GetBytes(key); byte[] secretKey = hmac.Key; Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = true, ValidIssuer = "http://localhost:64907", ValidateLifetime = true, ValidateAudience = false, RequireExpirationTime = true, IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(secretKey), }; ClaimsPrincipal claimPrinciple = handler.ValidateToken(token, validationParameters, out validatedToken); //1.Add try catch block //2.Add respective Custom Exception handling return(true); }
/// <summary> /// Recibe un token caducado, verifica si el token fue firmado por esta misma API, si es del mismo usuario /// y si usa el mismo algoritmo de encriptación. /// </summary> /// <param name="accessToken">Token caducado que viene del cliente</param> /// <returns></returns> private Usuario GetUserFromAccessToken(string accessToken) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_jwtSettings.SecretKey); // la que configuré en appsettings var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ClockSkew = TimeSpan.Zero }; SecurityToken securityToken; var principle = tokenHandler.ValidateToken(accessToken, tokenValidationParameters, out securityToken); //Verifico si el token de seguridad que caducó ha sido firmado por la misma API JwtSecurityToken jwtSecurityToken = securityToken as JwtSecurityToken; if (jwtSecurityToken != null && jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256Signature, StringComparison.InvariantCultureIgnoreCase)) { // Si lo encuentro: // Obtengo el id de usuario que firmó el token var userId = principle.FindFirst(ClaimTypes.Name)?.Value; // Verifico el id de usuario con el que tengo en la base de datos return(_context.Usuarios.Where(u => u.IdUsuario == Convert.ToInt32(User)).FirstOrDefault()); } // Sino retorno null return(null); }
public void InstallServices(IConfiguration configuration, IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddScoped <IIdentityService, IdentityService>(); #region JWT settings var jwtsettings = new JWTSettings(); configuration.Bind(nameof(jwtsettings), jwtsettings); // nameof give you the variable name or object name in string format, used to avoid hardcoding services.AddSingleton(jwtsettings); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { //here we define the last parameter of jwt token that is the signature made by the header,payload and secretkey ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtsettings.Secret)), ValidateAudience = false, ValidateIssuer = false, RequireExpirationTime = false, ValidateLifetime = true }; services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; }); services.AddSingleton(tokenValidationParameters);//so that we can use it anywhere with single object #endregion services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new Info { Title = "Tweetbook API", Version = "v1" }); var security = new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[0] } }; x.AddSecurityDefinition( "Bearer", new ApiKeyScheme { Description = "JWT authorization header using Bearer Scheme", Name = "Authorization", In = "header", Type = "apiKey" } ); }); }
public void InstallServices(IServiceCollection services, IConfiguration configuration) { var jwtSettings = new JwtSettings(); configuration.Bind(nameof(jwtSettings), jwtSettings); services.AddSingleton(jwtSettings); services.AddIdentity <IdentityUser, IdentityRole>().AddEntityFrameworkStores <DataContext>(); services.AddScoped <IIdentityService, IdentityService>(); services.AddMvc(options => options.Filters.Add <ValidationFilter>() ) .AddFluentValidation(mvcConfiguration => mvcConfiguration.RegisterValidatorsFromAssemblyContaining <Startup>()) //AbstractValidator içeren herşeyi bulur .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; services.AddAuthentication(q => { q.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; q.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; q.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; } ).AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; }); services.AddSingleton(tokenValidationParameters); services.AddScoped <IPostServices, PostService>(); //services.AddSingleton<IPostServices, CosmosPostService>(); }
public bool IsTokenValid(string protectedText) { var defaultAudience = AudiencesStore.DefaultAudience; // Audience audience = AudiencesStore.FindAudience(audienceId); // string symmetricKeyAsBase64 = audience.Base64Secret; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.Default.GetBytes(defaultAudience.Base64Secret)); var validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidIssuer = issuer, ValidateAudience = true, ValidAudience = defaultAudience.AudienceId, ValidateLifetime = true, ValidateIssuer = true, RequireExpirationTime = true, IssuerSigningKey = securityKey }; Microsoft.IdentityModel.Tokens.SecurityToken token = new JwtSecurityToken(); var tokenHandler = new JwtSecurityTokenHandler(); try { ClaimsPrincipal principal = tokenHandler.ValidateToken(protectedText, validationParameters, out token); DateTime now = DateTime.UtcNow; bool isValid = true; if (now > token.ValidTo) { isValid = false; } if (now < token.ValidFrom) { isValid = false; } return(principal.Identity.IsAuthenticated & isValid); } catch { } return(false); }
public void InstallServices(IConfiguration configuration, IServiceCollection services) { var jwtSettings = new JwtSettings(); configuration.Bind(nameof(JwtSettings), jwtSettings); services.AddSingleton(jwtSettings); services.AddScoped <IIdentityService, IdentityService>(); services .AddMvc(opt => { opt.EnableEndpointRouting = false; opt.Filters.Add <ValidationFilter>(); }) .AddFluentValidation(opt => opt.RegisterValidatorsFromAssemblyContaining <Startup>()) .SetCompatibilityVersion(CompatibilityVersion.Latest); TokenValidationParameters tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key: Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = false }; services.AddSingleton(tokenValidationParameters); services .AddAuthentication(opt => { opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; }); }
/// <summary> /// Will produce validation parameters that do not validate against expiry date, only issuer, audience and secret. /// </summary> /// <returns></returns> public TokenValidationParameters SecretOnly() { var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = SigningKey(), ValidateIssuer = true, ValidIssuer = _audience.Issuer, ValidateAudience = true, ValidAudience = _audience.Id, ValidateLifetime = false, //--Difference ClockSkew = TimeSpan.Zero }; return(tokenValidationParameters); }
public static string DecodeJwt(string tokenString, string keyString) { if (keyString == null) { return(null); } // 鍵 チケットの一部をキーとする //var keyString = tiket.Substring(5,20); var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyString)); // トークン操作用のクラス var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); // トークンの文字列表現 //var tokenString = model.Param; // トークン検証用のパラメータを用意 // Audience, Issuer, Lifetimeに関してはデフォルトで検証が有効になっている // audが空でexpが期限切れなのでValidateAudienceとValidateLifetimeはfalseにしておく var validationParams = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateAudience = false, ValidIssuer = keyString, ValidateLifetime = false, IssuerSigningKey = key, }; try { // 第三引数にSecurityToken型の変数を参照で渡しておくと、検証済みのトークンが出力される handler.ValidateToken(tokenString, validationParams, out SecurityToken token); var json = ((System.IdentityModel.Tokens.Jwt.JwtSecurityToken)token).Payload.SerializeToJson(); //Dictionary<string, object> dic = list.ToDictionary(item => item.Key, item => item.Value); return(json); } catch (Exception e) { // ValidateTokenで検証に失敗した場合はここにやってくる Console.WriteLine("トークンが無効です: " + e.Message); return(null); } }
/// <summary> /// Validate JWT token. /// </summary> public static (ClaimsPrincipal, MSTokens.SecurityToken) ValidateToken(string token, string issuer, IEnumerable <MSTokens.SecurityKey> issuerSigningKeys, string audience = null, bool validateAudience = true, bool validateLifetime = true, string nameClaimType = JwtClaimTypes.Subject, string roleClaimType = JwtClaimTypes.Role) { if (token.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(token)); } if (issuer.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(issuer)); } if (issuerSigningKeys?.Count() < 1) { throw new ArgumentException($"At least one key is required.", nameof(issuerSigningKeys)); } if (validateAudience && audience.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(audience)); } var validationParameters = new MSTokens.TokenValidationParameters { SaveSigninToken = true, ValidIssuer = issuer, IssuerSigningKeys = issuerSigningKeys, ValidAudience = audience, ValidateAudience = validateAudience, ValidateLifetime = validateLifetime, NameClaimType = nameClaimType, RoleClaimType = roleClaimType, }; var claimsPrincipal = GetTokenHandler().ValidateToken(token, validationParameters, out var securityToken); return(claimsPrincipal, securityToken); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); app.UseExceptionHandler(appBuilder => { appBuilder.Use(async(context, next) => { var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature; // This should be much more intelligent - at the moment only expired // security tokens are caught - might be worth checking other possible // exceptions such as an invalid signature. if (error != null && (error.Error is SecurityTokenExpiredException || error.Error is SecurityTokenInvalidSignatureException)) { context.Response.StatusCode = 401; // What you choose to return here is up to you, in this case a simple // bit of JSON to say you're no longer authenticated. context.Response.ContentType = "application/json"; await context.Response.WriteAsync( JsonConvert.SerializeObject( new { authenticated = false, tokenExpired = true })); } else if (error != null && error.Error != null) { context.Response.StatusCode = 500; if (error.Error.Source == "Microsoft.AspNet.Authentication.JwtBearer") { context.Response.StatusCode = 401; } context.Response.ContentType = "application/json"; // TODO: Shouldn't pass the exception message straight out, change this. await context.Response.WriteAsync( JsonConvert.SerializeObject (new { success = false, error = error.Error.Message })); } // We're not trying to handle anything else so just let the default // handler handle. else { await next(); } }); }); var key = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes("my super secret key goes here"))); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { IssuerSigningKey = new SymmetricSecurityKey(key), ValidAudience = TokenHandler.JWT_TOKEN_AUDIENCE, ValidIssuer = TokenHandler.JWT_TOKEN_ISSUER, ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(0) //TimeSpan.Zero }; app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = tokenValidationParameters }); app.UseStaticFiles(); app.UseCors(opt => opt.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() ); app.UseMvc(); }
public void IInstallServices(IConfiguration configuration, IServiceCollection services) { var jwtSettings = new JwtSettings(); configuration.Bind(nameof(jwtSettings), jwtSettings); services.AddSingleton(jwtSettings); services.AddScoped <IIdentityService, IdentityService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; services.AddSingleton(tokenValidationParameters); services.AddAuthentication(Options => { Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; Options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.SaveToken = true; options.TokenValidationParameters = tokenValidationParameters; }); services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new OpenApiInfo { Title = "Tweetbook API", Version = "v1" }); var security = new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[0] } }; x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the bearer scheme", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); x.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, new List <string>() } }); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { JwtSettings jwtSettings = new JwtSettings(); Configuration.Bind(nameof(jwtSettings), jwtSettings); services.AddSingleton(jwtSettings); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; services.AddSingleton(tokenValidationParameters); services.AddAuthorization(); services.AddAuthentication(i => { i.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; i.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; i.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(i => { i.SaveToken = true; i.TokenValidationParameters = tokenValidationParameters; }); services.AddDbContext <QuestionnaireDBContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("QuestionnaireDBConnection")); }); services.AddControllers(); services .AddMvc(options => { options.EnableEndpointRouting = false; options.Filters.Add <ValidationFilter>(); }) .AddFluentValidation(optinons => optinons.RegisterValidatorsFromAssemblyContaining <Startup>()); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Questionnaire", Version = "v1" }); c.ExampleFilters(); c.AddSecurityDefinition("bearer", new OpenApiSecurityScheme { Name = "Authorization", Type = SecuritySchemeType.Http, Scheme = "bearer", In = ParameterLocation.Header, Description = "Basic Authorization header using the Bearer scheme." }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearer" } }, new string[] {} } }); }); services.AddSwaggerExamplesFromAssemblyOf <Startup>(); services.AddIdentity <User, IdentityRole>() .AddRoles <IdentityRole>() .AddEntityFrameworkStores <QuestionnaireDBContext>(); //services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>)); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IQuestionnaireService, QuestionnaireService>(); services.AddScoped <IQuestionnaireRepository, QuestionnaireRepository>(); services.AddScoped <IQuestionRepository, QuestionRepository>(); services.AddScoped <IQuestionService, QuestionService>(); services.AddScoped <IAnswerRepository, AnswerRepository>(); services.AddScoped <IAnswerService, AnswerService>(); services.AddScoped <ITokenRepository, TokenRepository>(); services.AddScoped <IIdentityService, IdentityService>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseCors("AnyOrigin"); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); // Register a simple error handler to catch token expiries and change them to a 401, // and return all other errors as a 500. This should almost certainly be improved for // a real application. app.UseExceptionHandler(appBuilder => { appBuilder.Use(async(context, next) => { var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature; // This should be much more intelligent - at the moment only expired // security tokens are caught - might be worth checking other possible // exceptions such as an invalid signature. if (error != null && (error.Error is Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException || error.Error is Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException)) { context.Response.StatusCode = 403; // What you choose to return here is up to you, in this case a simple // bit of JSON to say you're no longer authenticated. context.Response.Headers["Access-Control-Allow-Origin"] = "*"; context.Response.ContentType = "application/json"; await context.Response.WriteAsync( JsonConvert.SerializeObject( new { authenticated = false, tokenExpired = true })); } else if (error != null && error.Error != null) { context.Response.StatusCode = 500; context.Response.Headers["Access-Control-Allow-Origin"] = "*"; context.Response.ContentType = "application/json"; // TODO: Shouldn't pass the exception message straight out, change this. await context.Response.WriteAsync( JsonConvert.SerializeObject (new { Success = false, Response = error.Error.Message })); } // We're not trying to handle anything else so just let the default // handler handle. else { await next(); } }); }); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = key, // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = "RelyBuilderApiIssuer", // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = "RelyBuilderApiAudience", // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here: ClockSkew = TimeSpan.Zero }; var options = new JwtBearerOptions(); options.TokenValidationParameters = tokenValidationParameters; options.Audience = tokenOptions.Audience; options.ClaimsIssuer = tokenOptions.Issuer; app.UseJwtBearerAuthentication(options); app.UseMvc(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var jwtSettings = new Logic.Options.JWTSettings(); Configuration.GetSection("JWTSettings").Bind(jwtSettings); services.AddSingleton(jwtSettings); var sessionCookieLifetime = Configuration.GetValue("SessionCookieLifetime", 60); services.AddScoped <IToken, TokenRepo>(); services.AddScoped <IUser, UserRepo>(); services.AddScoped <IUserInterfaces, UserService>(); var facebookSettings = new Repository.FacebookSettings.FacebookAuthSettings(); Configuration.GetSection("FacebookAuthSettings").Bind(facebookSettings); services.AddSingleton(facebookSettings); services.AddHttpClient("APIClient", client => { client.BaseAddress = new Uri("https://localhost:5201/"); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json"); }); services.AddSingleton <IFacebookInterface, FacebookRepo>(); services.AddRouting(); services.AddControllersWithViews().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true, }; services.AddSingleton(tokenValidationParameters); services.AddAuthentication(option => { option.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; option.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; } ).AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; } ).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, setup => setup.ExpireTimeSpan = TimeSpan.FromMinutes(sessionCookieLifetime) ).AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, option => { option.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; option.Authority = "https://localhost:5101/"; option.ClientId = "pokolokoshop"; option.ResponseType = "code"; option.UsePkce = false; option.Scope.Add("openid"); option.Scope.Add("profile"); option.SaveTokens = true; option.ClientSecret = "secret"; //option.CallbackPath = new PathString("..."); }); services.AddControllers(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); }
public void InstallServices(IServiceCollection services, IConfiguration configuration) { var jwtSettings = new JwtSettings(); configuration.Bind(nameof(jwtSettings), jwtSettings); services.AddSingleton(jwtSettings); services.AddScoped <IIdentityService, IdentityService>(); services .AddMvc(options => { options.Filters.Add <ValidationFilter>(); }) .AddFluentValidation(mvcConfiguration => mvcConfiguration.RegisterValidatorsFromAssemblyContaining <Startup>()) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; services.AddSingleton(tokenValidationParameters); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; }); services.AddAuthorization(); services.AddSingleton <IUriService>(provider => { var accessor = provider.GetRequiredService <IHttpContextAccessor>(); var request = accessor.HttpContext.Request; var absoluteUri = string.Concat(request.Scheme, "://", request.Host.ToUriComponent(), "/"); return(new UriService(absoluteUri)); }); services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new Info { Title = "Storage Api", Version = "v1" }); var security = new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[0] } }; x.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the bearer scheme", Name = "Authorization", In = "header", Type = "apiKey" }); x.AddSecurityRequirement(security); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; // --> disables default ModelState ValidationProblemDetails error }); services.AddCors(); services.AddControllers(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddDbContext <AppDbContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("DefaultConn")); }); services.AddIdentity <AppUser, IdentityRole>(options => { options.SignIn.RequireConfirmedEmail = true; options.User.RequireUniqueEmail = true; options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequiredLength = 6; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; }) .AddEntityFrameworkStores <AppDbContext>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IGlossaryService, GlossaryService>(); var jwtSettings = new JwtSettings(); Configuration.Bind(nameof(JwtSettings), jwtSettings); services.AddSingleton(jwtSettings); var key = Encoding.UTF8.GetBytes(jwtSettings.Secret); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, // --> change ValidateAudience = false, // --> change RequireExpirationTime = false, ValidateLifetime = true }; services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { //options.Events = new JwtBearerEvents //{ // OnTokenValidated = context => // { // // --> use this method to run checks like if the user is active or not, etc. // context.Fail("Unathorised"); // return Task.CompletedTask; // } //}; options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = tokenValidationParameters; }); services.AddSingleton(tokenValidationParameters); }
public void InstallServices(IServiceCollection services, IConfiguration configuration) { var jwtSettings = new JwtSettings(); configuration.Bind(nameof(jwtSettings), jwtSettings); services.AddSingleton(jwtSettings); services.AddScoped <IIdentityService, IdentityService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddCors(); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { // Most important, validates incoming token with server token from appsettings.json ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; services.AddSingleton(tokenValidationParameters); services .AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; }); services.AddAuthorization(); IdentityBuilder builder = services.AddIdentityCore <IdentityUser>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 4; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.User.RequireUniqueEmail = false; }); services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "WebApplication1", Version = "v1" }); var security = new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[0] } }; x.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the bearer scheme", Name = "Authorization", In = "header", Type = "apiKey" }); x.AddSecurityRequirement(security); }); }
public void InstallServices(IServiceCollection services, IConfiguration Configuration) { //JWT var jwtSettings = new JwtSettings(); Configuration.Bind(nameof(jwtSettings), jwtSettings); services.AddSingleton(jwtSettings); var tokenValidationParams = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateAudience = false, ValidateIssuer = false, RequireExpirationTime = false, ValidateLifetime = true };; services.AddSingleton(tokenValidationParams); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cog => { cog.SaveToken = true; cog.TokenValidationParameters = tokenValidationParams; }); services.AddAuthorization(options => { options.AddPolicy("TagViewer", builder => builder.RequireClaim("tags.view", "true")); }); //MVC services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //Swagger services.AddSwaggerGen(config => { config.SwaggerDoc("v1", new Info { Version = "v1", Title = "Order Api", Description = "Test API", TermsOfService = "https://example.com/terms", Contact = new Contact { Name = "prasad", Email = string.Empty, Url = "https://twitter.com/spboyer" }, License = new License { Name = "lic1", Url = "https://example.com/licence" } }); var security = new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[0] } }; config.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "Jwt Authorization for Order Api", Name = "Authorization", In = "header", Type = "apiKey" }); config.AddSecurityRequirement(security); }); }
public void InstallService(IConfiguration configuration, IServiceCollection services) { //Authentication with JWT var jwtSettings = new JwtSettings(); configuration.Bind(nameof(jwtSettings), jwtSettings); //c2: configuration.GetSection("jwtSettings").Bind(jwtSettings); //Hai cách này dùng để bind 1 section ở appsetting cho 1 ĐỐI TƯỢNG (object) //Còn muốn bind 1 sectin cho 1 CLASS, thì ta dùng Configure services.AddSingleton(jwtSettings); //thiết lập các phiên bản tương thích services.AddMvc() //FluentValidation .AddFluentValidation(mvcConfig => mvcConfig.RegisterValidatorsFromAssemblyContaining <Startup>()) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); //TokenValidationParameters property phải được cài đặt cho JWTBearerOptions thì nó cho phép người gọi chỉ định các cài đặt nâng // cao hơn về cách mà mã JWT token được xác thực. //ValidateIssuerSignsKey (Key của issuer phải match với một giá trị mong đợi) //ValdiateIssuer(cho biết rằng token's signature cần được xác thực) var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, ValidateIssuer = false, //k cho phep viec nhung nguoi khac nhau duoc cap chung 1 token IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), //xac thuc signature ValidateAudience = false, //1 token không thể đc dùng cho nhiều site RequireExpirationTime = false, // không yêu cầu 1 token phải có exp time ValidateLifetime = true //xác thực lifetime }; services.AddSingleton(tokenValidationParameters); //AUTHENTICATION services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; //Bearer x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) //add JwtBearerAuthentication //JwtBearer là một middleware tìm kiếm các tokens trong HTTP Authorization header của các request đc gửi tới // Nếu là valid token, request sẽ được authorized. => jwtbeaer giống như 1 công cụ để xác thực = token .AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; //xác thực token đc lấy từ HTTP Request Header. }); //AUTHORIZATION services.AddAuthorization(options => { options.AddPolicy("TagViewer", builder => builder.RequireClaim("tags.view", "true")); options.AddPolicy("CustomPolicy", policy => policy.AddRequirements(new WorksForCompanyRequirement(".dut"))); }); services.AddSingleton <IAuthorizationHandler, WorksForCompanyHandler>(); services.AddMvc(opt => { opt.EnableEndpointRouting = false; opt.Filters.Add <ValidationFilter>(); //opt.Filters.Add<ApiKeyAuthAttribute>(); //opt.Filters.Add<CachedAttribute>(); }); services.AddScoped <IIdentityService, IdentityService>(); //Pagination services.AddSingleton <IUriService>(provider => { //add DI IUriService-UriService, lấy baseUri để đưa cho hàm tạo của UriService //Khi ta gửi request đến server, request đó sẽ chứa các thuộc tính như: path/scheme/.. //Ví dụ gửi request xem tất cả các post //scheme: https //path: api/v1/posts var accessor = provider.GetRequiredService <IHttpContextAccessor>(); var request = accessor.HttpContext.Request; var absoluteUri = string.Concat(request.Scheme, "://", request.Host.ToUriComponent(), "/"); return(new UriService(absoluteUri)); }); }
public void InstallerServices(IServiceCollection services, IConfiguration configuration) { services.AddCors(c => { c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); }); var jwtSettings = new JwtSettings(); configuration.Bind(nameof(jwtSettings), jwtSettings); services.AddSingleton(jwtSettings); services.AddMvc(options => { options.EnableEndpointRouting = false; }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true, LifetimeValidator = LifetimeValidator, //ClockSkew = TimeSpan.Zero }; services.AddSingleton(new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; }); services.AddAuthorization(options => { }); services.AddHttpContextAccessor(); services.AddControllersWithViews() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); }
public async Task <HttpResponseMessage> ValidateAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string jwtToken = null; // The header is of the form "bearer <accesstoken>", so extract to the right of the whitespace to find the access token. var authHeader = request.Headers.Authorization;//.FirstOrDefault(x => x.Key == "Authorization"); if (authHeader != null) { jwtToken = authHeader.Parameter.Trim(); } if (string.IsNullOrWhiteSpace(jwtToken)) { return(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } var secretBytes = Encoding.UTF8.GetBytes("reactFTW!!!"); //Only do this if signature algorithm is HS256 // Okay for now because it is if (secretBytes.Length < 64)// && tokenReceived.SignatureAlgorithm == "HS256") { Array.Resize(ref secretBytes, 64); } JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenManager.TokenValidationParameters { ValidateLifetime = true, //ValidateLifetime = false, ValidateAudience = false, ValidateIssuer = false, IssuerSigningKeys = new[] { new TokenManager.SymmetricSecurityKey(secretBytes) }, }; try { TokenManager.SecurityToken validatedToken = new JwtSecurityToken(jwtToken); // Validate token. ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out validatedToken); // Set the ClaimsPrincipal on the current thread. Thread.CurrentPrincipal = claimsPrincipal; // Set the ClaimsPrincipal on HttpContext.Current if the app is running in web hosted environment. if (HttpContext.Current != null) { HttpContext.Current.User = claimsPrincipal; } return(await base.SendAsync(request, cancellationToken)); } catch (TokenManager.SecurityTokenValidationException ex) { return(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } catch (System.IdentityModel.Tokens.SecurityTokenValidationException) { return(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } catch (Exception ex) { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } }
//private static bool AudienceValidator_(IEnumerable<string> audiences, SystemIdentityModelToken.SecurityToken securityToken, SystemIdentityModelToken.TokenValidationParameters validationParameters) private static bool AudienceValidator_(IEnumerable <string> audiences, MicrosoftIdentityModelToken.SecurityToken securityToken, MicrosoftIdentityModelToken.TokenValidationParameters validationParameters) { return(true); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <DataContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <AppUser, IdentityRole>( q => q.User.RequireUniqueEmail = true) .AddEntityFrameworkStores <DataContext>(); services.AddScoped <IUserClaimsPrincipalFactory <AppUser>, UserClaimsPrincipalFactory <AppUser, IdentityRole> >(); services.AddControllers(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("https://localhost:8090") .AllowAnyMethod() .AllowAnyHeader() .WithExposedHeaders("Pagination") ); }); services.AddMvc().AddNewtonsoftJson(options => { options.SerializerSettings.Converters.Add(new StringEnumConverter()); }); services.AddControllers(); services.AddScoped <ICategoryService, CategoryService>(); services.AddScoped <IAdService, AdService>(); services.AddScoped <IIdentityService, IdentityService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IMessageService, MessageService>(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); var jwtSettings = new JwtSettings { Key = Configuration["JwtSettings:Key"], TokenLifetime = TimeSpan.FromDays(1) }; services.AddSingleton(jwtSettings); services.AddMvc(options => { options.EnableEndpointRouting = false; options.Filters.Add <ValidationFilter>(); }) .AddFluentValidation(mvcConfiguration => mvcConfiguration.RegisterValidatorsFromAssemblyContaining <Startup>()) .SetCompatibilityVersion(CompatibilityVersion.Latest); services.AddSingleton <IUriService>(provider => { var accessor = provider.GetRequiredService <IHttpContextAccessor>(); if (accessor.HttpContext != null) { var request = accessor.HttpContext.Request; var absoluteUri = string.Concat(request.Scheme, "://", request.Host.ToUriComponent(), "/"); return(new UriService(absoluteUri)); } return(null); }); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Key)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.SaveToken = true; x.TokenValidationParameters = tokenValidationParameters; }); services.AddAuthorization(); services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new OpenApiInfo { Title = "webAPI", Version = "v1" }); x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey }); x.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, new List <string>() } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); x.IncludeXmlComments(xmlPath); }); services.AddSwaggerGenNewtonsoftSupport(); }
static async Task Main(string[] args) { // request token var tokenClient = new TokenClient(new HttpClient() { BaseAddress = new Uri("http://localhost:5000/connect/token") }, new TokenClientOptions() { ClientId = "client", ClientSecret = "secret" }); var tokenResponse = await tokenClient.RequestClientCredentialsTokenAsync(); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); } Console.WriteLine(tokenResponse.Json); var passwordTokenClient = new TokenClient(new HttpClient() { BaseAddress = new Uri("http://localhost:5000/connect/token") }, new TokenClientOptions() { ClientId = "ro.client", ClientSecret = "secret" }); var passwordTokenResponse = await passwordTokenClient.RequestPasswordTokenAsync("alice", "password"); if (passwordTokenResponse.IsError) { Console.WriteLine(passwordTokenResponse.Error); } else { var keyClient = new HttpClient() { }; var webkey = await keyClient.GetJsonWebKeySetAsync("http://localhost:5000/.well-known/openid-configuration/jwks"); if (webkey.IsError) { return; } var configuration = OpenIdConnectConfiguration.Create(webkey.Raw); var RsaParameter = new RSAParameters() { Exponent = Convert.FromBase64String(webkey.KeySet.Keys.First().E), Modulus = Base64Url.Decode(webkey.KeySet.Keys.First().N) }; var rsa = new RSACryptoServiceProvider(2048); var publishKey = rsa.ExportParameters(false); var key = new RsaSecurityKey(RsaParameter); var validateParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuerSigningKey = false, IssuerSigningKey = key, ValidateAudience = false, ValidateIssuer = false }; JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); var user = jwtSecurityTokenHandler.ValidateToken(passwordTokenResponse.Json.GetValue("access_token").ToString(), validateParameters, out var token); Console.WriteLine(passwordTokenResponse.Json.GetValue("access_token")); } Console.WriteLine("\n\n"); Console.ReadKey(); var client = new HttpClient(); // call api //var client = new HttpClient(); //client.SetBearerToken(tokenResponse.AccessToken); //var response = await client.GetAsync("http://localhost:5001/identity"); //if (!response.IsSuccessStatusCode) //{ // Console.WriteLine(response.StatusCode); //} //else //{ // var content = await response.Content.ReadAsStringAsync(); // Console.WriteLine(JArray.Parse(content)); //} }
/// <summary> /// /// </summary> /// <param name="services"></param> public static void AuthExtension(this IServiceCollection services) { #region 获取配置文件信息 var audienceConfig = Appsettings.app(new string[] { "JwtSettings" });// Configuration.GetSection("JwtSettings"); var jwtSettings = new JwtSettings() { SecretKey = Appsettings.app(new string[] { "JwtSettings", "SecretKey" }), Issuer = Appsettings.app(new string[] { "JwtSettings", "Issuer" }), Audience = Appsettings.app(new string[] { "JwtSettings", "Audience" }), }; var symmetricKeyAsBase64 = jwtSettings.SecretKey; var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64); var signingKey = new SymmetricSecurityKey(keyByteArray); //Configuration.Bind("JwtSettings", jwtSettings); //获取主要jwt token参数设置 // 令牌验证参数 var TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, //Token颁发机构 ValidIssuer = jwtSettings.Issuer, //颁发给谁 ValidAudience = jwtSettings.Audience, //这里的key密钥要进行加密,需要引用Microsoft.IdentityModel.Tokens IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),//加密密钥 ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ////是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比 ClockSkew = TimeSpan.Zero, ////允许的服务器时间偏移量 RequireExpirationTime = true, }; var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var permission = new List <PermissionItem>(); //需要从数据库动态绑定,这里先留个空,后边处理器里动态赋值 // var permissionRequirement = new PermissionRequirement ( "/api/denied", //拒绝跳转的Action permission, //角色菜单实体 ClaimTypes.Role, //基于角色的授权 jwtSettings.Issuer, //发行人 jwtSettings.Audience, //听众 signingCredentials, //签名凭据 expiration: TimeSpan.FromSeconds(60 * 60) //过期时间 ); //No.1 基于自定义角色的策略授权 services.AddAuthorization(options => { options.AddPolicy(GlobalRouteAuthorizeVars.Name, policy => policy.Requirements.Add(permissionRequirement)); }); //No.2 配置认证服务 services.AddAuthentication(options => { //认证middleware配置 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(t => { t.TokenValidationParameters = TokenValidationParameters; //给SignalR 赋值给集线器的链接管道添加Token验证 t.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(path) && path.StartsWithSegments("/api2/chatHub")) { context.Token = accessToken; } return(Task.CompletedTask); } }; //过期时间判断 //t.Events = new JwtBearerEvents //{ // // 如果过期,则把<是否过期>添加到,返回头信息中 // OnAuthenticationFailed = context => // { // if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) // { // context.Response.Headers.Add("Token-Expired", "true"); // } // return Task.CompletedTask; // } //}; }); //注入权限处理核心控制器,将自定义的授权处理器 匹配给官方授权处理器接口,这样当系统处理授权的时候,就会直接访问我们自定义的授权处理器了。 services.AddScoped <IAuthorizationHandler, PermissionHandler>();//注意此处的注入类型取决于你获取角色Action信息的注入类型如果你服务层用AddScoped此处也必须是AddScoped //将授权必要类注入生命周期内 services.AddSingleton(permissionRequirement); #endregion }
/// <summary> /// 启动程序 /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { #region 配置启动程序 //获取appsettings.json文件Default节点下面的连接字符串 var sqlconn = Configuration.GetConnectionString("SqlserverDefault"); //第一个参数传入连接字符串 , 第二个参数指明执行迁移的程序集 //options.UseSqlServer(sqlconn,b=>b.MigrationsAssembly("CorePractice") 如果事WebApi 项目的话需要加services.AddEntityFrameworkSqlServer().AddDbContext services.AddEntityFrameworkSqlServer().AddDbContext <UwlDbContext>(options => options.UseSqlServer(sqlconn, b => b.MigrationsAssembly("UwlAPI.Tools"))); #endregion services.AddMvc(mvc => { //全局路由权限公约,给路由添加Authorize特性 mvc.Conventions.Insert(0, new GlobalRouteAuthorizeConvention()); //mvc.Conventions.Insert(0, new AddRoutePrefixFilter(new RouteAttribute(RoutePrefix.Name))); }); #region Swagger services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new Info { Version = "v0.1.0", Title = "UwlAPI.Tools", Description = "框架说明文档", TermsOfService = "None", Contact = new Contact { Name = "UwlAPI.Tools", Email = "*****@*****.**", Url = "https://www.jianshu.com/u/94102b59cc2a" } }); var basepath = AppDomain.CurrentDomain.BaseDirectory; var xmls = System.IO.Directory.GetFiles(basepath, "*.xml"); foreach (var xml in xmls) { x.IncludeXmlComments(xml); } var IssuerName = (Configuration.GetSection("JwtSettings"))["Issuer"];// 发行人 var security = new Dictionary <string, IEnumerable <string> > { { IssuerName, new string[] { } }, }; x.AddSecurityRequirement(security); x.AddSecurityDefinition(IssuerName, new ApiKeyScheme { Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"", Name = "Authorization", //jwt默认的参数名称 In = "header", //jwt默认存放Authorization信息的位置(请求头中) Type = "apiKey" }); }); #endregion #region 获取配置文件信息 var audienceConfig = Configuration.GetSection("JwtSettings"); var symmetricKeyAsBase64 = audienceConfig["SecretKey"]; var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64); var signingKey = new SymmetricSecurityKey(keyByteArray); var jwtSettings = new JwtSettings(); Configuration.Bind("JwtSettings", jwtSettings); //获取主要jwt token参数设置 // 令牌验证参数 var TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, //Token颁发机构 ValidIssuer = audienceConfig["Issuer"], //颁发给谁 ValidAudience = audienceConfig["Audience"], //这里的key要进行加密,需要引用Microsoft.IdentityModel.Tokens IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)), ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ////是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比 ClockSkew = TimeSpan.Zero, ////允许的服务器时间偏移量 RequireExpirationTime = true, }; #endregion #region No.1 官方的JWT验证 简单的策略授权(简单版) //services.AddAuthorization(options => //{ // options.AddPolicy("Client", policy => policy.RequireRole("Client").Build()); // options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build()); // options.AddPolicy("SystemOrAdmin", policy => policy.RequireRole("Admin", "System")); // options.AddPolicy("SystemOrAdminOrOther", policy => policy.RequireRole("Admin", "System", "Other")); //}); //services.AddAuthentication(options => //{ // options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; // options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; //}).AddJwtBearer(jwt=> //{ // jwt.TokenValidationParameters = TokenValidationParameters; //}); #endregion #region No.2 中间件授权认证方式 使用此认证需要在Configure里面放开app.UseMiddleware<JwtTokenAuth>();取消注释所有控制器的[Authorize(Policy = "Admin")] 并且注释掉[Authorize] //中间件签名过期无效待解决——————需要自己写鉴权方式,前名是否过期……????????????????????????????????? //基于角色的策略授权(简单版) + 自定义认证中间件 //services.AddAuthorization(options => //{ // options.AddPolicy("Client", policy => policy.RequireRole("Client").Build()); // options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build()); // options.AddPolicy("AdminOrClient", policy => policy.RequireRole("AdminOrClient").Build()); //}); // 2【认证】、然后在下边的configure里,配置中间件即可: // app.UseMiddleware<JwtTokenAuth>(); //services.AddAuthorization(options => //{ // options.AddPolicy("Client", policy => policy.RequireRole("Client").Build()); // options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build()); // options.AddPolicy("SystemOrAdmin", policy => policy.RequireRole("Admin", "System")); // options.AddPolicy("SystemOrAdminOrOther", policy => policy.RequireRole("Admin", "System", "Other")); //}); //services.AddAuthentication(options => //{ // options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; // options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; //}).AddJwtBearer(jwt => //{ // jwt.TokenValidationParameters = TokenValidationParameters; //}); #endregion #region No.3 复杂策略授权 + 官方JWT认证 var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var permission = new List <PermissionItem>(); //需要从数据库动态绑定,这里先留个空,后边处理器里动态赋值 // var permissionRequirement = new PermissionRequirement ( "/api/denied", //拒绝跳转的Action permission, //角色菜单实体 ClaimTypes.Role, //基于角色的授权 jwtSettings.Issuer, //发行人 jwtSettings.Audience, //听众 signingCredentials, //签名凭据 expiration: TimeSpan.FromSeconds(15 * 60) //过期时间 ); //No.1 基于角色的授权 services.AddAuthorization(options => { options.AddPolicy(GlobalRouteAuthorizeVars.Name, policy => policy.Requirements.Add(permissionRequirement)); }); //No.2 配置认证服务 services.AddAuthentication(options => { //认证middleware配置 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(t => { t.TokenValidationParameters = TokenValidationParameters; //给SignalR 赋值给集线器的链接管道添加Token验证 t.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(path) && path.StartsWithSegments("/api/chatHub")) { context.Token = accessToken; } return(Task.CompletedTask); } }; //过期时间判断 //t.Events = new JwtBearerEvents //{ // // 如果过期,则把<是否过期>添加到,返回头信息中 // OnAuthenticationFailed = context => // { // if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) // { // context.Response.Headers.Add("Token-Expired", "true"); // } // return Task.CompletedTask; // } //}; }); //注入权限处理核心控制器,将自定义的授权处理器 匹配给官方授权处理器接口,这样当系统处理授权的时候,就会直接访问我们自定义的授权处理器了。 services.AddScoped <IAuthorizationHandler, PermissionHandler>();//注意此处的注入类型取决于你获取角色Action信息的注入类型如果你服务层用AddScoped此处也必须是AddScoped //将授权必要类注入生命周期内 services.AddSingleton(permissionRequirement); #endregion services.AddSignalR(); #region 添加automapper实体映射,如果存在相同字段则自动映射 services.AddAutoMapper(); //注册需要自动映射的实体类 _mapperConfiguration = new MapperConfiguration(cfg => { //初始化自动映射类 cfg.AddProfile <MyProfile>(); }); //将自动映射属性封装为静态属性 MyMappers.ObjectMapper = _mapperConfiguration.CreateMapper(); #endregion #region Cors跨域需要添加以下代码 //services.AddCors(c => //{ // //控制器中[EnableCors("AllRequests")]名字需对应 // c.AddPolicy("AllRequests", policy => // { // policy // .AllowAnyOrigin()//允许任何源 // .AllowAnyMethod()//允许任何方式 // .AllowAnyHeader()//允许任何头 // .AllowCredentials();//允许cookie // }); //}); #endregion #region 接口控制反转依赖注入 -netcore自带方法 //services.AddSingleton<IAuthorizationHandler, DomainUserServer>(); services.AddScoped <MyProfile>();//注入自动映射类 //注入工作单元接口和实现 services.AddScoped <IUnitofWork, UnitofWorkBase>(); //services.AddScoped(typeof(IRepository<Entity,Guid>), typeof(UwlRepositoryBase<Entity, Guid>)); //注入用户管理领域仓储层实现 services.AddScoped <IUserRepositoty, DomainUserServer>(); //注入用户管理服务层实现 services.AddScoped <IUserServer, UserServer>(); //services.AddScoped<Log>();//注入记录日志类 //注入日志管理领域仓储层实现 services.AddScoped <ILogRepositoty, DomainLogsServer>(); //注入日志管理服务层实现 services.AddScoped <ILogsServer, LogsServer>(); //注入菜单管理领域仓储层实现 services.AddScoped <IMenuRepositoty, DomainMenuServer>(); //注入菜单管理服务层实现 services.AddScoped <IMenuServer, MenuServer>(); //注入角色管理领域仓储层实现 services.AddTransient <IRoleRepositoty, DomainRoleServer>(); //注入角色管理服务层实现 services.AddTransient <IRoleServer, RoleServer>(); //注入按钮管理领域仓储层实现 services.AddScoped <IButtonRepositoty, DomainButtonServer>(); //注入按钮管理服务层实现 services.AddScoped <IButtonServer, ButtonServer>(); //注入菜单按钮管理领域仓储层实现 services.AddScoped <ISysMenuButton, DomainSysMenuButton>(); //注入菜单按钮服务层实现 services.AddScoped <ISysMenuButtonServer, SysMenuButtonServer>(); //注入角色权限分配领域仓储实现 services.AddScoped <IRoleRightAssigRepository, DomainRoleRightAssigServer>(); //注入角色权限分配服务层实现 services.AddScoped <IRoleAssigServer, SysRoleAssigServer>(); //注入用户角色领域仓储实现 services.AddScoped <IUserRoleRepository, DomainUserRoleServer>(); //注入用户角色服务层 services.AddScoped <IUserRoleServer, UserRoleServer>(); //注入组织机构领域仓储实现 services.AddScoped <IOrganizeRepositoty, DomainOrganizeServer>(); //注入组织机构服务层 services.AddScoped <IOrganizeServer, OrganizeServer>(); //注入计划任务领域仓储实现 services.AddScoped <IScheduleRepositoty, DomainScheduleServer>(); //注入计划任务服务层 services.AddScoped <IScheduleServer, ScheduleServer>(); //注入Redis缓存 services.AddSingleton <IRedisCacheManager, RedisCacheManager>(); //注入RabbitMQ服务 services.AddSingleton <IRabbitMQ, RabbitServer>(); services.AddSingleton <ISchedulerCenter, SchedulerCenterServer>(); #endregion }