// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //authentication services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(AuthenticationConfig.GetApiResources()) .AddInMemoryClients(AuthenticationConfig.GetClients()); services.AddMvcCore() .AddAuthorization() .AddJsonFormatters(); services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "http://*****:*****@"Server=.;Database=dtCms;Trusted_Connection=True;"; services.AddDbContext <dtCmsContext>(options => options.UseSqlServer(connection)); }
private async Task <Dictionary <string, string> > GenerateToken(UserModel user, string clientId, AccessTokenType accessTokenType = AccessTokenType.Reference) { var request = new TokenCreationRequest(); var identityUser = new IdentityServerUser(user.UserName); Dictionary <string, string> tokenResponse = null; string accessToken = null; string identityToken = null; string refreshToken = null; var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim("FirstName", user.FirstName), new Claim("LastName", user.LastName), new Claim("UserName", user.UserName) }; try { // Add Identity User information identityUser.DisplayName = user.FirstName + " " + user.LastName; identityUser.AuthenticationTime = DateTime.UtcNow; identityUser.IdentityProvider = IdentityServer4.IdentityServerConstants.LocalIdentityProvider; // Build Token Request information request.Subject = identityUser.CreatePrincipal(); request.IncludeAllIdentityClaims = true; request.ValidatedRequest = new IdentityServer4.Validation.ValidatedRequest { Subject = request.Subject, }; var clients = AuthenticationConfig.GetClients(); var client = clients.FirstOrDefault(item => item.ClientId == clientId) ?? throw new Exception("invalid client"); request.ValidatedRequest.SetClient(client); request.ValidatedResources = new IdentityServer4.Validation.ResourceValidationResult { Resources = new Resources(AuthenticationConfig.GetIdentityResources(), AuthenticationConfig.GetApiResources(), AuthenticationConfig.GetApiScopes()) }; Token accessTokenObj = null; if (accessTokenType == AccessTokenType.Reference) { accessTokenObj = await _tokenService.CreateAccessTokenAsync(request); accessTokenObj.Issuer = AuthenticationConfig.authority; foreach (var claim in claims) { accessTokenObj.Claims.Add(claim); } accessToken = await _tokenService.CreateSecurityTokenAsync(accessTokenObj); } var principal = new ClaimsPrincipal(); refreshToken = await _refreshTokenService.CreateRefreshTokenAsync(principal, accessTokenObj, client); tokenResponse = new Dictionary <string, string> { { "access_token", accessToken }, }; if (refreshToken != null) { tokenResponse.Add("refresh_token", refreshToken); } } catch (Exception e) { tokenResponse = null; } return(tokenResponse); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { #region MVC Options // Add framework services. // ExpandoObject (the "content" in Response Entity ) is not serialized to camel case by default. // So set the resolver // https://stackoverflow.com/questions/41329279/net-core-json-serialization-of-properties-on-dynamic-expandoobject services.AddMvc(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); options.Filters.Add(typeof(ValidateModelStateFilter)); }).AddJsonOptions(opt => { opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); #endregion #region Authentication // Register IdentityServer services.AddIdentityServer() .AddDeveloperSigningCredential() //.AddInMemoryIdentityResources(AuthenticationConfig.GetIdentityResources()) .AddInMemoryApiResources(AuthenticationConfig.GetApiResources()) .AddInMemoryClients(AuthenticationConfig.GetClients()) .AddCustomUserStore(); // Register authentication services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = AuthenticationSettings.WebAppURL; options.RequireHttpsMetadata = false; options.ApiName = "CMSApi"; }); #endregion #region Automap configuration var automapConfiguration = new MapperConfiguration( cfg => { cfg.CreateMap <DeviceRegisterRequest, NotificationDeviceRegisterRequest>(); cfg.CreateMap <DeviceUnRegisterRequest, NotificationDeviceUnRegisterRequest>(); cfg.CreateMap <TopicRegisterRequest, NotificationTopicRegisterRequest>(); cfg.CreateMap <TopicUnRegisterRequest, NotificationTopicUnRegisterRequest>(); }); IMapper iMapper = automapConfiguration.CreateMapper(); #endregion #region DI // Services services.AddSingleton <IDbService, DbService>(); services.AddSingleton <IEventBusMessagePublisher, EventBusServiceBusMessagePublisher>(); services.AddSingleton(this.mongoDBSettings); services.AddSingleton(this.azureServiceBusSettings); services.AddSingleton(this.fcmAppSettings); // TODO - Not sure authenticationSettings can be injected everywhere //services.AddSingleton(this.authenticationSettings); services.AddSingleton <IRegistrationService, FcmRegistrationService>(); services.AddSingleton <IResponseGenerator, ResponseGenerator>(); services.AddSingleton <IStaticDataService, StaticDataService>(); // Repository services.AddSingleton <IResponseRepository, ResponseRepository>(); services.AddSingleton <IFlowMapRepository, FlowMapRepository>(); services.AddSingleton <IUserDeviceRepository, UserDeviceRepository>(); services.AddSingleton <IUserDeviceRepository, UserDeviceRepository>(); // Automap services.AddSingleton(iMapper); var builder = new ContainerBuilder(); builder.Populate(services); this.ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(this.ApplicationContainer)); #endregion }