Commit 4402f5c6 authored by alan.f's avatar alan.f

add-identity-server

parent 95408542
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.4" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.3" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ApiOne.Controllers
{
public class SecretController : Controller
{
[Route("/secret")]
[Authorize]
public string Index()
{
//var claims = User.Claims.ToList();
return "secret message from ApiOne";
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ApiOne
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:61001",
"sslPort": 44340
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ApiOne": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ApiOne
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", config =>
{
config.Authority = "https://localhost:44325/";
config.Audience = "ApiOne";
//config.RequireHttpsMetadata = false;
});
services.AddHttpClient();
//services.AddCors(confg =>
// confg.AddPolicy("AllowAll",
// p => p.AllowAnyOrigin()
// .AllowAnyMethod()
// .AllowAnyHeader()));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseCors("AllowAll");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="IdentityModel" Version="4.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.4" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.3" />
</ItemGroup>
</Project>
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
namespace ApiTwo.Controllers
{
public class HomeController : Controller
{
private readonly IHttpClientFactory _httpClientFactory;
public HomeController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[Route("/home")]
public async Task<IActionResult> Index()
{
//retrieve access token
var serverClient = _httpClientFactory.CreateClient();
var discoveryDocument = await serverClient.GetDiscoveryDocumentAsync("https://localhost:44325/");
var tokenResponse = await serverClient.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address = discoveryDocument.TokenEndpoint,
ClientId = "client_id",
ClientSecret = "client_secret",
Scope = "ApiOne",
});
//retrieve secret data
var apiClient = _httpClientFactory.CreateClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);
var response = await apiClient.GetAsync("https://localhost:44340/secret");
var content = await response.Content.ReadAsStringAsync();
return Ok(new
{
access_token = tokenResponse.AccessToken,
message = content,
});
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ApiTwo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:61267",
"sslPort": 44320
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ApiTwo": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ApiTwo
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", config =>
{
config.Authority = "https://localhost:44325/";
config.Audience = "ApiTwo";
//config.RequireHttpsMetadata = false;
});
services.AddHttpClient();
//services.AddCors(confg =>
// confg.AddPolicy("AllowAll",
// p => p.AllowAnyOrigin()
// .AllowAnyMethod()
// .AllowAnyHeader()));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowAll");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
......@@ -5,7 +5,19 @@ VisualStudioVersion = 16.0.29911.84
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basics", "Basics\Basics.csproj", "{E2F91297-82C6-4735-B44E-1EAE43684D33}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IdentityExample", "IdentityExample\IdentityExample.csproj", "{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IdentityExample", "IdentityExample\IdentityExample.csproj", "{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IdentityServer4", "IdentityServer4", "{BAE8199D-D3C7-4D71-9A3E-7DC76A54EDDF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IdentityServer", "IdentityServer\IdentityServer.csproj", "{C485D2F3-980A-468C-A0AB-D1F1EF1C1568}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Basic", "Basic", "{74E427C0-9930-417D-9787-67F03127196B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiOne", "ApiOne\ApiOne.csproj", "{E2FD0592-0C76-4D1C-9C3E-5A8FECA85D3E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiTwo", "ApiTwo\ApiTwo.csproj", "{F0813394-EC56-461F-BE36-CE7E229C46B8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MvcClient", "MvcClient\MvcClient.csproj", "{592538AC-4F87-4642-B9F5-0A94C31262A7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
......@@ -21,10 +33,34 @@ Global
{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}.Release|Any CPU.Build.0 = Release|Any CPU
{C485D2F3-980A-468C-A0AB-D1F1EF1C1568}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C485D2F3-980A-468C-A0AB-D1F1EF1C1568}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C485D2F3-980A-468C-A0AB-D1F1EF1C1568}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C485D2F3-980A-468C-A0AB-D1F1EF1C1568}.Release|Any CPU.Build.0 = Release|Any CPU
{E2FD0592-0C76-4D1C-9C3E-5A8FECA85D3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E2FD0592-0C76-4D1C-9C3E-5A8FECA85D3E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E2FD0592-0C76-4D1C-9C3E-5A8FECA85D3E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E2FD0592-0C76-4D1C-9C3E-5A8FECA85D3E}.Release|Any CPU.Build.0 = Release|Any CPU
{F0813394-EC56-461F-BE36-CE7E229C46B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F0813394-EC56-461F-BE36-CE7E229C46B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F0813394-EC56-461F-BE36-CE7E229C46B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F0813394-EC56-461F-BE36-CE7E229C46B8}.Release|Any CPU.Build.0 = Release|Any CPU
{592538AC-4F87-4642-B9F5-0A94C31262A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{592538AC-4F87-4642-B9F5-0A94C31262A7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{592538AC-4F87-4642-B9F5-0A94C31262A7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{592538AC-4F87-4642-B9F5-0A94C31262A7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{E2F91297-82C6-4735-B44E-1EAE43684D33} = {74E427C0-9930-417D-9787-67F03127196B}
{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323} = {74E427C0-9930-417D-9787-67F03127196B}
{C485D2F3-980A-468C-A0AB-D1F1EF1C1568} = {BAE8199D-D3C7-4D71-9A3E-7DC76A54EDDF}
{E2FD0592-0C76-4D1C-9C3E-5A8FECA85D3E} = {BAE8199D-D3C7-4D71-9A3E-7DC76A54EDDF}
{F0813394-EC56-461F-BE36-CE7E229C46B8} = {BAE8199D-D3C7-4D71-9A3E-7DC76A54EDDF}
{592538AC-4F87-4642-B9F5-0A94C31262A7} = {BAE8199D-D3C7-4D71-9A3E-7DC76A54EDDF}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {503F7386-5516-4A48-B303-EB2EBBB70E07}
EndGlobalSection
......
using IdentityModel;
using IdentityServer4;
using IdentityServer4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServer
{
public static class Configuration
{
public static IEnumerable<IdentityResource> GetIdentityResources() =>
new List<IdentityResource>() {
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource
{
Name = "rc.scope",
UserClaims =
{
"rc.garndma"
}
}
};
public static IEnumerable<ApiResource> GetApis() =>
new List<ApiResource>
{
new ApiResource("ApiOne"),
new ApiResource("ApiTwo"),
};
public static IEnumerable<Client> GetClients() =>
new List<Client>
{
new Client
{
ClientId="client_id",
ClientSecrets={ new Secret("client_secret".ToSha256())},
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes={ "ApiOne"}
},
new Client
{
ClientId="client_id_mvc",
ClientSecrets={ new Secret("client_secret_mvc".ToSha256())},
AllowedGrantTypes = GrantTypes.Code,
RedirectUris={ "https://localhost:44349/signin-oidc" },
AllowedScopes={
"ApiOne",
"ApiTwo" ,
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"rc.scope"
},
//puts all the claims in the id token
//AlwaysIncludeUserClaimsInIdToken=true,
RequireConsent=false
}
};
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace IdentityServer.Controllers
{
public class AuthController : Controller
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
public AuthController(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
[HttpGet]
public IActionResult Login(string returnUrl)
{
return View(new LoginViewModel { ReturnUrl =returnUrl});
}
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel vm)
{
//check if model is exsist
var result = await _signInManager.PasswordSignInAsync(vm.Username, vm.Password, false, false);
if (result.IsNotAllowed)
{
return Redirect(vm.ReturnUrl);
}
else if (result.IsLockedOut)
{
}
return View();
}
[HttpGet]
public IActionResult Register(string returnUrl)
{
return View(new RegisterViewModel { ReturnUrl = returnUrl });
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel vm)
{
if (!ModelState.IsValid)
{
return View(vm);
}
var user = new IdentityUser(vm.Username);
var result = await _userManager.CreateAsync(user, vm.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, false);
return Redirect(vm.ReturnUrl);
}
return View();
}
}
}
\ No newline at end of file

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace IdentityServer.Data
{
// IdentityDbContext contains all the user tables
public class AppDbContext : IdentityDbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="IdentityServer4" Version="3.1.3" />
<PackageReference Include="IdentityServer4.AspNetIdentity" Version="3.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="3.1.4" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.4" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="3.1.4" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.3" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace IdentityServer
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var userManager = scope.ServiceProvider.
GetRequiredService<UserManager<IdentityUser>>();
var user = new IdentityUser("alan");
userManager.CreateAsync(user, "password").GetAwaiter().GetResult();
userManager.AddClaimAsync(user, new Claim("rc.garndma", "big.cookie"))
.GetAwaiter().GetResult();
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:60605",
"sslPort": 44325
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IdentityServer": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using IdentityServer.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace IdentityServer
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(config =>
{
config.UseInMemoryDatabase("Memory");
});
// AddIdentity registers the services
services.AddIdentity<IdentityUser, IdentityRole>(config =>
{
config.Password.RequiredLength = 4;
config.Password.RequireDigit = false;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "IdentityServer.Cookie";
config.LoginPath = "/Auth/Login";
});
services.AddIdentityServer()
.AddAspNetIdentity<IdentityUser>()
.AddInMemoryApiResources(Configuration.GetApis())
.AddInMemoryIdentityResources(Configuration.GetIdentityResources())
.AddInMemoryClients(Configuration.GetClients())
.AddDeveloperSigningCredential();
//services.AddAuthentication()
// .AddFacebook(config => {
// config.AppId = "3396617443742614";
// config.AppSecret = "secret";
// });
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServer.ViewModels
{
public class LoginViewModel
{
public string Username { get; set; }
public string Password { get; set; }
public string ReturnUrl { get; set; }
//public IEnumerable<AuthenticationScheme> ExternalProviders { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServer.ViewModels
{
public class RegisterViewModel
{
[Required]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword { get; set; }
public string ReturnUrl { get; set; }
}
}
@model LoginViewModel
<h1>Sign In With</h1>
@*<form asp-controller="Auth" asp-action="ExternalLogin"
asp-route-returnUrl="@Model.ReturnUrl" method="post">
@foreach (var provider in Model.ExternalProviders)
{
<button name="provider"
type="submit"
value="@provider.Name">
@provider.Name
</button>
}
</form>*@
<form asp-controller="Auth" asp-action="Login" method="post">
<input type="hidden" asp-for="ReturnUrl" />
<div>
<label>Username</label>
<input asp-for="Username" />
</div>
<div>
<label>Password</label>
<input asp-for="Password" />
</div>
<div>
<button type="submit">Sign In</button>
</div>
</form>
<div>
<a asp-controller="Auth" asp-action="Register"
asp-route-returnUrl="@Model.ReturnUrl">Register</a>
</div>
\ No newline at end of file
@model RegisterViewModel
<form asp-controller="Auth" asp-action="Register" method="post">
<input type="hidden" asp-for="ReturnUrl" />
<div>
<label>Username</label>
<input asp-for="Username" />
<span asp-validation-for="Username"></span>
</div>
<div>
<label>Password</label>
<input asp-for="Password" />
<span asp-validation-for="Password"></span>
</div>
<div>
<label>Password</label>
<input asp-for="ConfirmPassword" />
<span asp-validation-for="ConfirmPassword"></span>
</div>
<div>
<button type="submit">Sign Up</button>
</div>
</form>
<a asp-controller="Auth" asp-action="Login"
asp-route-returnUrl="@Model.ReturnUrl">Back to Login</a>
\ No newline at end of file
@using IdentityServer.ViewModels
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
\ No newline at end of file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
{"KeyId":"SdbPpmysCIs5YedrPEGghA","Parameters":{"D":"J/ZyMAjNfyewnjDVTkdRrpkDc1ijPC4nGaLne+FA/P8RO0MEZ6RPz6STw+d3bjc119p3j3BsoPkkNfQ/JDTbrld2Nn6nxG2Fg65623Mdhub1/WmaCethtJADd6e13NhBMf4tj/0hx2bnHHN8q3aT9/8TatiRHHp4qHi/emVTsjO0W2WG+6oCc6bOAmmVwVYRfcuO1Jke+XWYJF2Uo6Vz7kiaAhXy6H0mDXrIDhIYUIf8TI1Am9BAxrAOVAhWt5WKyhIqRqCSje9NIDX5AnKvFLBO46yhIcWr1tznibtVhm7viM7M1LUXck8Q0fmEWirTgn1XwcurXO/bSZAARI7vkQ==","DP":"mo7IGAl42YHIVhdO4nb24+nUdTpa0ncPtIS1v8pRdG4pPeaI4yolWXJ4pJ6I1rHyxPbB8TGjdE6nk+bng2IylsmJQnjCdnpu5VFXSudiYUGiP5aahFLbx1LB9vkT/KGkNTj3znQ9gRDHYRhC+MLwXQfJkXBZI472aGPr8AUfzNM=","DQ":"TVPHHGNmBv0wz+961+4rmVCDHjPn8KJJezPISBTfZYD0wCHpkGi16WKJj3I9m7hWvOudqS2+YDz++4v1ZutwORDOTcmtK5lPRqYCyRxO1cL3Y96eI4g+HlnJm/ooYENHId4vku/lb+LLpmqQyVk9eMxFRey96zj8coNfzknb4DU=","Exponent":"AQAB","InverseQ":"wOlwiaJzay6TtjuuTZPXki+TblpHi9t9pqb0cThFo83w2lzyvxt5eVZmbOP5U+la+27AynT8gsc5j2JEpp6XblYn5OvY40rP4PslFTK4nA9S3FUk3tikNVG2IhZFm821MbjQdsHoDjy8f2nX6I2kQ1S8aPvNM2K/zHLvkpJiEV4=","Modulus":"zt/uqPKappDHazOYIEkec47NiQU6k7k2G4qT/o8aQIwOcc9M+Z/l35K2fE3g5LbhpjlqkExGj0hVuC8EImBAIBgIsbif4/WGNkYEPrm7IIaHfUg4Cxwj6WMVluoHsf011XEmD0LD/o7P8QILduKgm68FyBu+GaHK1l9xYgxq64f2O0LP2ulm0tz3K7PmMJJ6fLGYq7lb59B6dBWMEJmXszDtPuUlN1UDuCwogeHF01mYSxMgKZfezXcPnJ0NovFY7xKkFw7U5/JFbilKqKrkTGXHCJQgnrishXsKPmEtzZoFuqMBZyMsQGYF/kH8zMhggQeN/OG/OOqPxWTkSPyV0Q==","P":"1PS6XYRmNiW9DoC8CfTCOTc3kLEM1HlpGBvTsnn53lETBq2RBPDiaZBPm3UxR6J9BUF6bTNi8GMYQpnOh3oVDKHqZXEstH/M2NtxT5P/rjarNiHoaOpb7Wm/zP514118gkvh6/JOxNCBWlj3dA3OR6iAOt56WzovkEergCX5phs=","Q":"+LCI4kIcBPcHH+Mw9iN4hNAXgEBlw3n1d1XLvO4uAkQEVc+HoSfz91zS+b3IjF+bXVG22Hh+mvbE8AhAwi13OZ/2vH0PUTXhGHaCFj/eDouCXBVujW8mMpnQyXNNvhE6bipHUbm0XuAcQYEB7v2ZKc4TxqO2olhJG5w7aq1XIoM="}}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MvcClient.Controllers
{
public class HomeController : Controller
{
private readonly IHttpClientFactory _httpClientFactory;
public HomeController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public IActionResult Index()
{
return View();
}
[Authorize]
public async Task<IActionResult> Secret()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var idToken = await HttpContext.GetTokenAsync("id_token");
var refreshToken = await HttpContext.GetTokenAsync("refresh_token");
var claims = User.Claims.ToList();
var _accessToken = new JwtSecurityTokenHandler().ReadJwtToken(accessToken);
var _idToken = new JwtSecurityTokenHandler().ReadJwtToken(idToken);
var result = await GetSecret(accessToken);
await RefreshAccessToken();
return View();
}
public async Task<string> GetSecret(string accessToken)
{
var apiClient = _httpClientFactory.CreateClient();
apiClient.SetBearerToken(accessToken);
var response = await apiClient.GetAsync("https://localhost:44337/secret");
var content = await response.Content.ReadAsStringAsync();
return content;
}
private async Task RefreshAccessToken()
{
var serverClient = _httpClientFactory.CreateClient();
var discoveryDocument = await serverClient.GetDiscoveryDocumentAsync("https://localhost:44305/");
var accessToken = await HttpContext.GetTokenAsync("access_token");
var idToken = await HttpContext.GetTokenAsync("id_token");
var refreshToken = await HttpContext.GetTokenAsync("refresh_token");
var refreshTokenClient = _httpClientFactory.CreateClient();
var tokenResponse = await refreshTokenClient.RequestRefreshTokenAsync(
new RefreshTokenRequest
{
Address = discoveryDocument.TokenEndpoint,
RefreshToken = refreshToken,
ClientId = "client_id_mvc",
ClientSecret = "client_secret_mvc"
});
var authInfo = await HttpContext.AuthenticateAsync("Cookie");
authInfo.Properties.UpdateTokenValue("access_token", tokenResponse.AccessToken);
authInfo.Properties.UpdateTokenValue("id_token", tokenResponse.IdentityToken);
authInfo.Properties.UpdateTokenValue("refresh_token", tokenResponse.RefreshToken);
await HttpContext.SignInAsync("Cookie", authInfo.Principal, authInfo.Properties);
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="IdentityModel" Version="4.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.1.4" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.3" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace MvcClient
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:63627",
"sslPort": 44349
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"MvcClient": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MvcClient
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(config=> {
config.DefaultScheme = "Cookie";
config.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookie")
.AddOpenIdConnect("oidc",config=> {
config.Authority = "https://localhost:44325/";
config.ClientId = "client_id_mvc";
config.ClientSecret = "client_secret_mvc";
config.SaveTokens = true;
config.ResponseType = "code";
//two trips to load claims in to the cookie
config.GetClaimsFromUserInfoEndpoint = true;
//configure scope
config.Scope.Add("rc.scope");
} );
services.AddHttpClient();
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}

@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>

@{
ViewData["Title"] = "Secret";
}
<h1>Secret</h1>
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment