Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added client side generation #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/OidcTemplate.Api/OidcTemplate.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,21 @@
<RootNamespace>OpenSoftware.OidcTemplate.Api</RootNamespace>
</PropertyGroup>

<Target Name="NSwag" AfterTargets="Build">
<Copy SourceFiles="@(Reference)" DestinationFolder="$(OutDir)References" />
<Exec Command="$(NSwagExe_Core20) run debug.nswag" />
<RemoveDir Directories="$(OutDir)References" />
</Target>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.5" />
<PackageReference Include="NSwag.AspNetCore" Version="11.15.3" />
<PackageReference Include="NSwag.MSBuild" Version="11.15.3" />
<PackageReference Include="Serilog" Version="2.6.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
Expand Down
21 changes: 15 additions & 6 deletions src/OidcTemplate.Api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using IdentityModel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NJsonSchema;
using NSwag;
using NSwag.AspNetCore;
using NSwag.SwaggerGeneration.Processors.Security;
using OpenSoftware.OidcTemplate.Domain.Authentication;
using OpenSoftware.OidcTemplate.Domain.Configuration;

namespace OpenSoftware.OidcTemplate.Api
{
public class Startup
{
private readonly int _sslPort = 443;
private readonly int _sslPort = 443;

public Startup(IHostingEnvironment env, IConfiguration configuration)
{
Expand Down Expand Up @@ -45,11 +51,11 @@ public void ConfigureServices(IServiceCollection services)
services.AddApplicationInsightsTelemetry(Configuration);

services.AddMvcCore(options =>
{
// options.Conventions.Insert(0, new ModeRouteConvention());
// options.Filters.Add(new RequireHttpsAttribute());
options.SslPort = _sslPort;
})
{
// options.Conventions.Insert(0, new ModeRouteConvention());
// options.Filters.Add(new RequireHttpsAttribute());
options.SslPort = _sslPort;
})
.AddAuthorization()
.AddJsonFormatters();

Expand Down Expand Up @@ -91,6 +97,9 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)

app.UseCors("default");
app.UseAuthentication();

app.UseSwaggerUi(typeof(Startup).Assembly, new SwaggerUiSettings());

app.UseMvc();
}
}
Expand Down
68 changes: 68 additions & 0 deletions src/OidcTemplate.Api/debug.nswag
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"runtime": "NetCore20",
"swaggerGenerator": {
"webApiToSwagger": {
"controllerNames": [],
"isAspNetCore": true,
"defaultUrlTemplate": "api/{controller}/{id?}",
"defaultPropertyNameHandling": "CamelCase",
"defaultReferenceTypeNullHandling": "NotNull",
"defaultEnumHandling": "String",
"flattenInheritanceHierarchy": false,
"generateKnownTypes": true,
"generateXmlObjects": false,
"generateAbstractProperties": false,
"addMissingPathParameters": false,
"ignoreObsoleteProperties": false,
"allowReferencesWithProperties": false,
"excludedTypeNames": [],
"output": "",
"assemblyPaths": [
"bin/Debug/netcoreapp2.0/OpenSoftware.OidcTemplate.Api.dll"
],
"referencePaths": []
}
},
"codeGenerators": {
"swaggerToTypeScriptClient": {
"className": "{controller}Client",
"moduleName": "",
"namespace": "",
"typeScriptVersion": 2.0,
"template": "Angular",
"promiseType": "Promise",
"httpClass": "Http",
"injectionTokenType": "InjectionToken",
"dateTimeType": "Date",
"nullValue": "Undefined",
"generateClientClasses": true,
"generateClientInterfaces": false,
"generateOptionalParameters": false,
"wrapDtoExceptions": true,
"clientBaseClass": "ClientBase",
"wrapResponses": false,
"generateResponseClasses": true,
"responseClass": "SwaggerResponse",
"configurationClass": "Injector",
"useTransformOptionsMethod": true,
"useTransformResultMethod": true,
"generateDtoTypes": true,
"operationGenerationMode": "MultipleClientsFromOperationId",
"markOptionalProperties": true,
"generateCloneMethod": true,
"typeStyle": "Class",
"extendedClasses": [],
"extensionCode": "../OidcTemplate.Client/ClientApp/app/services/generated.extensions.ts",
"generateDefaultValues": true,
"excludedTypeNames": [],
"handleReferences": false,
"generateConstructorInterface": false,
"convertConstructorInterfaceData": false,
"importRequiredTypes": true,
"useGetBaseUrlMethod": false,
"baseUrlTokenName": "API_BASE_URL",
"queryNullValue": "",
"output": "../OidcTemplate.Client/ClientApp/app/services/generated.ts"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { AppComponent } from './components/app/app.component';
AppModuleShared
],
providers: [
{ provide: 'BASE_URL', useFactory: getBaseUrl }
{ provide: 'BASE_URL', useFactory: getBaseUrl },
]
})
export class AppModule {
Expand Down
9 changes: 5 additions & 4 deletions src/OidcTemplate.Client/ClientApp/app/app.shared.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { PortalService } from './services/portal.service';
import { SampleDataClient, API_BASE_URL } from './services/generated';

import { PortalService } from "./services/portal.service";
import {AuthenticatedHttpService} from "./services/authenticated-http.service";

@NgModule({
declarations: [
Expand All @@ -34,8 +34,9 @@ import {AuthenticatedHttpService} from "./services/authenticated-http.service";
])
],
providers: [
AuthenticatedHttpService,
PortalService
PortalService,
SampleDataClient,
{ provide: API_BASE_URL, useValue: new PortalService().appSettings.baseUrls.api }
]
})
export class AppModuleShared {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Component } from '@angular/core';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
styleUrls: ['./app.component.css'],
})
export class AppComponent {
}
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import { Component, OnInit } from '@angular/core';
import {AuthenticatedHttpService} from "../../services/authenticated-http.service";
import { SampleDataClient, WeatherForecast, SwaggerException } from '../../services/generated';

@Component({
selector: 'fetchdata',
templateUrl: './fetchdata.component.html'
})
export class FetchDataComponent implements OnInit{
public forecasts: WeatherForecast[];

constructor(private http: AuthenticatedHttpService) {
constructor(private sampleDataClient: SampleDataClient) {
}

ngOnInit(): void {
this.http.get('api/SampleData/WeatherForecasts').subscribe(result => {
this.forecasts = result.json() as WeatherForecast[];
}, error => console.error(error));
this.sampleDataClient.weatherForecasts().subscribe(result => {
console.log(result)
this.forecasts = result;
}, (error: SwaggerException)=> console.error(error));
}
}

interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Component } from '@angular/core';
import { PortalService } from "../../services/portal.service"

@Component({
selector: 'home',
Expand Down
12 changes: 0 additions & 12 deletions src/OidcTemplate.Client/ClientApp/app/services/IAppSettings.ts

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

import * as generated from "./generated";

import { HttpClient, HttpResponse } from "@angular/common/http"; // ignore
import { Observable } from "rxjs/Observable"; // ignore
import { Http } from "@angular/http"; // ignore
import { API_BASE_URL } from "./generated"; // ignore

import { Injector } from "@angular/core";
import { PortalService } from "./portal.service";


export class ClientBase {
private portalService: PortalService;
private baseHttp: Http;

constructor(private injector: Injector) {
this.portalService = injector.get(PortalService);
this.baseHttp = injector.get(Http);
}

protected transformOptions(options: any) {
options.headers.append("Authorization", "Bearer " + this.portalService.appSettings.accessToken);
return Promise.resolve(options);
}

protected transformResult(url: string, response: Response, processor: (response: Response) => any): Observable<any> {

if (response.status === 401) {
return this.refreshTokens()
.flatMap((newTokenResponse: ITokenRefresh) => {
if (!newTokenResponse || !newTokenResponse.access_token) {
// Something's up with the token refresg. Only solution from here is to re-login
// Redirect to logout
window.location.href = this.portalService.appSettings.baseUrls.web + "/account/logoff";
return Observable.throw("Could not refresh authentication token. Redirecting to logout.");
}
this.portalService.appSettings.accessToken = newTokenResponse.access_token;
return processor(response);
});
} else {
return processor(response);
}
}

refreshTokens() {
console.log("Refreshed access token");
return this.baseHttp.get(this.portalService.appSettings.baseUrls.web + "/Account/RefreshTokens")
.map((r) => <ITokenRefresh>r.json());
}
}

export interface ITokenRefresh {
access_token: string;
}
Loading