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

feat: Add ConsoleApp and MvcApp samples #2

Merged
merged 3 commits into from
May 12, 2022
Merged
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
43 changes: 43 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: Build

on: [push, pull_request]

jobs:
build:
runs-on: windows-latest

steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0

- name: Setup .NET SDK
uses: actions/setup-dotnet@v1
with:
dotnet-version: |
3.1.x
5.0.x
6.0.x
7.0.x
include-prerelease: true

- name: Check .NET info
run: dotnet --info

- name: Install dependencies
run: dotnet restore

- name: Build solution
run: dotnet build -c Release --no-restore

- name: Test solution
run: dotnet test -c Release --no-build --no-restore --results-directory test-results --verbosity normal --collect:"XPlat Code Coverage" `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=json,cobertura,lcov,teamcity,opencover

- name: Upload test results artefacts
if: github.repository_owner == 'casdoor' && github.event_name == 'push'
uses: actions/upload-artifact@v1.0.0
with:
name: "drop-ci-test-results"
path: './test-results'
48 changes: 15 additions & 33 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,27 @@
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
*.DotSettings
*.Development.json

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Mono auto generated files
mono_crash.*

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/

# Visual Studio 2015/2017 cache/options directory
.vs/
Expand All @@ -43,10 +38,9 @@ Generated\ Files/
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUnit
# NUNIT
*.VisualState.xml
TestResult.xml
nunit-*.xml

# Build Results of an ATL Project
[Dd]ebugPS/
Expand All @@ -67,7 +61,7 @@ StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*_i.h
*.ilk
*.meta
*.obj
Expand All @@ -84,7 +78,6 @@ StyleCopReport.xml
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
Expand Down Expand Up @@ -127,6 +120,9 @@ _ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding add-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

Expand Down Expand Up @@ -184,8 +180,6 @@ PublishScripts/

# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
Expand All @@ -210,14 +204,12 @@ BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
!*.[Cc]ache/

# Others
ClientBin/
Expand Down Expand Up @@ -261,9 +253,6 @@ ServiceFabricBackup/
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl

# Microsoft Fakes
FakesAssemblies/
Expand Down Expand Up @@ -299,8 +288,12 @@ paket-files/
# FAKE - F# Make
.fake/

# CodeRush personal settings
.cr/personal
# JetBrains Rider
.idea/
*.sln.iml

# CodeRush
.cr/

# Python Tools for Visual Studio (PTVS)
__pycache__/
Expand Down Expand Up @@ -336,15 +329,4 @@ ASALocalRun/

# MFractors (Xamarin productivity tool) working folder
.mfractor/

# Local History for Visual Studio
.localhistory/

# BeatPulse healthcheck temp database
healthchecksdb

# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/

# Ionide (cross platform F# VS Code tools) working folder
.ionide/
opencoverCoverage.xml
22 changes: 22 additions & 0 deletions Casdoor.SDK.Samples.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MvcApp", "MvcApp\MvcApp.csproj", "{BBE14F00-34BC-4D12-8D61-3EB9D7B631AD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp", "ConsoleApp\ConsoleApp.csproj", "{8A1E8031-9518-4AB3-BB3F-825B9F68D349}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BBE14F00-34BC-4D12-8D61-3EB9D7B631AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BBE14F00-34BC-4D12-8D61-3EB9D7B631AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BBE14F00-34BC-4D12-8D61-3EB9D7B631AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BBE14F00-34BC-4D12-8D61-3EB9D7B631AD}.Release|Any CPU.Build.0 = Release|Any CPU
{8A1E8031-9518-4AB3-BB3F-825B9F68D349}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8A1E8031-9518-4AB3-BB3F-825B9F68D349}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8A1E8031-9518-4AB3-BB3F-825B9F68D349}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8A1E8031-9518-4AB3-BB3F-825B9F68D349}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
15 changes: 15 additions & 0 deletions ConsoleApp/ConsoleApp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Casdoor.Client" Version="1.0.0-preview.2" />
</ItemGroup>

</Project>
40 changes: 40 additions & 0 deletions ConsoleApp/ConsoleExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Text.Json;

namespace ConsoleApp;

public static class ConsoleExtension
{
private static readonly JsonSerializerOptions _jsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};

public static void WriteLine(string text, ConsoleColor color = ConsoleColor.Black)
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}

public static void JsonWriteLine(object obj, ConsoleColor color = ConsoleColor.Black)
{
Console.ForegroundColor = color;
Console.WriteLine(JsonSerializer.Serialize(obj, _jsonSerializerOptions));
Console.ResetColor();
}
}
61 changes: 61 additions & 0 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using Casdoor.Client;
using ConsoleApp;
using Microsoft.IdentityModel.Logging;

var httpClient = new HttpClient();
var options = new CasdoorOptions
{
// Require: Basic options
Endpoint = "https://door.casdoor.com",
OrganizationName = "build-in",
ApplicationName = "app-build-in",
ApplicationType = "native", // webapp, webapi or native
ClientId = "541738959670d221d59d",
ClientSecret = "66863369a64a5863827cf949bab70ed560ba24bf",

// Optional: The callback path that the client will be redirected to
// after the user has authenticated. default is "/casdoor/signin-callback"
CallbackPath = "/callback",
// Optional: Whether require https for casdoor endpoint
RequireHttpsMetadata = true,
// Optional: The scopes that the client is requesting.
Scope = "openid profile email"

// More options can be found at README.md
// https://github.com/casdoor/casdoor-dotnet-sdk/blob/master/README.md
};

var client = new CasdoorClient(httpClient, options);

// If you want look PII in logs or exception, you can set the following
IdentityModelEventSource.ShowPII = true;

var configuration = await options.GetOpenIdConnectConfigurationAsync();
ConsoleExtension.WriteLine("Auto fetching OpenIdConnectConfiguration...");
ConsoleExtension.JsonWriteLine(new
{
configuration.Issuer,
configuration.JwksUri,
configuration.TokenEndpoint,
configuration.AuthorizationEndpoint,
configuration.UserInfoEndpoint,
}, ConsoleColor.DarkBlue);

var token = await client.RequestPasswordTokenAsync("admin", "123");
ConsoleExtension.WriteLine("Get tokens by username and password...");
if (token.IsError is false)
{
ConsoleExtension.JsonWriteLine(new
{
token.AccessToken,
token.RefreshToken,
token.IdentityToken,
token.Scope,
token.ExpiresIn,
token.TokenType,
}, ConsoleColor.DarkGreen);
}
else
{
ConsoleExtension.WriteLine(token.Error, ConsoleColor.Red);
}
36 changes: 36 additions & 0 deletions MvcApp/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Diagnostics;
using Casdoor.Client;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web;
using MvcApp.Models;

namespace MvcApp.Controllers;

[Authorize]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}

[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
}
}
8 changes: 8 additions & 0 deletions MvcApp/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace MvcApp.Models;

public class ErrorViewModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
17 changes: 17 additions & 0 deletions MvcApp/MvcApp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>aspnet-MvcApp-1A63ACA3-B056-4958-9C9E-A77B03279C97</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Casdoor.AspNetCore" Version="1.0.0-preview.2" />
<PackageReference Include="Casdoor.Client" Version="1.0.0-preview.2" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.16.0" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="1.16.0" />
</ItemGroup>

</Project>
Loading