1 Commits

Author SHA1 Message Date
8ce99cba13 encryption failed à la restauration depuis Nuget.org ++ 2020-09-11 03:31:45 +01:00
3521 changed files with 84304 additions and 586019 deletions

View File

@ -35,10 +35,3 @@ indent_style = space
indent_size = 2
dotnet_naming_rule.locals_should_be_camel_case.severity = none
dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters
dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style
dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local
dotnet_naming_style.camel_case_style.capitalization = camel_case

View File

@ -1,53 +0,0 @@
# This workflow will build a .NET project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net
name: Dotnet build and test
on:
workflow_dispatch:
inputs:
logLevel:
description: 'Log level'
required: true
default: 'warning'
type: choice
options:
- info
- warning
- debug
tags:
description: 'Test scenario tags'
required: false
type: boolean
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
log-the-inputs:
runs-on: ubuntu-latest
steps:
- run: |
echo "Log level: $LEVEL"
echo "Tags: $TAGS"
echo "Environment: $ENVIRONMENT"
env:
LEVEL: ${{ inputs.logLevel }}
TAGS: ${{ inputs.tags }}
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --verbosity normal

19
.gitignore vendored
View File

@ -5,14 +5,14 @@
.gitignore
.paket/
.vscode/
.vs/
.sass-cache/
.private/
.dnx/
/out
bin
obj
bower_components
project.lock.json
node_modules/
private/
@ -21,24 +21,17 @@ RSA-Params.json
appsettings.*.json
omnisharp.json
DataProtection/
/packages/
/src/Yavsc/Avatars-*/
/src/Yavsc/Blog-*/
/src/Yavsc/Bills-*/
/src/Yavsc/AppData*/
/src/Yavsc/Temp-*/
/src/Yavsc/*-Avatars/
/src/Yavsc/bower_components/
/src/Yavsc/Data-Dev/
/src/Yavsc/AppData*/
/src/test/testingrepo/
connectionsettings.Development.json
appsettings.Development.json
/src/Yavsc/web.log
/yavscd
builds/
/test/yavscTests/test-results.xml
/test/yavscTests/test-results.html
/binaries/Debug/yavscd
yavsc-pre
yavscd

4
.nuget/packages.config Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Machine.Specifications.Runner.Console" version="0.9.0" />
</packages>

16
.travis.yml Normal file
View File

@ -0,0 +1,16 @@
language: csharp
os: linux
mono:
- beta
sudo: false
install:
- curl --insecure -sSL https://lua.pschneider.fr/files/Paul/pub/dnx-install.sh | bash
- DNX_USER_HOME=`pwd -P`/dnx . ./dnx/dnvm/dnvm.sh
- cd src/OAuth.AspNet.Token && dnu restore
- cd ../OAuth.AspNet.AuthServer && dnu restore
- cd ../Yavsc.Abstract && dnu restore
- cd ../Yavsc.Server && dnu restore
- cd ../Yavsc && dnu restore
script:
- "dnu build"

134
.vscode/launch.json vendored
View File

@ -1,134 +0,0 @@
{
// Utilisez IntelliSense pour en savoir plus sur les attributs possibles.
// Pointez pour afficher la description des attributs existants.
// Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "C#: sampleWebAsWebApiClient Debug",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/sampleWebAsWebApiClient/sampleWebAsWebApiClient.csproj"
},
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/<target-framework>/<project-name.dll>",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
/* {
"name": ".NET Core Launch (web-client)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/src/sampleWebAsWebApiClient/bin/Debug/net8.0/sampleWebAsWebApiClient.dll>",
"args": [],
"cwd": "${workspaceFolder}/src/sampleWebAsWebApiClient",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Launch (Api)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build-webapi",
"program": "${workspaceFolder}/src/Api/bin/Debug/net8.0/Api.dll",
"args": [],
"cwd": "${workspaceFolder}/src/Api",
"stopAtEntry": false,
"console": "internalConsole"
},
*/
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/src/Yavsc/bin/Debug/net9.0/Yavsc.dll",
"args": [],
"cwd": "${workspaceFolder}/src/Yavsc",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": "webApi",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/Api/Api.csproj"
},
{
"name": "webClient",
"type": "dotnet",
"request": "launch",
//"projectPath": "${workspaceFolder}/src/Yavsc/Yavsc.csproj",
"projectPath": "${workspaceFolder}/src/sampleWebAsWebApiClient/sampleWebAsWebApiClient.csproj",
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
}
},
{
"name": "web",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/Yavsc/Yavsc.csproj",
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"presentation": {
"hidden": false,
"group": "run",
"order": 1
}
},
{
"name": "web core",
"type": "coreclr",
"request": "launch",
"program": "${workspaceFolder}/src/Yavsc/bin/Debug/net8.0/Yavsc.dll",
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"cwd": "${workspaceFolder}/src/Yavsc",
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
}
}
]
}

16
.vscode/settings.json vendored
View File

@ -1,16 +0,0 @@
{
"dotnet-test-explorer.testProjectPath": "test/**/*Tests.csproj",
"cSpell.words": [
"appsettings",
"Cratie",
"Newtonsoft",
"Npgsql",
"Yavsc"
],
"cSpell.dictionaries": [
"fr"
],
"cSpell.reportUnknownWords": true,
"cSpell.language": "fr,fr-FR,en,en-GB"
}

100
.vscode/tasks.json vendored
View File

@ -1,100 +0,0 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary;ForceNoAlign",
],
"group": "build",
"isBuildCommand": true,
"isTestCommand": false,
"problemMatcher": "$msCompile"
},
{
"label": "build-web",
"type": "process",
"problemMatcher": ["$msCompile"],
"command": "dotnet",
"args": [
"build"
],
"options": {
"cwd": "src/Yavsc"
},
"group": {
"kind": "build"
},
"isBackground": true
},
{
"label": "build-webapi",
"type": "process",
"problemMatcher": ["$msCompile"],
"command": "dotnet",
"args": [
"build"
],
"options": {
"cwd": "src/Api"
},
"group": {
"kind": "build"
},
"isBackground": true
},
{
"label": "build-webclient",
"type": "process",
"problemMatcher": ["$msCompile"],
"command": "dotnet",
"args": [
"build"
],
"runOptions": {
},
"options": {
"cwd": "src/sampleWebAsWebApiClient"
},
"group": {
"kind": "build"
},
"isBackground": true,
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
}
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary;ForceNoAlign"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run"
],
"problemMatcher": "$msCompile"
}
]
}

View File

@ -1,50 +0,0 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="AsciiDocNet" Version="1.0.0" />
<PackageVersion Include="bootstrap" Version="5.3.7" />
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
<PackageVersion Include="Google.Apis.Calendar.v3" Version="1.69.0.3746" />
<PackageVersion Include="Google.Apis.Compute.v1" Version="1.70.0.3829" />
<PackageVersion Include="HigginsSoft.IdentityServer8" Version="8.0.5-preview-net9" />
<PackageVersion Include="HigginsSoft.IdentityServer8.AspNetIdentity" Version="8.0.5-preview-net9" />
<PackageVersion Include="IdentityModel.AspNetCore" Version="4.3.0" />
<PackageVersion Include="MailKit" Version="4.13.0" />
<PackageVersion Include="Microsoft.AspNetCore.Antiforgery" Version="2.3.0" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.Google" Version="9.0.7" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.7" />
<PackageVersion Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="9.0.7" />
<PackageVersion Include="Microsoft.AspNetCore.Hosting" Version="2.3.0" />
<PackageVersion Include="Microsoft.AspNetCore.Http.Features" Version="5.0.17" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.7" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.UI" Version="9.0.7" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="9.0.7" />
<PackageVersion Include="Microsoft.AspNetCore.Razor" Version="2.3.0" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR" Version="1.2.0" />
<PackageVersion Include="Microsoft.AspNetCore.StaticFiles" Version="2.3.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.7" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.7" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.7" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="9.0.7" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="9.0.7" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.7" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageVersion Include="Microsoft.Playwright" Version="1.53.0" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0" />
<PackageVersion Include="MimeKit" Version="4.13.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageVersion Include="PayPalMerchantSDK" Version="2.16.250" />
<PackageVersion Include="pazof.rules" Version="1.1.3" />
<PackageVersion Include="popper.js" Version="1.16.1" />
<PackageVersion Include="RazorEngine.NetCore" Version="3.1.0" />
<PackageVersion Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.10" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="9.0.3" />
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="9.0.7" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.2" />
</ItemGroup>
</Project>

View File

@ -8,12 +8,12 @@ In this doc, let's say, `FreeField`
### A domain name
Wait ... `pschneider.fr`
Wait ... `freefield.pschneider.fr`
You'll have to see with your provider, in order to power it, and make it point to your host ip, at least concerning the ports 80 & 443.
### A Postgresql db
### An Npgsql db
The database must be created, and we need its connection string, allowed to modify the data dictionary
The database must be created, and we need its connection string, allowed to modify the dd
### A mailling service
@ -24,3 +24,5 @@ You'll need to send e-mail ... using smtp and the provider of your choice.
I'll have to make with it, a least a moment, it needs a *service account*, and some setup,
in the `appsettings.*.json` file, and
the execution environment variable GOOGLE_APPLICATION_CREDENTIALS to a value pointing the json description file for the Google Service account.

237
LICENSE
View File

@ -1,14 +1,231 @@
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
Preamble
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
The GNU General Public License is a free, copyleft license for software and other kinds of works.
0. You just DO WHAT THE FUCK YOU WANT TO.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' aVVnd authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,35 +1,58 @@
LIBS:=$(shell ls private/lib/*.dll)
MONO_PREFIX=/home/paul/mono46
DNX_USER_HOME=/home/paul/.dnx
DNXLIBS=Microsoft.Dnx.Host.Mono.dll Microsoft.Dnx.Host.dll Microsoft.Dnx.ApplicationHost.dll Microsoft.Dnx.Loader.dll Microsoft.Dnx.Compilation.Abstractions.dll Microsoft.Dnx.Compilation.CSharp.Abstractions.dll Microsoft.CodeAnalysis.dll Microsoft.CodeAnalysis.CSharp.dll Microsoft.Dnx.Compilation.CSharp.Common.dll Microsoft.Dnx.Compilation.CSharp.dll Microsoft.Dnx.Compilation.dll Microsoft.Dnx.Runtime.dll Microsoft.Dnx.Runtime.Internals.dll Microsoft.Extensions.PlatformAbstractions.dll System.Collections.Immutable.dll System.Reflection.Metadata.dll
DNXLIBFP:=$(addprefix $(DNX_USER_HOME)/runtimes/dnx-mono.1.0.0-rc1-update2/bin/, $(DNXLIBS))
CONFIG=Debug
FRAMEWORK=net8.0
DESTDIR=/tmp/yavsc
git_status := $(shell git status -s --porcelain |wc -l)
clean:
dotnet clean
rm -f src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/Yavsc.Abstract.dll src/OAuth.AspNet.Token/bin/$(CONFIG)/dnx451/OAuth.AspNet.Token.dll src/OAuth.AspNet.AuthServer/bin/$(CONFIG)/dnx451/OAuth.AspNet.AuthServer.dll src/Yavsc.Server/bin/$(CONFIG)/dnx451/Yavsc.Server.dll src/Yavsc/bin/$(CONFIG)/dnx451/Yavsc.dll
src/Yavsc/bin/output/wwwroot:
dotnet --project src/Yavsc/Yavsc.csproj publish
checklibs:
ls $(DNXLIBFP)
test:
dotnet test
make -C src/test
web:
dotnet watch -p:Configuration=$(CONFIG) --project src/Yavsc/Yavsc.csproj
make -C src/Yavsc web
src/Yavsc.Abstract/bin/$(CONFIG)/$(FRAMEWORK)/Yavsc.Abstract.dll:
dotnet build -p:Configuration=$(CONFIG) --project src/Yavsc.Abstract/Yavsc.Abstract.csproj
pushInPre: yavscd
make -C src/Yavsc pushInPre
src/Yavsc.Server/bin/$(CONFIG)/$(FRAMEWORK)/Yavsc.Server.dll:
dotnet build -p:Configuration=$(CONFIG) --project src/Yavsc.Server/Yavsc.Server.csproj
pushInProd: yavscd
make -C src/Yavsc pushInProd
src/Yavsc/bin/$(CONFIG)/$(FRAMEWORK)/Yavsc.dll:
dotnet build -p:Configuration=$(CONFIG) --project src/Yavsc/Yavsc.csproj
packages:
make -C src/Yavsc.Abstract pack
findResources:
find src -name "*.resx" |sort
prepare_all_code:
make -C src/Yavsc.Abstract prepare_code
make -C src/Yavsc.Server prepare_code
make -C src/Yavsc prepare_code
publish:
dotnet publish src/Yavsc/Yavsc.csproj -c Release -o $(DESTDIR)/srv/www/yavsc
src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/Yavsc.Abstract.dll: prepare_all_code
make -C src/Yavsc.Abstract CONFIGURATION=$(CONFIG)
install: publish
chown -R www-data $(DESTDIR)/srv/www/yavsc
chgrp -R www-data $(DESTDIR)/srv/www/yavsc
src/OAuth.AspNet.Token/bin/$(CONFIG)/dnx451/OAuth.AspNet.Token.dll: prepare_all_code
make -C src/OAuth.AspNet.Token CONFIGURATION=$(CONFIG)
.PHONY:
src/OAuth.AspNet.AuthServer/bin/$(CONFIG)/dnx451/OAuth.AspNet.AuthServer.dll: prepare_all_code
make -C src/OAuth.AspNet.AuthServer CONFIGURATION=$(CONFIG)
src/Yavsc.Server/bin/$(CONFIG)/dnx451/Yavsc.Server.dll: src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/Yavsc.Abstract.dll prepare_all_code
make -C src/Yavsc.Server CONFIGURATION=$(CONFIG)
src/Yavsc/bin/$(CONFIG)/dnx451/Yavsc.dll: src/Yavsc.Server/bin/$(CONFIG)/dnx451/Yavsc.Server.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/Yavsc.Abstract.dll src/OAuth.AspNet.AuthServer/bin/$(CONFIG)/dnx451/OAuth.AspNet.AuthServer.dll src/OAuth.AspNet.Token/bin/$(CONFIG)/dnx451/OAuth.AspNet.Token.dll
make -C src/Yavsc CONFIGURATION=$(CONFIG)
yavscd: src/Yavsc/bin/$(CONFIG)/dnx451/Yavsc.dll src/Yavsc.Server/bin/$(CONFIG)/dnx451/Yavsc.Server.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/Yavsc.Abstract.dll src/OAuth.AspNet.AuthServer/bin/$(CONFIG)/dnx451/OAuth.AspNet.AuthServer.dll src/OAuth.AspNet.Token/bin/$(CONFIG)/dnx451/OAuth.AspNet.Token.dll
mkbundle --static $(DNXLIBS) src/Yavsc/bin/$(CONFIG)/dnx451/Yavsc.dll src/Yavsc/bin/$(CONFIG)/dnx451/pt/Yavsc.resources.dll src/Yavsc/bin/$(CONFIG)/dnx451/en/Yavsc.resources.dll src/Yavsc.Server/bin/$(CONFIG)/dnx451/Yavsc.Server.dll src/Yavsc.Server/bin/$(CONFIG)/dnx451/en/Yavsc.Server.resources.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/Yavsc.Abstract.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/en/Yavsc.Abstract.resources.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/pt/Yavsc.Abstract.resources.dll src/OAuth.AspNet.AuthServer/bin/$(CONFIG)/dnx451/OAuth.AspNet.AuthServer.dll src/OAuth.AspNet.Token/bin/$(CONFIG)/dnx451/OAuth.AspNet.Token.dll $(LIBS) -L $(DNX_USER_HOME)/runtimes/dnx-mono.1.0.0-rc1-update2/bin --machine-config $(MONO_PREFIX)/etc/mono/4.5/machine.config -o yavscd
strip yavscd
.PHONY: packages

View File

@ -1,6 +1,4 @@
[![pipeline status](http://gitlab.pschneider.fr/Paul/yavsc/badges/vnext/pipeline.svg)](http://gitlab.pschneider.fr/Paul/yavsc/-/commits/vnext)
[![Build Status](https://travis-ci.org/pazof/yavsc.svg?branch=vnext)](https://travis-ci.org/pazof/yavsc)
# [Yavsc](https://yavsc.pschneider.fr)
@ -11,36 +9,78 @@ C'est une application mettant en oeuvre une prise de contact entre un demandeur
## Construction
```bash
dotnet build
```
Le code est du c sharp, dont les librairies sont restorées et le tout compilé avec les librairies DNX de M$, téléchargeable en executant le script d'installation suivant (c.f. `/.travis.yml`):
curl --insecure -sSL https://lua.pschneider.fr/files/Paul/dnx-install.sh | bash && DNX_USER_HOME=`pwd -P`/dnx . ./dnx/dnvm/dnvm.sh && cd Yavsc && dnu restore
Une fois l'environnement ainsi pollué, executer, depuis le sous dossier `Yavsc`:
dnu build
L'utilisation du serveur web, avec un runtime Mono, échoura dans ses version récentes (à peu près supérieure ou égale à 4.7).
La version 4.6.2 de mono convient:
[monoperso] ~/workspace/yavsc/Yavsc @ mono --version
Mono JIT compiler version 4.6.2 (Stable 4.6.2.7/08fd525 jeudi 18 janvier 2018, 13:10:54 (UTC+0100))
TLS: __thread
SIGSEGV: altstack
Notifications: epoll
Architecture: amd64
Disabled: none
Misc: softdebug
LLVM: supported, not enabled.
GC: sgen
et, pour execution en environement de développement
```bash
~/workspace/yavsc/Yavsc @ ASPNETCORE_ENV=Development dotnet run
```
[monoperso] ~/workspace/yavsc/Yavsc @ ASPNET_ENV=Development dnx web
warn: Yavsc.Startup[0]
AppData was not found in environment variables
warn: Yavsc.Startup[0]
It has been set to : /home/paul/workspace/yavsc/Yavsc/AppDataDevelopment
Hosting environment: Development
Now listening on: http://*:5000
Application started. Press Ctrl+C to shut down.
Si vous êtes arrivé jusqu'ici, vous devriez pouvoir visiter la home page
[ici](http://localhost:5000).
## Tests
Utilisez GNU/Makefile (et visitez le code, dans le dossier `test` ):
[TODO] Depuis le répertoire racine:
Depuis le répertoire racine:
```bash
```
make test
```
## Installation / Déploiment / Développement
## Installation / Déploiment / Développement
### les services et l'API
### les services kestrel et kestrel-pre
[TODO]
### la configuration Apache 2
[TODO]
### la mise en pré-production
Pour déployer le tout en production, on peut d'abord déployer en "pré-production",
Afin de pouvoir tester manuellement quelque dernier développement :
```
cd Yavsc
make pushInPre # arrete kestrel-pre, pousse tout dans DESTDIR=/srv/www/yavscpre avec rsync,
# et redemarre kestrel-pre
```
### La Prod
`cd srv/Yavsc` : `make pushInProd CONFIGURATION=Release`.
puis, pour une première installation
`make install_service`.
Une fois sûr de vous, et une fois que Git dit propre votre copie de travail, depuis le répertoire `Yavsc`, lancez `make pushInProd`.
## Fonctionalités (encore en cours de développement)

10
SECURITY.md Normal file
View File

@ -0,0 +1,10 @@
# Security Policy
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| 1.0.6 | :x: |
(https://yavsc.pschneider.fr)

View File

@ -6,6 +6,7 @@ Ceci est une grosse liste de fonctionnalités, existantes, ou à implémenter, o
## Jalon 1
☐ Redirection vers la Page d'accueil à la validation du second facteur (evitera l'erreur Anti-forgery token)
☐ Des spécifications détaillées du coeur de l'application
✔ Acces (publique) aux Blogs. @done (August 13th 2016, 0:51)
✔ Accès aux profiles des intervenants. @done (August 13th 2016, 0:57)

View File

@ -1,165 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<xsl:text disable-output-escaping="yes"><![CDATA[<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">]]></xsl:text>
<html>
<head>
<title>
xUnit.net Test Results - <xsl:value-of select="@name"/>
</title>
<style type="text/css">
body { font-family: Calibri, Verdana, Arial, sans-serif; background-color: White; color: Black; }
h2,h3,h4,h5 { margin: 0; padding: 0; }
h3 { font-weight: normal; }
h5 { font-weight: normal; font-style: italic; margin-bottom: 0.75em; }
pre { font-family: Consolas; font-size: 85%; margin: 0 0 0 1em; padding: 0; }
.divided { border-top: solid 1px #f0f5fa; padding-top: 0.5em; }
.row, .altrow { padding: 0.1em 0.3em; }
.row { background-color: #f0f5fa; }
.altrow { background-color: #e1ebf4; }
.success, .failure, .skipped { font-family: Arial Unicode MS; font-weight: normal; float: left; width: 1em; display: block; }
.success { color: #0c0; }
.failure { color: #c00; }
.skipped { color: #cc0; }
.timing { float: right; }
.indent { margin: 0.25em 0 0.5em 2em; }
.indenttest { margin: 0.25em 0 0.5em 1em; }
.clickable { cursor: pointer; }
.testcount { font-size: 85%; }
</style>
<script language="javascript">
function ToggleClass(id) {
var elem = document.getElementById(id);
if (elem.style.display == "none") {
elem.style.display = "block";
}
else {
elem.style.display = "none";
}
}
function EnsureBlock(id) {
var elem = document.getElementById(id);
if (elem.style.display == "none") {
elem.style.display = "block";
}
}
</script>
</head>
<body>
<h3 class="divided"><b>Assemblies Run</b></h3>
<xsl:apply-templates select="//assembly"/>
<h3 class="divided"><b>Summary</b></h3>
<div>
Tests run: <a href="#all"><b><xsl:value-of select="sum(//assembly/@total)"/></b></a> &#160;
Failures: <a href="#failures"><b><xsl:value-of select="sum(//assembly/@failed)"/></b></a>,
Skipped: <a href="#skipped"><b><xsl:value-of select="sum(//assembly/@skipped)"/></b></a>,
Run time: <b><xsl:value-of select="sum(//assembly/@time)"/>s</b>
</div>
<xsl:if test="//assembly/collection/test[@result='Fail']">
<br />
<h2><a name="failures"></a>Failed tests</h2>
<xsl:apply-templates select="//assembly/collection/test[@result='Fail']"><xsl:sort select="@name"/></xsl:apply-templates>
</xsl:if>
<xsl:if test="//assembly/collection/failure">
<br />
<h2><a name="failures"></a>Failed fixtures</h2>
<xsl:apply-templates select="//assembly/collection/failure"><xsl:sort select="../@name"/></xsl:apply-templates>
</xsl:if>
<xsl:if test="//assembly/@skipped > 0">
<br />
<h2><a name="skipped"></a>Skipped tests</h2>
<xsl:apply-templates select="//assembly/collection/test[@result='Skip']"><xsl:sort select="@name"/></xsl:apply-templates>
</xsl:if>
<br />
<h2><a name="all"></a>All tests</h2>
<h5>Click test collection name to expand/collapse test details</h5>
<xsl:apply-templates select="//assembly/collection"><xsl:sort select="@name"/></xsl:apply-templates>
</body>
</html>
</xsl:template>
<xsl:template match="assembly">
<div><xsl:value-of select="@name"/></div>
</xsl:template>
<xsl:template match="test">
<div>
<xsl:attribute name="class"><xsl:if test="(position() mod 2 = 0)">alt</xsl:if>row</xsl:attribute>
<xsl:if test="@result!='Skip'"><span class="timing"><xsl:value-of select="@time"/>s</span></xsl:if>
<xsl:if test="@result='Skip'"><span class="timing">Skipped</span><span class="skipped">&#x2762;</span></xsl:if>
<xsl:if test="@result='Fail'"><span class="failure">&#x2718;</span></xsl:if>
<xsl:if test="@result='Pass'"><span class="success">&#x2714;</span></xsl:if>
<span class="clickable">
<xsl:attribute name="onclick">ToggleClass('test<xsl:value-of select="generate-id()"/>')</xsl:attribute>
&#160;<xsl:value-of select="@name"/>
</span>
<div >
<xsl:if test="@result='Pass'"><xsl:attribute name="style">display: none;</xsl:attribute></xsl:if>
<xsl:attribute name="id">test<xsl:value-of select="generate-id()"/></xsl:attribute>
<xsl:if test="child::node()/message"> : <xsl:value-of select="child::node()/message"/></xsl:if>
<br clear="all" />
<xsl:if test="failure/stack-trace">
<pre><xsl:value-of select="failure/stack-trace"/></pre>
</xsl:if>
<xsl:if test="output">
<h4>Output</h4>
<pre><xsl:value-of select="output"/></pre>
</xsl:if>
</div>
</div>
</xsl:template>
<xsl:template match="failure">
<span class="failure">&#x2718;</span> <xsl:value-of select="../@name"/> : <xsl:value-of select="message"/><br clear="all"/>
Stack Trace:<br />
<pre><xsl:value-of select="stack-trace"/></pre>
</xsl:template>
<xsl:template match="collection">
<h3>
<span class="timing"><xsl:value-of select="@time"/>s</span>
<span class="clickable">
<xsl:attribute name="onclick">ToggleClass('collection<xsl:value-of select="generate-id()"/>')</xsl:attribute>
<xsl:attribute name="ondblclick">ToggleClass('collection<xsl:value-of select="generate-id()"/>')</xsl:attribute>
<xsl:if test="@failed > 0"><span class="failure">&#x2718;</span></xsl:if>
<xsl:if test="@failed = 0"><span class="success">&#x2714;</span></xsl:if>
&#160;<xsl:value-of select="@name"/>
&#160;<span class="testcount">(<xsl:value-of select="@total"/>&#160;test<xsl:if test="@total > 1">s</xsl:if>)</span>
</span>
<br clear="all" />
</h3>
<div class="indent">
<xsl:if test="@failed = 0"><xsl:attribute name="style">display: none;</xsl:attribute></xsl:if>
<xsl:attribute name="id">collection<xsl:value-of select="generate-id()"/></xsl:attribute>
<xsl:for-each select="test">
<div class="indent">
<xsl:if test="@result ='Fail'">
<a>
<xsl:attribute name="onclick">EnsureBlock('test<xsl:value-of select="generate-id()"/>')</xsl:attribute>
<xsl:attribute name="href">#test<xsl:value-of select="generate-id()"/></xsl:attribute>
<span class="failure">&#x2718;</span>
<xsl:value-of select="@name"/>
</a>
</xsl:if>
<xsl:if test="@result ='Pass'">
<span class="success">&#x2714;</span>
<xsl:value-of select="@name"/>
</xsl:if>
</div>
</xsl:for-each>
</div>
</xsl:template>
</xsl:stylesheet>

131
contrib/kestrel Executable file
View File

@ -0,0 +1,131 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: kestrel
# Required-Start: $local_fs $network $named $time $syslog $postgresql
# Required-Stop: $local_fs $network $named $time $syslog $postgresql
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: Script to run asp.net 5 application in background
### END INIT INFO
# Author: Ivan Derevianko aka druss <drussilla7@gmail.com>
# Modified by: Paul Schneider <redienhcs.luap@gmail.com>
. /lib/init/vars.sh
. /lib/lsb/init-functions
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
CONFIGS="/etc/kestrel/*.webenv"
TMP_SAVE_runlevel_VAR=$runlevel
unset runlevel
running() {
if [ -f $PIDFILE ]
then
PID=$(cat $PIDFILE)
if kill -0 $PID 2>/dev/null
then
return 0
fi
fi
return 1
}
setdnxenv() {
env=$1
. $env
# reset all except the name to default values
export ASPNET_ENV=$NAME
export WWW_USER=www-data
YAVSCBIN=/usr/local/bin/yavscd
PROJECT=approot/Web
CONFIGURATION=Release
ROOT=/srv/www/yavsc
DESC="$NAME"
PIDFILE=/var/run/kestrel-${NAME}.pid
LOGDIR=/var/log
# reset to specified values
. $env
}
status() {
for env in $CONFIGS
do
setdnxenv "$env"
if running;
then
echo "Service running $DESC ($NAME; pid: $PID)"
else
echo "Service stopped $DESC ($NAME)"
fi
done
}
start() {
# wait a little for postgresql to be available
sleep 1
for env in $CONFIGS
do
setdnxenv "$env"
if running; then
echo "Service already running $DESC" "$NAME"
log_end_msg 0
else
log_daemon_msg "Starting service $NAME for user $WWW_USER"
if ! start-stop-daemon -SbmCv -u $WWW_USER -p $PIDFILE -d $ROOT -g www-data -x $YAVSCBIN -- --project $PROJECT --configuration $CONFIGURATION $NAME > "${LOGDIR}/kestrel-${NAME}.log"
then
log_daemon_msg "Could not start $NAME : $?, see ${LOGDIR}/kestrel-${NAME}.log"
log_end_msg 2
else
log_daemon_msg "Service $DESC started ($NAME), logs: ${LOGDIR}/kestrel-${NAME}.log"
log_end_msg 0
fi
fi
done
}
stop() {
for env in $CONFIGS
do
setdnxenv "$env"
if running
then
log_daemon_msg "Stopping service $NAME"
start-stop-daemon -K -p "$PIDFILE"
log_daemon_msg "$DESC stopped"
log_end_msg 0
else
log_daemon_msg "$DESC Service not running"
log_end_msg 1
fi
done
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
sleep 1
start
;;
status)
status
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
export runlevel=$TMP_SAVE_runlevel_VAR

View File

@ -1,11 +1,11 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: yavsc
# Provides: kestrel-pre
# Required-Start: $local_fs $network $named $time $syslog $postgresql
# Required-Stop: $local_fs $network $named $time $syslog $postgresql
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: Script to run yavsc
# Description: Script to run asp.net 5 application in background
### END INIT INFO
# Author: Ivan Derevianko aka druss <drussilla7@gmail.com>
@ -14,9 +14,8 @@
. /lib/init/vars.sh
. /lib/lsb/init-functions
NAME=yavsc
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
CONFIGS="/etc/kestrel/*.prewebenv"
TMP_SAVE_runlevel_VAR=$runlevel
unset runlevel
@ -34,34 +33,47 @@ running() {
}
export WWW_USER=www-data
export ROOT=/srv/www/${NAME}
export DESC="$NAME"
export PIDFILE=/var/run/kestrel-${NAME}.pid
export LOGDIR=/var/log
export DOTNET_CLI_HOME=$ROOT
export ASPDOTNETCORE_ENVIRONMENT=Production
export ASPDOTNETCORE_LOGLEVEL=Information
setdnxenv() {
env=$1
. $env
# reset all except the name to default values
export ASPNET_ENV=$NAME
export WWW_USER=www-data
YAVSCBIN=/usr/local/bin/yavscd-pre
PROJECT=approot/Web
CONFIGURATION=Release
ROOT=/srv/www/yavscpre
DESC="$NAME"
PIDFILE=/var/run/kestrel-${NAME}.pid
LOGDIR=/var/log
# reset to specified values
. $env
}
status() {
for env in $CONFIGS
do
setdnxenv "$env"
if running;
then
echo "Service running $DESC ($NAME; pid: $PID)"
else
echo "Service stopped $DESC ($NAME)"
fi
echo WWW_USER: $WWW_USER ROOT:$ROOT DESC: $DESC NAME: $NAME PIDFILE: $PIDFILE LOGDIR=$LOGDIR
done
}
start() {
for env in $CONFIGS
do
setdnxenv "$env"
if running; then
echo "Service already running $DESC" "$NAME"
log_end_msg 0
else
cd $ROOT
sleep 4
log_daemon_msg "Starting service $NAME for user $WWW_USER"
if ! start-stop-daemon -SbmCv -u $WWW_USER -p $PIDFILE -d $ROOT -g www-data -x yavsc > "${LOGDIR}/kestrel-${NAME}.log"
if ! start-stop-daemon -SbmCv -u $WWW_USER -p $PIDFILE -d $ROOT -g www-data -x $YAVSCBIN -- --project $PROJECT --configuration $CONFIGURATION $NAME > "${LOGDIR}/kestrel-${NAME}.log"
then
log_daemon_msg "Could not start $NAME : $?, see ${LOGDIR}/kestrel-${NAME}.log"
log_end_msg 2
@ -70,10 +82,14 @@ start() {
log_end_msg 0
fi
fi
done
}
stop() {
for env in $CONFIGS
do
setdnxenv "$env"
if running
then
log_daemon_msg "Stopping service $NAME"
@ -84,6 +100,7 @@ stop() {
log_daemon_msg "$DESC Service not running"
log_end_msg 1
fi
done
}
@ -96,6 +113,7 @@ case "$1" in
;;
restart)
stop
sleep 1
start
;;
status)

View File

@ -1,27 +0,0 @@
[Unit]
Description=Yavsc
After=syslog.target
After=network.target
Wants=postgresql.service
After=postgresql.service
[Service]
RestartSec=5s
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/srv/www/yavsc/
ExecStart=/srv/www/yavsc/Yavsc
Restart=always
Environment="HOME=/srv/www/yavsc"
Environment="ASPNETCORE_ENVIRONMENT=Production"
Environment="ASPNETCORE_ConnectionStrings__DefaultConnection=YOUR Postgresql CONNECTION STRING"
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=yavsc
[Install]
WantedBy=multi-user.target

30
dnx-install.sh Normal file
View File

@ -0,0 +1,30 @@
set -e
# config
export DNX_USER_HOME="`pwd -P`/dnx"
# rt
mkdir -p dnx/runtimes
cd dnx/runtimes
curl --insecure -sSL https://freespeech.pschneider.fr/files/Paul/dnx-mono.1.0.0-rc1-update2.tar.bz2 |tar xj
cd ..
# dnvm
mkdir -p dnvm
cd dnvm
curl --insecure -sSL https://freespeech.pschneider.fr/files/Paul/dnvm.sh >dnvm.sh
cd ..
# alias
mkdir -p alias
echo "dnx-mono.1.0.0-rc1-update2" >alias/default.alias
. dnvm/dnvm.sh
# end
cd ..
echo "DNX a été ressucité dans $DNX_USER_HOME"
echo "Pour utiliser dnx et dnu:"
echo " . ${DNX_USER_HOME}/dnvm/dnvm.sh"

13
global.json Normal file
View File

@ -0,0 +1,13 @@
{
"projects": [
"src",
"scripts",
"tests"
],
"sdk": {
"version": "1.0.0-rc1-update2",
"runtime": "mono",
"architecture": "x64"
},
"packages": "packages"
}

25
omnisharp.json Normal file
View File

@ -0,0 +1,25 @@
{
"dotnet": {
"enabled": false
},
"msbuild": {
"enabled": false
},
"Dnx": {
"enabled": true,
"enablePackageRestore": false,
"projects": "src/*/project.json;*/project.json;project.json;test/*/project.json"
},
"Script": {
"enabled": false
},
"fileOptions": {
"systemExcludeSearchPatterns": [
"**/bin/**/*",
"**/obj/**/*",
"**/node_modules/**/*"
],
"userExcludeSearchPatterns": []
}
}

View File

@ -0,0 +1,78 @@
include versioning.mk
REPO_ROOT=../../../src
SUBDIRS=Yavsc Yavsc.Server Yavsc.Abstract OAuth.AspNet.AuthServer OAuth.AspNet.Token cli test
all: $(SUBDIRS)
Yavsc.Abstract:
$(MAKE) -C $(REPO_ROOT)/Yavsc.Abstract VERSION=$(VERSION)
OAuth.AspNet.Token:
$(MAKE) -C $(REPO_ROOT)/OAuth.AspNet.Token VERSION=$(VERSION)
OAuth.AspNet.AuthServer: OAuth.AspNet.Token
$(MAKE) -C $(REPO_ROOT)/OAuth.AspNet.AuthServer VERSION=$(VERSION)
Yavsc.Server: Yavsc.Abstract
$(MAKE) -C $(REPO_ROOT)/Yavsc.Server VERSION=$(VERSION)
Yavsc: Yavsc.Server OAuth.AspNet.AuthServer OAuth.AspNet.Token
make -C $(REPO_ROOT)/Yavsc VERSION=$(VERSION)
Yavsc-deploy-pkg: Yavsc
make -C $(REPO_ROOT)/Yavsc deploy-pkg
Yavsc.Server-deploy-pkg: Yavsc.Server
make -C $(REPO_ROOT)/Yavsc.Server deploy-pkg
Yavsc.Abstract-deploy-pkg: Yavsc.Abstract
make -C $(REPO_ROOT)/Yavsc.Abstract deploy-pkg
cli-deploy-pkg: cli check
make -C $(REPO_ROOT)/cli deploy-pkg
cli: Yavsc-deploy-pkg Yavsc.Server-deploy-pkg Yavsc.Abstract-deploy-pkg
make -C $(REPO_ROOT)/cli
undoLocalYavscNugetDeploy:
rm -rf ../../../packages/Yavsc.Abstract
rm -rf ../../../packages/Yavsc.Server
rm -rf ../../../packages/Yavsc
rm -rf ~/.dnx/packages/Yavsc.Abstract
rm -rf ~/.dnx/packages/Yavsc.Server
rm -rf ~/.dnx/packages/Yavsc
check: cli
make -C $(REPO_ROOT)/cli check
make -C $(REPO_ROOT)/test
test:
make -C $(REPO_ROOT)/test
pushInPre:
make -C $(REPO_ROOT)/Yavsc pushInPre
pushInProd:
make -C $(REPO_ROOT)/Yavsc pushInProd
deploy-pkgs: Yavsc-deploy-pkg Yavsc.Server-deploy-pkg Yavsc.Abstract-deploy-pkg cli-deploy-pkg
memo:
vim ~/TODO.md
rc-num:
@echo echo 1-alpha1 < $< ^ $^ @ $@
clean:
for subdir in $(SUBDIRS) ; do \
make -C $(REPO_ROOT)/$${subdir} clean ; \
done
watch:
make -C $(REPO_ROOT)/Yavsc watch
.PHONY: all $(SUBDIRS)

76
scripts/build/make/dnx.mk Normal file
View File

@ -0,0 +1,76 @@
# Common defs
#
ifndef PRJNAME
PRJNAME := $(shell basename `pwd -P`)
endif
FRAMEWORK=dnx451
ASPNET_ENV=Development
ASPNET_LOG_LEVEL=Debug
HOSTING=localhost
HOSTADMIN=root
FRAMEWORKALIAS=dnx451
# nuget package destination, at generation time
BINTARGET=$(PRJNAME).dll
BINTARGETPATH=bin/$(CONFIGURATION)/$(FRAMEWORKALIAS)/$(BINTARGET)
PKGFILENAME=$(PRJNAME).$(VERSION).nupkg
dnu=dnu
dnx=ndnx
# OBS SUBDIRS=Yavsc.Server Yavsc.Abstract Yavsc cli
#
# Git commit hash, in order to not publish some uncrontrolled code in production environment
#
git_status := $(shell git status -s --porcelain |wc -l)
all: $(BINTARGETPATH)
restore:
touch project.json
$(dnu) restore --ignore-failed-sources
project.lock.json: project.json
$(dnu) restore --ignore-failed-sources
watch: project.lock.json
MONO_OPTIONS=--debug MONO_MANAGED_WATCHER=enabled ASPNET_ENV=$(ASPNET_ENV) ASPNET_LOG_LEVEL=$(ASPNET_LOG_LEVEL) dnx-watch web --configuration=$(CONFIGURATION)
clean:
rm -rf bin obj
rm project.lock.json
cleanoutput:
rm -rf bin/$(CONFIGURATION)
rm -rf bin/output
$(BINTARGETPATH): project.lock.json rc-num.txt-check
$(dnu) build --configuration=$(CONFIGURATION)
# Default target, from one level sub dirs
bin/output:
@$(dnu) publish
bin/output/wwwroot/version: bin/output
echo $(version) > bin/output/wwwroot/version
# @git log -1 --pretty=format:%h > bin/output/wwwroot/version
pack: $(NUGETSOURCE)/$(PKGFILENAME)
$(NUGETSOURCE)/$(PKGFILENAME): $(BINTARGETPATH) ../../version.txt
ifeq ($(git_status),0)
nuget pack $(PRJNAME).nuspec -Version $(VERSION) -Properties config=$(CONFIGURATION) -OutputDirectory bin
else
$(error Please, commit your changes before publishing your NuGet packages)
endif
deploy-pkg: pack
@mv bin/$(PKGFILENAME) $(NUGETSOURCE)
.PHONY: rc-num.txt-check
# .DEFAULT_GOAL := $(BINTARGETPATH)

View File

@ -0,0 +1,16 @@
MSBUILD=msbuild
MONO=mono
CONFIGURATION=Debug
BINTYPE=exe
PRJNAME := $(shell basename `pwd -P`)
SOLUTIONDIR=$(HOME)/workspace/yavsc
rc_num := $(shell cat $(SOLUTIONDIR)/rc-num.txt)
VERSION=1.0.5-rc$(rc_num)
BINTARGET=$(PRJNAME).$(BINTYPE)
BINTARGETPATH=bin/$(CONFIGURATION)/$(BINTARGET)
NUGETSOURCE=$(HOME)/Nupkgs
PKGFILENAME=$(PRJNAME).$(VERSION).nupkg

View File

@ -0,0 +1,19 @@
ifndef PRJNAME
PRJNAME := $(shell basename `pwd -P`)
endif
SOLUTIONDIR=../..
version := $(shell cat $(SOLUTIONDIR)/version.txt)
MAKE=make
NUGETSOURCE=$(HOME)/Nupkgs
VERSION=$(version)
CONFIGURATION=Debug
version-check:
ifndef version
@echo no version number specification ... please, could you try and run 'echo 1.2.3 > $(SOLUTIONDIR)version.txt' ?.
else
@echo 'Got version number : $(version)'
endif

View File

@ -0,0 +1,145 @@
@inherits Microsoft.Extensions.CodeGeneration.Templating.RazorTemplateBase
@using Microsoft.Extensions.CodeGeneration.EntityFramework
@@model @Model.ViewDataTypeName
@{
if (Model.IsPartialView)
{
}
else if (Model.IsLayoutPageSelected)
{
@:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"];
if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{
@:Layout = "@Model.LayoutPageFile";
}
@:}
@:
@:<h2>@@SR["@Model.ViewName"]</h2>
@:
}
else
{
@:@@{
@:Layout = null;
@:}
@:
@:<!DOCTYPE html>
@:
@:<html>
@:<head>
@:<meta name="viewport" content="width=device-width" />
@:<title>@Model.ViewName</title>
@:</head>
@:<body>
@:
// PushIndent(" ");
}
@:<form asp-action="@Model.ViewName">
@:<div class="form-horizontal">
@:<h4>@@SR["@Model.ViewDataTypeShortName"]</h4>
@:<hr />
@:<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
foreach (var property in Model.ModelMetadata.Properties)
{
if (property.Scaffold && !property.IsAutoGenerated && !property.IsReadOnly)
{
// If the property is a primary key and Guid, then the Guid is generated in the controller. Hence, this propery is not displayed on the view.
if (property.IsPrimaryKey)
{
continue;
}
if (property.IsForeignKey)
{
@:<div class="form-group">
@:<label asp-for="@property.PropertyName" class="col-md-2 control-label"></label>
@:<div class="col-md-10">
@:<select asp-for="@property.PropertyName" class ="form-control"></select>
@:</div>
@:</div>
continue;
}
bool isCheckbox = property.TypeName.Equals("System.Boolean");
if (isCheckbox)
{
@:<div class="form-group">
@:<div class="col-md-offset-2 col-md-10">
@:<div class="checkbox">
@:<input asp-for="@property.PropertyName" />
@:<label asp-for="@property.PropertyName"></label>
@:</div>
@:</div>
@:</div>
}
else if (property.IsEnum && !property.IsEnumFlags)
{
@:<div class="form-group">
@:<label asp-for="@property.PropertyName" class="col-md-2 control-label"></label>
@:<div class="col-md-10">
@:<select asp-for="@property.PropertyName" class="form-control"></select>
@:<span asp-validation-for="@property.PropertyName" class="text-danger" ></span>
@:</div>
@:</div>
}
else
{
@:<div class="form-group">
@:<label asp-for="@property.PropertyName" class="col-md-2 control-label"></label>
@:<div class="col-md-10">
@:<input asp-for="@property.PropertyName" class="form-control" />
@:<span asp-validation-for="@property.PropertyName" class="text-danger" ></span>
@:</div>
@:</div>
}
}
}
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">@@SR["Back to List"]</a>
</div>
@{
if (Model.ReferenceScriptLibraries && (Model.IsLayoutPageSelected || Model.IsPartialView))
{
@:@@section Scripts {
@:<script src="~/lib/jquery/dist/jquery.min.js"></script>
@:<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
@:<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
@:}
}
// The following code closes the tag used in the case of a view using a layout page and the body and html tags in the case of a regular view page
if (!Model.IsPartialView && !Model.IsLayoutPageSelected)
{
if (Model.ReferenceScriptLibraries)
{
@:@@section Scripts {
@:<script src="~/lib/jquery/dist/jquery.min.js"></script>
@:<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
@:<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
@:}
//ClearIndent();
}
@:</body>
@:</html>
}
}
@functions
{
// Do we need to use this in conjunction with the PrimaryKey check?
bool IsPropertyGuid(PropertyMetadata property)
{
return string.Equals("System.Guid", property.TypeName, StringComparison.OrdinalIgnoreCase);
}
}

View File

@ -0,0 +1,81 @@
@inherits Microsoft.Extensions.CodeGeneration.Templating.RazorTemplateBase
@using Microsoft.Extensions.CodeGeneration.EntityFramework
@@model @Model.ViewDataTypeName
@{
if (Model.IsPartialView)
{
}
else if (Model.IsLayoutPageSelected)
{
@:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"];
if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{
@:Layout = "@Model.LayoutPageFile";
}
@:}
@:
@:<h2>@@SR["@Model.ViewName"]</h2>
@:
}
else
{
@:@@{
@:Layout = null;
@:}
@:
@:<!DOCTYPE html>
@:
@:<html>
@:<head>
@:<meta name="viewport" content="width=device-width" />
@:<title>@@SR[@Model.ViewName]</title>
@:</head>
@:<body>
@:
// PushIndent(" ");
}
}
<h3>@@SR["AreYourSureYouWantToDeleteThis"]</h3>
<div>
<h4>@@SR[@Model.ViewDataTypeShortName]</h4>
<hr />
<dl class="dl-horizontal">
@{
foreach (var property in Model.ModelMetadata.Properties)
{
if (property.Scaffold && !property.IsPrimaryKey && !property.IsForeignKey)
{
<dt>
@@Html.DisplayNameFor(model => model.@GetValueExpression(property))
</dt>
<dd>
@@Html.DisplayFor(model => model.@GetValueExpression(property))
</dd>
}
}
@:</dl>
@:
@:<form asp-action="@Model.ViewName">
@:<div class="form-actions no-color">
@:<input type="submit" value="@@SR["Delete"]" class="btn btn-default" /> |
@:<a asp-action="Index">@@SR["Back to List"]</a>
@:</div>
@:</form>
@:</div>
if (!Model.IsPartialView && !Model.IsLayoutPageSelected)
{
//ClearIndent();
@:</body>
@:</html>
}
}
@functions
{
string GetValueExpression(PropertyMetadata property)
{
//Todo: Get the association for the property and use that.
return property.PropertyName;
}
}

View File

@ -0,0 +1,95 @@
@inherits Microsoft.Extensions.CodeGeneration.Templating.RazorTemplateBase
@using Microsoft.Extensions.CodeGeneration.EntityFramework
@@model @Model.ViewDataTypeName
@{
if (Model.IsPartialView)
{
}
else if (Model.IsLayoutPageSelected)
{
@:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"];
if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{
@:Layout = "@Model.LayoutPageFile";
}
@:}
@:
@:<h2>@@SR["@Model.ViewName"]</h2>
@:
}
else
{
@:@@{
@:Layout = null;
@:}
@:
@:<!DOCTYPE html>
@:
@:<html>
@:<head>
@:<meta name="viewport" content="width=device-width" />
@:<title>@Model.ViewName</title>
@:</head>
@:<body>
@:
// PushIndent(" ");
}
}
<div>
<h4>@Model.ViewDataTypeShortName</h4>
<hr />
<dl class="dl-horizontal">
@{
foreach (var property in Model.ModelMetadata.Properties)
{
if (property.Scaffold && !property.IsPrimaryKey && !property.IsForeignKey)
{
<dt>
@@Html.DisplayNameFor(model => model.@GetValueExpression(property))
</dt>
<dd>
@@Html.DisplayFor(model => model.@GetValueExpression(property))
</dd>
}
}
} </dl>
</div>
<p>
@{
string pkName = GetPrimaryKeyName();
if (pkName != null)
{
@:<a asp-action="Edit" asp-route-id="@@Model.@pkName">@@SR["Edit"]</a> |
@:<a asp-action="Index">@@SR["Back to List"]</a>
}
else
{
@:@@Html.ActionLink(@@SR["Edit"], "Edit", new { /* id = Model.PrimaryKey */ }) |
@:<a asp-action="Index">@@SR["Back to List"]</a>
}
}</p>
@{
if (!Model.IsPartialView && !Model.IsLayoutPageSelected)
{
//ClearIndent();
@:</body>
@:</html>
}
}
@functions
{
string GetPrimaryKeyName()
{
return (Model.ModelMetadata.PrimaryKeys != null && Model.ModelMetadata.PrimaryKeys.Length == 1)
? Model.ModelMetadata.PrimaryKeys[0].PropertyName
: null;
}
string GetValueExpression(PropertyMetadata property)
{
//Todo: Get the association for the property and use that.
return property.PropertyName;
}
}

View File

@ -0,0 +1,149 @@
@inherits Microsoft.Extensions.CodeGeneration.Templating.RazorTemplateBase
@using Microsoft.Extensions.CodeGeneration.EntityFramework
@@model @Model.ViewDataTypeName
@{
if (Model.IsPartialView)
{
}
else if (Model.IsLayoutPageSelected)
{
@:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"];
if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{
@:Layout = "@Model.LayoutPageFile";
}
@:}
@:
@:<h2>@@SR["@Model.ViewName"]</h2>
@:
}
else
{
@:@@{
@:Layout = null;
@:}
@:
@:<!DOCTYPE html>
@:
@:<html>
@:<head>
@:<meta name="viewport" content="width=device-width" />
@:<title>@@SR["@Model.ViewName"]</title>
@:</head>
@:<body>
@:
// PushIndent(" ");
}
@:<form asp-action="@Model.ViewName">
@:<div class="form-horizontal">
@:<h4>@Model.ViewDataTypeShortName</h4>
@:<hr />
@:<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
foreach (PropertyMetadata property in Model.ModelMetadata.Properties)
{
if (property.Scaffold)
{
if (property.IsPrimaryKey)
{
@:<input type="hidden" asp-for="@property.PropertyName" />
continue;
}
if (property.IsReadOnly)
{
continue;
}
if (property.IsForeignKey)
{
@:<div class="form-group">
@:<label asp-for="@property.PropertyName" class="control-label col-md-2">@GetAssociationName(property)</label>
@:<div class="col-md-10">
@:<select asp-for="@property.PropertyName" class="form-control" ></select>
@:<span asp-validation-for="@property.PropertyName" class="text-danger" ></span>
@:</div>
@:</div>
continue;
}
bool isCheckbox = property.TypeName.Equals("System.Boolean");
if (isCheckbox)
{
@:<div class="form-group">
@:<div class="col-md-offset-2 col-md-10">
@:<div class="checkbox">
@:<input asp-for="@property.PropertyName" />
@:<label asp-for="@property.PropertyName"></label>
@:</div>
@:</div>
@:</div>
}
else if (property.IsEnum && !property.IsEnumFlags)
{
@:<div class="form-group">
@:<label asp-for="@property.PropertyName" class="col-md-2 control-label"></label>
@:<div class="col-md-10">
@:<select asp-for="@property.PropertyName" class="form-control"></select>
@:<span asp-validation-for="@property.PropertyName" class="text-danger" ></span>
@:</div>
@:</div>
}
else
{
@:<div class="form-group">
@:<label asp-for="@property.PropertyName" class="col-md-2 control-label"></label>
@:<div class="col-md-10">
@:<input asp-for="@property.PropertyName" class="form-control" />
@:<span asp-validation-for="@property.PropertyName" class="text-danger"></span>
@:</div>
@:</div>
}
}
}
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">@@SR["Back to List"]</a>
</div>
@{
if (Model.ReferenceScriptLibraries && (Model.IsLayoutPageSelected || Model.IsPartialView))
{
@:@@section Scripts {
@:<script src="~/lib/jquery/dist/jquery.min.js"></script>
@:<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
@:<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
@:}
}
// The following code closes the tag used in the case of a view using a layout page and the body and html tags in the case of a regular view page
if (!Model.IsPartialView && !Model.IsLayoutPageSelected)
{
if (Model.ReferenceScriptLibraries)
{
@:@@section Scripts {
@:<script src="~/lib/jquery/dist/jquery.min.js"></script>
@:<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
@:<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
@:}
//ClearIndent();
}
@:</body>
@:</html>
}
}
@functions
{
string GetAssociationName(PropertyMetadata property)
{
//Todo: Implement properly.
return property.PropertyName;
}
}

View File

@ -0,0 +1,115 @@
@inherits Microsoft.Extensions.CodeGeneration.Templating.RazorTemplateBase
@using Microsoft.Extensions.CodeGeneration.EntityFramework
@@model @GetEnumerableTypeExpression(Model.ViewDataTypeName)
@{
if (Model.IsPartialView)
{
}
else if (Model.IsLayoutPageSelected)
{
@:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"];
if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{
@:Layout = "@Model.LayoutPageFile";
}
@:}
@:
@:<h2>@@SR["@Model.ViewName"]</h2>
@:
}
else
{
@:@@{
@:Layout = null;
@:}
@:
@:<!DOCTYPE html>
@:
@:<html>
@:<head>
@:<meta name="viewport" content="width=device-width" />
@:<title>@@SR["@Model.ViewName"]</title>
@:</head>
@:<body>
// PushIndent(" ");
}
@:<p>
@:<a asp-action="Create">@@SR["Create New"]</a>
@:</p>
@:<table class="table">
@:<tr>
IEnumerable<PropertyMetadata> properties = Model.ModelMetadata.Properties;
foreach (var property in properties)
{
if (property.Scaffold && !property.IsPrimaryKey && !property.IsForeignKey)
{
<th>
@@Html.DisplayNameFor(model => model.@GetValueExpression(property))
</th>
}
}
@:<th></th>
@:</tr>
@:
@:@@foreach (var item in Model) {
@:<tr>
foreach (PropertyMetadata property in properties)
{
if (property.Scaffold && !property.IsPrimaryKey && !property.IsForeignKey)
{
<td>
@@Html.DisplayFor(modelItem => item.@GetValueExpression(property))
</td>
}
}
string pkName = GetPrimaryKeyName();
if (pkName != null)
{
@:<td>
@:<a asp-action="Edit" asp-route-id="@@item.@pkName">@@SR["Edit"]</a> |
@:<a asp-action="Details" asp-route-id="@@item.@pkName">@@SR["Details"]</a> |
@:<a asp-action="Delete" asp-route-id="@@item.@pkName">@@SR["Delete"]</a>
@:</td>
}
else
{
<td>
@@Html.ActionLink(SR["Edit"], "Edit",new { /* id=item.PrimaryKey */ }) |
@@Html.ActionLink(SR["Details"], "Details", new { /* id=item.PrimaryKey */ }) |
@@Html.ActionLink(SR["Delete"], "Delete", new { /* id=item.PrimaryKey */ })
</td>
}
@:</tr>
@:}
@:</table>
if(!Model.IsPartialView && !Model.IsLayoutPageSelected)
{
//ClearIndent();
@:</body>
@:</html>
}
}
@functions
{
string GetPrimaryKeyName()
{
return (Model.ModelMetadata.PrimaryKeys != null && Model.ModelMetadata.PrimaryKeys.Length == 1)
? Model.ModelMetadata.PrimaryKeys[0].PropertyName
: null;
}
string GetValueExpression(PropertyMetadata property)
{
//Todo: Get the association for the property and use that.
return property.PropertyName;
}
string GetEnumerableTypeExpression(string typeName)
{
return "IEnumerable<" + typeName + ">";
}
}

View File

@ -1,12 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>1c73094f-959f-4211-b1a1-6a69b236c283</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<ProjectReference Include="../Yavsc.Server/Yavsc.Server.csproj" />
</ItemGroup>
</Project>

View File

@ -1,136 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Blog;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize]
[Produces("application/json")]
[Route("api/blogcomments")]
public class CommentsApiController : Controller
{
private readonly ApplicationDbContext _context;
public CommentsApiController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet("{id}", Name = "GetComment")]
public async Task<IActionResult> GetComment([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return NotFound();
}
return Ok(comment);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] CommentPost post)
{
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
var article = await _context.BlogSpot.FirstOrDefaultAsync
(p=> p.Id == post.ReceiverId);
if (article==null) {
ModelState.AddModelError("ReceiverId", "not found");
return BadRequest(ModelState);
}
if (post.ParentId!=null)
{
var parentExists = _context.Comment.Any(c => c.Id == post.ParentId);
if (!parentExists)
{
ModelState.AddModelError("ParentId", "not found");
return BadRequest(ModelState);
}
}
string uid = User.GetUserId();
Comment c = new Comment{
ReceiverId = post.ReceiverId,
Content = post.Content,
ParentId = post.ParentId,
AuthorId = uid,
UserModified = uid
};
_context.Comment.Add(c);
try
{
await _context.SaveChangesAsync(uid);
}
catch (DbUpdateException)
{
if (CommentExists(c.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetComment", new { id = c.Id }, new { id = c.Id, dateCreated = c.DateCreated });
}
// DELETE: api/CommentsApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete([FromRoute] long id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null)
{
return NotFound();
}
RemoveRecursive(comment);
await _context.SaveChangesAsync(User.GetUserId());
return Ok(comment);
}
private void RemoveRecursive (Comment comment)
{
var children = _context.Comment.Where
(c=>c.ParentId==comment.Id).ToList();
foreach (var child in children) {
RemoveRecursive(child);
}
_context.Comment.Remove(comment);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool CommentExists(long id)
{
return _context.Comment.Count(e => e.Id == id) > 0;
}
}
}

View File

@ -1,73 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Attributes.Validation;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Messaging;
using Yavsc.Services;
using Microsoft.AspNetCore.SignalR;
using Yavsc.Server.Helpers;
namespace Yavsc.ApiControllers
{
[Authorize, Route("api/stream")]
public partial class FileSystemStreamController : Controller
{
private readonly ILogger logger;
private readonly ILiveProcessor liveProcessor;
private readonly IHubContext<ChatHub> hubContext;
readonly ApplicationDbContext dbContext;
public FileSystemStreamController(ApplicationDbContext context, ILiveProcessor liveProcessor, ILoggerFactory loggerFactory,
IHubContext<ChatHub> hubContext)
{
this.dbContext = context;
this.logger = loggerFactory.CreateLogger<FileSystemStreamController>();
this.liveProcessor = liveProcessor;
this.hubContext = hubContext;
}
[Authorize, Route("put/{filename}")]
public async Task<IActionResult> Put([ValidRemoteUserFilePath] string filename)
{
logger.LogInformation("Put : " + filename);
if (!HttpContext.WebSockets.IsWebSocketRequest)
return BadRequest("not a web socket");
if (!HttpContext.User.Identity.IsAuthenticated)
return new UnauthorizedResult();
var subdirs = filename.Split('/');
var filePath = subdirs.Length > 1 ? string.Join("/", subdirs.Take(subdirs.Length-1)) : null;
var shortFileName = subdirs[subdirs.Length-1];
if (!shortFileName.IsValidShortFileName())
{
logger.LogInformation("invalid file name : " + filename);
return BadRequest("invalid file name");
}
logger.LogInformation("validated: api/stream/Put: "+filename);
var userName = User.GetUserName();
string url = string.Format(
"{0}/{1}/{2}",
Config.UserFilesOptions.RequestPath.ToUriComponent(),
userName,
filename
);
hubContext.Clients.All.SendAsync("addPublicStream", new PublicStreamInfo
{
sender = userName,
url = url,
}, $"{userName} is starting a stream!");
string destDir = HttpContext.User.InitPostToFileSystem(filePath);
logger.LogInformation($"Saving flow to {destDir}");
var userId = User.GetUserId();
var user = await dbContext.Users.FirstAsync(u => u.Id == userId);
logger.LogInformation("Accepting stream ...");
await liveProcessor.AcceptStream(HttpContext, user, destDir, shortFileName);
return Ok();
}
}
}

View File

@ -1,16 +0,0 @@
using Yavsc.Attributes.Validation;
namespace Yavsc.Models.FileSystem
{
public class MoveFileQuery
{
[ValidRemoteUserFilePath]
[YaStringLength(1, 512)]
public required string Id { get; set; }
[YaStringLength(0, 512)]
[ValidRemoteUserFilePath]
public required string To { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using Yavsc.Attributes.Validation;
namespace Yavsc.Models.FileSystem
{
public class RenameFileQuery
{
[ValidRemoteUserFilePath]
[YaStringLength(1, 512)]
public required string Id { get; set; }
[YaStringLength(0, 512)]
[ValidRemoteUserFilePath]
public required string To { get; set; }
}
}

View File

@ -1,56 +0,0 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Services;
using Yavsc.ViewModels.FrontOffice;
namespace Yavsc.ApiControllers
{
[Route("api/front")]
public class FrontOfficeApiController : Controller
{
ApplicationDbContext dbContext;
private IBillingService billing;
public FrontOfficeApiController(ApplicationDbContext context, IBillingService billing)
{
dbContext = context;
this.billing = billing;
}
[HttpGet("profiles/{actCode}")]
async Task <IEnumerable<PerformerProfileViewModel>> Profiles(string actCode)
{
return await dbContext.ListPerformersAsync(billing, actCode);
}
[HttpPost("query/reject")]
public IActionResult RejectQuery(string billingCode, long queryId)
{
if (billingCode == null) return BadRequest("billingCode");
if (queryId == 0) return BadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return BadRequest();
billing.Decided = true;
billing.Accepted = false;
dbContext.SaveChanges();
return Ok();
}
[HttpPost("query/accept")]
public IActionResult AcceptQuery(string billingCode, long queryId)
{
if (billingCode == null) return BadRequest("billingCode");
if (queryId == 0) return BadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return BadRequest();
billing.Accepted = true;
billing.Decided = true;
dbContext.SaveChanges();
return Ok();
}
}
}

View File

@ -1,175 +0,0 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Messaging;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Produces("application/json")]
[Route("api/dimiss")]
public class DimissClicksApiController : Controller
{
private readonly ApplicationDbContext _context;
public DimissClicksApiController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/DimissClicksApi
[HttpGet]
public IEnumerable<DismissClicked> GetDismissClicked()
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
return _context.DismissClicked.Where(d=>d.UserId == uid);
}
[HttpGet("click/{noteid}"),AllowAnonymous]
public async Task<IActionResult> Click(long noteid )
{
if (User.IsSignedIn())
return await PostDismissClicked(new DismissClicked { NotificationId= noteid, UserId = User.GetUserId()});
await HttpContext.Session.LoadAsync();
var clicked = HttpContext.Session.GetString("clicked");
if (clicked == null) {
HttpContext.Session.SetString("clicked",noteid.ToString());
} else HttpContext.Session.SetString("clicked",$"{clicked}:{noteid}");
await HttpContext.Session.CommitAsync();
return Ok();
}
// GET: api/DimissClicksApi/5
[HttpGet("{id}", Name = "GetDismissClicked")]
public async Task<IActionResult> GetDismissClicked([FromRoute] string id)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != id) return new ChallengeResult();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
DismissClicked DismissClicked = await _context.DismissClicked.SingleAsync(m => m.UserId == id);
if (DismissClicked == null)
{
return NotFound();
}
return Ok(DismissClicked);
}
// PUT: api/DimissClicksApi/5
[HttpPut("{id}")]
public async Task<IActionResult> PutDismissClicked([FromRoute] string id, [FromBody] DismissClicked DismissClicked)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != id || uid != DismissClicked.UserId) return new ChallengeResult();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != DismissClicked.UserId)
{
return BadRequest();
}
_context.Entry(DismissClicked).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateConcurrencyException)
{
if (!DismissClickedExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/DimissClicksApi
[HttpPost]
public async Task<IActionResult> PostDismissClicked([FromBody] DismissClicked DismissClicked)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != DismissClicked.UserId) return new ChallengeResult();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.DismissClicked.Add(DismissClicked);
try
{
await _context.SaveChangesAsync(User.GetUserId());
}
catch (DbUpdateException)
{
if (DismissClickedExists(DismissClicked.UserId))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetDismissClicked", new { id = DismissClicked.UserId }, DismissClicked);
}
// DELETE: api/DimissClicksApi/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteDismissClicked([FromRoute] string id)
{
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole("Administrator"))
if (uid != id) return new ChallengeResult();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
DismissClicked DismissClicked = await _context.DismissClicked.SingleAsync(m => m.UserId == id);
if (DismissClicked == null)
{
return NotFound();
}
_context.DismissClicked.Remove(DismissClicked);
await _context.SaveChangesAsync(User.GetUserId());
return Ok(DismissClicked);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool DismissClickedExists(string id)
{
return _context.DismissClicked.Count(e => e.UserId == id) > 0;
}
}
}

View File

@ -1,87 +0,0 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Api.Helpers;
using Yavsc.Server.Helpers;
using System.Diagnostics;
namespace Yavsc.WebApi.Controllers
{
[Route("~/api/account")]
[Authorize("ApiScope")]
public class ApiAccountController : Controller
{
readonly ApplicationDbContext _dbContext;
private readonly ILogger _logger;
public ApiAccountController(
ILoggerFactory loggerFactory, ApplicationDbContext dbContext)
{
_logger = loggerFactory.CreateLogger(nameof(ApiAccountController));
_dbContext = dbContext;
}
[HttpGet("me")]
public async Task<IActionResult> Me()
{
if (User == null)
return new BadRequestObjectResult(
new { error = "user not found" });
var uid = User.GetUserId();
Debug.Assert(uid != null, "uid is null");
var userData = await GetUserData(uid);
Debug.Assert(userData != null, "userData is null");
var user = new Yavsc.Models.Auth.Me(userData.Id, userData.UserName, userData.Email,
userData.Avatar,
userData.PostalAddress, userData.DedicatedGoogleCalendar);
var userRoles = _dbContext.UserRoles.Where(u => u.UserId == uid).Select(r => r.RoleId).ToArray();
IdentityRole[] roles = _dbContext.Roles.Where(r => userRoles.Contains(r.Id)).ToArray();
user.Roles = roles.Select(r => r.Name).ToArray();
return Ok(user);
}
private async Task<ApplicationUser> GetUserData(string uid)
{
return await _dbContext.Users
.Include(u => u.PostalAddress)
.Include(u => u.AccountBalance)
.FirstAsync(u => u.Id == uid);
}
[HttpGet("myhost")]
public IActionResult MyHost ()
{
return Ok(new { host = Request.ForwardedFor() });
}
/// <summary>
/// Updates the avatar
/// </summary>
/// <returns></returns>
[HttpPost("~/api/setavatar")]
public async Task<IActionResult> SetAvatar()
{
var root = User.InitPostToFileSystem(null);
var user = await GetUserData(User.GetUserId());
if (Request.Form.Files.Count!=1)
return new BadRequestResult();
var info = user.ReceiveAvatar(Request.Form.Files[0]);
await _dbContext.SaveChangesAsync();
return Ok(info);
}
[HttpGet("identity")]
public async Task<IActionResult> Identity()
{
return Json(User.Claims.Select(c=>new {c.Type, c.Value}));
}
}
}

View File

@ -1,104 +0,0 @@
/*
Copyright (c) 2024 HigginsSoft, Alexander Higgins - https://github.com/alexhiggins732/
Copyright (c) 2018, Brock Allen & Dominick Baier. All rights reserved.
Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
Source code and license this software can be found
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
using IdentityModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Interface;
using Yavsc.Models;
using Yavsc.Services;
internal class Program
{
private static async Task Main(string[] args)
{
Console.Title = "API";
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
// builder.Services.AddDistributedMemoryCache();
// accepts any access token issued by identity server
// adds an authorization policy for scope 'scope1'
services
.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy
.RequireAuthenticatedUser()
.RequireClaim(JwtClaimTypes.Scope, new string[] { "scope2" });
});
})
.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("https://localhost:5003")
.AllowAnyHeader()
.AllowAnyMethod();
});
})
.AddControllers();
// accepts any access token issued by identity server
var authenticationBuilder = services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.IncludeErrorDetails = true;
options.Authority = "https://localhost:5001";
options.TokenValidationParameters =
new() { ValidateAudience = false, RoleClaimType = JwtClaimTypes.Role };
options.MapInboundClaims = true;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<ITrueEmailSender, MailSender>()
.AddTransient<IBillingService, BillingService>()
.AddTransient<ICalendarManager, CalendarManager>();
services.AddTransient<IFileSystemAuthManager, FileSystemAuthManager>();
WorkflowHelpers.ConfigureBillingService();
using (var app = builder.Build())
{
if (app.Environment.IsDevelopment())
app.UseDeveloperExceptionPage();
app
.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseCors("default")
/* .UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute()
.RequireAuthorization();
})*/
;
// app.MapIdentityApi<ApplicationUser>().RequireAuthorization("ApiScope");
app.MapDefaultControllerRoute();
app.MapGet("/identity", (HttpContext context) =>
new JsonResult(context?.User?.Claims.Select(c => new { c.Type, c.Value }))
);
// app.UseSession();
await app.RunAsync();
}
}
}

View File

@ -1,30 +0,0 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "https://localhost:5001",
"sslPort": 6001
}
},
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:6001;",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -1,10 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

View File

@ -1 +0,0 @@
{"AdditionalData":{},"Alg":"RS256","Crv":null,"D":"V1qxZgyKyWNi8FbeueGjfOae22fnDa0dU8YpTohrjn89bk9B8kvIzFJP9IPYThTLMaKCTFN09A3aVy_zhL5Cv2ebEqkZIpXkPmtvRavAYxoSQWUfN2czMok216KI7csVVk79csLnnO6i3pf0B9OgGwsuEsLR40_X4MTy5iTejZfwEVobN7H6_uylw5dEUjcJlR-RtuXAZz48stOLt8-y9it7rvowv8eHEsAFSaiV-g92rKZdvMdxVqW5dvHkqF4-h1gdp9VvStZYsqfnR8hrObSxom5yWFnpmxZKmaFaFxbF-k9T8YX1izuPzESPyKCUb-GX5_4sLB6vOiUO4drHiQ","DP":"7Vz77Jz00YuT87QDAEHuBl-GInvI2VT1Fg0HsUEUhBN_o1ZwqlgX6U_3yGUgYYvoWQZZQeLTxRiQSzymPxXiikKnmGt97zMypIllEOar284Ddypa4fraXSJwgKR-1UPYGZg1adjN3KDruLok3ahyUcD9375tCXmQ3Cs0QC1_ATs","DQ":"B5qgaCcQGleo-zZqWIjMCtyEyB4JBbPFtKk3uZ5KAV8lO-TQPJkohraRxInOUHoSS1O2hj1bUO1r-C29XJqrkhi2APGs2hu6V11cmAtwwhj5XPTnL_TNx314dK5ECEQ231gxidfod-6PknG20Qim7sacsj5OrJHfp9RnMZ2p4fk","E":"AQAB","K":null,"KeyId":"E7139A7A77AEA502B0482C026DCE5C59","KeyOps":[],"Kid":"E7139A7A77AEA502B0482C026DCE5C59","Kty":"RSA","N":"tL1q9Mon5IGTGYvBg_FmDoxy0HWQ0ceo6iZmDMzAkjYZ06KKdWoR7Up2ZJ7NrBnGpyrb1uR9qAJAAJm19SLKDKSrEUn5QcnTDMqVQLBurtXYw-eY2DL4cO0bbetc5_z8hyKUzikf6jJRRGfDSR2nEfXwUf3riYfYXtNgSmr_CsBwPUcH12JGad0bwsqJy7z9Tg2_pWvNR36Ba5qd_6VmkLQRGQuDTcHzwbagd3bl4Ma1bzxPULBiBENfj6srAxV-6gQhCJr3mIr1ZsJcZsrYuUnnBNgzYCZvkOkmyB68PlrV9C9xQO8aQfla2s42Uc12-UhBbreI0uBP_k8PXXXjXw","Oth":[],"P":"_jaZkNClDqxS8nddu2t6pgP596qJdzMAq11JVWAoDJV_9JRUZH2Qbq2CrDRUjRF9nxR2bVTglfzZ-bho-Iy9PqcWeVekLObiyR30zmUzoWCdUhmi-BRd3FF3uSteNPc7ohtuX4SrbbCoUR4BpcBAgHas8KKj80sIPpoYo10xK-s","Q":"tgKedcJQilsxEzRRbs8_XD4MxnsmrxqvccfvzzHkqqZMNI0CMGA41ddHiWdNcYsyzqIc-vCf6OGabD6Z7mzZXPbYsr1o4rIQXveUy3Ty3fD9YCRKgWbS9gTbXNGBFAglu3iyNl1XUCGc_DF8PImgk99pu9byPoIr6rAPhciaDV0","QI":"2wtLbwL9kODL6HoF5R8CFmf0Fz3gqoEetrq_I7wuK1pL2vmpZlzmURjvERhi5T6lD2L8SC1vY4AJ7NGzAncwn5ozpnos2s0YIxHYUixj5RuTWQLPKqk5r1bEORuju8KwfW6Nzc4K6Rhk3Lb3TXDvKi6BSf1URjLtiI8DUB_enxw","Use":null,"X":null,"X5c":[],"X5t":null,"X5tS256":null,"X5u":null,"Y":null,"KeySize":2048,"HasPrivateKey":true,"CryptoProviderFactory":{"CryptoProviderCache":{},"CustomCryptoProvider":null,"CacheSignatureProviders":true,"SignatureProviderObjectPoolCacheSize":16}}

View File

@ -1,5 +0,0 @@
<Project>
<PropertyGroup>
<Version>1.0.8</Version>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using System.Text;
using GoogleTranslateNET.Misc;
using GoogleTranslateNET.Objects.Error;
using GoogleTranslateNET.Objects.LanguageDetection;
using GoogleTranslateNET.Objects.SupportedLanguages;
using GoogleTranslateNET.Objects.Translation;
using RestSharp;
using RestSharp.Deserializers;
using System.Linq;
namespace GoogleTranslateNET
{
public class GoogleTranslate
{
private string _key;
private static RestClient _client = new RestClient("https://www.googleapis.com/language/translate/v2");
public GoogleTranslate(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key is required.", "key");
_key = key;
}
/// <summary>
/// When true, the output from google is in human readable format.
/// Default: Not set, Google defaults to true
/// </summary>
public bool? PrettyPrint { get; set; }
/// <summary>
/// When true, queries will be sent using HTTP POST instead of GET.
/// GET queries have a limit of 2000 characters, POST queries have a limit of 5000 characters.
/// Default: Not set, Google defaults to false
/// </summary>
public bool? LargeQuery { get; set; }
/// <summary>
/// Translates a text from one language to another.
/// You can input multiple texts and get them translated all at once.
/// Warning: Setting source and destination languages to the same language will result in an error.
/// </summary>
/// <param name="sourceLanguage">The language to translate from. Set it to Language.Automatic to let Google Translate determine the language.</param>
/// <param name="destinationLanaguage">The language to translate to.</param>
/// <param name="text">The text to translate. You may input more than one text.</param>
/// <returns>The translated text.</returns>
public List<Translation> Translate(Language sourceLanguage, Language destinationLanaguage, params string[] text)
{
//https://www.googleapis.com/language/translate/v2?key=key&q=hello%20world&source=en&target=de
RestRequest request = CreateRequest(string.Empty);
CheckRequest(text);
//Required
foreach (string q in text)
{
request.AddParameter("q", q);
}
request.AddParameter("target", destinationLanaguage.GetStringValue());
//Optional
if (sourceLanguage != Language.Automatic)
request.AddParameter("source", sourceLanguage.GetStringValue());
//Output
TranslateResult results = GetResponse<TranslateResult>(request);
return results.Data.Translations;
}
/// <summary>
/// Gives you a list of supported languages.
/// </summary>
/// <param name="targetLanguage">When defined, gives you a list of languages that translates into the target language.</param>
/// <returns>A list of supported languages</returns>
public List<TranslationLanaguage> GetSupportedLanguages(Language targetLanguage = Language.Unknown)
{
//https://www.googleapis.com/language/translate/v2/languages?key=key&target=zh-TW
RestRequest request = CreateRequest("languages");
//Optional
if (targetLanguage != Language.Unknown)
request.AddParameter("target", targetLanguage.GetStringValue());
//Output
SupportedLanguageResult results = GetResponse<SupportedLanguageResult>(request);
return results.Data.Languages;
}
/// <summary>
/// Detects the languages that might be used in the text.
/// You can send more than one text in a single request to detect multiple texts.
/// </summary>
/// <param name="text">The text to use when detecting languages.</param>
/// <returns>A list of languages that might be used in the text.</returns>
public List<LanguageDetection> DetectLanguage(params string[] text)
{
//https://www.googleapis.com/language/translate/v2/detect?key=key&q=google+translate+is+fast
RestRequest request = CreateRequest("detect");
CheckRequest(text);
//Required
foreach (string q in text)
{
request.AddParameter("q", q);
}
//Output
LanguageDetectionResult results = GetResponse<LanguageDetectionResult>(request);
//Flatten the results from Google Translate API
List<LanguageDetection> detections = new List<LanguageDetection>();
foreach (List<LanguageDetection> languageDetections in results.Data.Detections)
{
detections.AddRange(languageDetections);
}
return detections;
}
private void CheckRequest(IEnumerable<string> requestContent)
{
//Compute the total size of the content
int sum = requestContent.Sum(item => item.Length);
if (((LargeQuery.HasValue && !LargeQuery.Value) || !LargeQuery.HasValue) && sum >= 2000)
{
throw new ArgumentException("Your text content is larger than 2000 characters. Set LargeQuery to 'true' to enable support up to 5000 characters.");
}
if (sum > 5000)
throw new ArgumentException("Your text content is larger than 5000 characters. Google Translate only allow up to 5000 characters");
}
private RestRequest CreateRequest(string function)
{
RestRequest request;
if (LargeQuery.HasValue && LargeQuery.Value)
{
request = new RestRequest(function, Method.POST);
//To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).
request.AddHeader("X-HTTP-Method-Override", "GET");
}
else
{
request = new RestRequest(function, Method.GET);
}
request.AddParameter("key", _key);
if (PrettyPrint.HasValue)
request.AddParameter("prettyprint", PrettyPrint.ToString().ToLower());
return request;
}
private T GetResponse<T>(RestRequest request)
{
RestResponse response = (RestResponse)_client.Execute(request);
JsonDeserializer deserializer = new JsonDeserializer();
T results = deserializer.Deserialize<T>(response);
//Try to deserialize it as an error - it is a hack since I'm using generics here.
ErrorResponse errorResponse = deserializer.Deserialize<ErrorResponse>(response);
if (errorResponse.Error != null)
throw new Exception(GetErrorText(errorResponse.Error));
return results;
}
private string GetErrorText(Error error)
{
if (error != null)
{
StringBuilder sb = new StringBuilder();
sb.Append(error.Message);
if (error.Errors.Count >= 1)
{
ErrorData errorData = error.Errors.First();
sb.Append("Reason: " + errorData.Reason);
}
return sb.ToString();
}
return "There was an error. Unable to determine the cause.";
}
}
}

View File

@ -0,0 +1,118 @@
using GoogleTranslateNET.Misc;
namespace GoogleTranslateNET
{
public enum Language
{
Unknown,
Automatic,
[StringValue("af")]
Afrikaans,
[StringValue("sq")]
Albanian,
[StringValue("ar")]
Arabic,
[StringValue("be")]
Belarusian,
[StringValue("bg")]
Bulgarian,
[StringValue("ca")]
Catalan,
[StringValue("zh")]
ChineseSimplified,
[StringValue("zh-TW")]
ChineseTraditional,
[StringValue("hr")]
Croatian,
[StringValue("cs")]
Czech,
[StringValue("da")]
Danish,
[StringValue("nl")]
Dutch,
[StringValue("en")]
English,
[StringValue("eo")]
Esperanto,
[StringValue("et")]
Estonian,
[StringValue("tl")]
Filipino,
[StringValue("fi")]
Finnish,
[StringValue("fr")]
French,
[StringValue("gl")]
Galician,
[StringValue("de")]
German,
[StringValue("el")]
Greek,
[StringValue("ht")]
HaitianCreole,
[StringValue("iw")]
Hebrew,
[StringValue("hi")]
Hindi,
[StringValue("hu")]
Hungarian,
[StringValue("is")]
Icelandic,
[StringValue("id")]
Indonesian,
[StringValue("ga")]
Irish,
[StringValue("it")]
Italian,
[StringValue("ja")]
Japanese,
[StringValue("ko")]
Korean,
[StringValue("lv")]
Latvian,
[StringValue("lt")]
Lithuanian,
[StringValue("mk")]
Macedonian,
[StringValue("ms")]
Malay,
[StringValue("mt")]
Maltese,
[StringValue("no")]
Norwegian,
[StringValue("fa")]
Persian,
[StringValue("pl")]
Polish,
[StringValue("pt")]
Portuguese,
[StringValue("ro")]
Romanian,
[StringValue("ru")]
Russian,
[StringValue("sr")]
Serbian,
[StringValue("sk")]
Slovak,
[StringValue("sl")]
Slovenian,
[StringValue("es")]
Spanish,
[StringValue("sw")]
Swahili,
[StringValue("sv")]
Swedish,
[StringValue("th")]
Thai,
[StringValue("tr")]
Turkish,
[StringValue("uk")]
Ukrainian,
[StringValue("vi")]
Vietnamese,
[StringValue("cy")]
Welsh,
[StringValue("yi")]
Yiddish
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Reflection;
namespace GoogleTranslateNET.Misc
{
public static class ExtensionMethods
{
/// <summary>
/// Will get the string value for a given enums value, this will
/// only work if you assign the StringValue attribute to
/// the items in your enum.
/// Source: http://weblogs.asp.net/stefansedich/archive/2008/03/12/enum-with-string-values-in-c.aspx
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetStringValue(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;
}
}
}

View File

@ -0,0 +1,18 @@
using System;
namespace GoogleTranslateNET.Misc
{
/// <summary>
/// This attribute is used to represent a string value
/// for a value in an enum.
/// </summary>
public class StringValueAttribute : Attribute
{
public string StringValue { get; private set; }
public StringValueAttribute(string value)
{
StringValue = value;
}
}
}

View File

@ -0,0 +1,11 @@
using System.Collections.Generic;
namespace GoogleTranslateNET.Objects.Error
{
public class Error
{
public int Code { get; set; }
public string Message { get; set; }
public List<ErrorData> Errors { get; set; }
}
}

View File

@ -0,0 +1,11 @@
namespace GoogleTranslateNET.Objects.Error
{
public class ErrorData
{
public string Domain { get; set; }
public string Reason { get; set; }
public string Message { get; set; }
public string LocationType { get; set; }
public string Location { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GoogleTranslateNET.Objects.Error
{
public class ErrorResponse
{
public Error Error { get; set; }
}
}

View File

@ -0,0 +1,9 @@
namespace GoogleTranslateNET.Objects.LanguageDetection
{
public class LanguageDetection
{
public string Language { get; set; }
public bool IsReliable { get; set; }
public float Confidence { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace GoogleTranslateNET.Objects.LanguageDetection
{
public class LanguageDetectionData
{
public List<List<LanguageDetection>> Detections { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GoogleTranslateNET.Objects.LanguageDetection
{
public class LanguageDetectionResult
{
public LanguageDetectionData Data { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace GoogleTranslateNET.Objects.SupportedLanguages
{
public class SupportedLanguageData
{
public List<TranslationLanaguage> Languages { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GoogleTranslateNET.Objects.SupportedLanguages
{
public class SupportedLanguageResult
{
public SupportedLanguageData Data { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace GoogleTranslateNET.Objects.SupportedLanguages
{
public class TranslationLanaguage
{
public string Language { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GoogleTranslateNET.Objects.Translation
{
public class TranslateResult
{
public TranslationData Data { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace GoogleTranslateNET.Objects.Translation
{
public class Translation
{
public string TranslatedText { get; set; }
public string DetectedSourceLanguage { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace GoogleTranslateNET.Objects.Translation
{
public class TranslationData
{
public List<Translation> Translations { get; set; }
}
}

View File

@ -0,0 +1,59 @@
{
"version": "1.0.5-*",
"title": "Yavsc Google Translate [DNX]",
"description": "Google Translate for DNX",
"authors": [
"Paul Schneider <paul@pschneider.fr>"
],
"packOptions": {
"repository": {
"type": "git",
"url": "https://github.com/pazof/yavsc"
},
"licenseUrl": "https://github.com/pazof/yavsc/blob/vnext/LICENSE",
"requireLicenseAcceptance": true,
"owners": [
"Paul Schneider <paul@pschneider.fr>"
],
"summary": "CSharp Google Tranlate API",
"projectUrl": "http://yavsc.pschneider.fr",
"tags": [
"Translation"
]
},
"tooling": {
"defaultNamespace": "Yavsc"
},
"dependencies": {
"Newtonsoft.Json": "6.0.0",
"Gapi.net45": "1.0.1",
"RestSharp": "103.4.0"
},
"frameworks": {
"dnx451": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
},
"net46": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
},
"net461": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
},
"net452": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
},
"net451": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0"
}
}
}
}

View File

@ -0,0 +1,32 @@
using Microsoft.AspNet.Http.Authentication;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Exposes the security.Challenge environment value as a strong type.
/// </summary>
public class AuthenticationResponseChallenge
{
/// <summary>
/// Initializes a new instance of the <see cref="AuthenticationResponseChallenge"/> class
/// </summary>
/// <param name="authenticationTypes"></param>
/// <param name="properties"></param>
public AuthenticationResponseChallenge(string[] authenticationTypes, AuthenticationProperties properties)
{
AuthenticationTypes = authenticationTypes;
Properties = properties ?? new AuthenticationProperties();
}
/// <summary>
/// List of the authentication types that should send a challenge in the response.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "By design")]
public string[] AuthenticationTypes { get; private set; }
/// <summary>
/// Dictionary used to store state values about the authentication session.
/// </summary>
public AuthenticationProperties Properties { get; private set; }
}
}

View File

@ -0,0 +1,57 @@
using Microsoft.AspNet.Http.Authentication;
using System;
using System.Linq;
using System.Security.Claims;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Exposes the security.SignIn environment value as a strong type.
/// </summary>
public class AuthenticationResponseGrant
{
/// <summary>
/// Initializes a new instance of the <see cref="AuthenticationResponseGrant"/> class.
/// </summary>
/// <param name="identity"></param>
/// <param name="properties"></param>
public AuthenticationResponseGrant(ClaimsIdentity identity, AuthenticationProperties properties)
{
Principal = new ClaimsPrincipal(identity);
Identity = identity;
Properties = properties;
}
/// <summary>
/// Initializes a new instance of the <see cref="AuthenticationResponseGrant"/> class.
/// </summary>
/// <param name="principal"></param>
/// <param name="properties"></param>
public AuthenticationResponseGrant(ClaimsPrincipal principal, AuthenticationProperties properties)
{
if (principal == null)
{
throw new ArgumentNullException("principal");
}
Principal = principal;
Identity = principal.Identities.FirstOrDefault();
Properties = properties;
}
/// <summary>
/// The identity associated with the user sign in.
/// </summary>
public ClaimsIdentity Identity { get; private set; }
/// <summary>
/// The security principal associated with the user sign in.
/// </summary>
public ClaimsPrincipal Principal { get; private set; }
/// <summary>
/// Dictionary used to store state values about the authentication session.
/// </summary>
public AuthenticationProperties Properties { get; private set; }
}
}

View File

@ -0,0 +1,43 @@
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication;
using System;
namespace OAuth.AspNet.AuthServer
{
public class AuthenticationTokenCreateContext : BaseContext
{
private readonly ISecureDataFormat<AuthenticationTicket> _secureDataFormat;
public AuthenticationTokenCreateContext(HttpContext context, ISecureDataFormat<AuthenticationTicket> secureDataFormat, AuthenticationTicket ticket) : base(context)
{
if (secureDataFormat == null)
throw new ArgumentNullException(nameof(secureDataFormat));
if (ticket == null)
throw new ArgumentNullException(nameof(ticket));
_secureDataFormat = secureDataFormat;
Ticket = ticket;
}
public string Token { get; protected set; }
public AuthenticationTicket Ticket { get; protected set; }
public string SerializeTicket()
{
return _secureDataFormat.Protect(Ticket);
}
public void SetToken(string tokenValue)
{
if (tokenValue == null)
throw new ArgumentNullException(nameof(tokenValue));
Token = tokenValue;
}
}
}

View File

@ -0,0 +1,72 @@
using System;
using System.Threading.Tasks;
namespace OAuth.AspNet.AuthServer
{
public class AuthenticationTokenProvider : IAuthenticationTokenProvider
{
public Action<AuthenticationTokenCreateContext> OnCreate { get; set; }
public Func<AuthenticationTokenCreateContext, Task> OnCreateAsync { get; set; }
public Action<AuthenticationTokenReceiveContext> OnReceive { get; set; }
public Func<AuthenticationTokenReceiveContext, Task> OnReceiveAsync { get; set; }
public virtual void Create(AuthenticationTokenCreateContext context)
{
if (OnCreateAsync != null && OnCreate == null)
{
throw new InvalidOperationException("Authentication token did not provide an OnCreate method.");
}
if (OnCreate != null)
{
OnCreate.Invoke(context);
}
}
public virtual async Task CreateAsync(AuthenticationTokenCreateContext context)
{
if (OnCreateAsync != null && OnCreate == null)
{
throw new InvalidOperationException("Authentication token did not provide an OnCreate method.");
}
if (OnCreateAsync != null)
{
await OnCreateAsync.Invoke(context);
}
else
{
Create(context);
}
}
public virtual void Receive(AuthenticationTokenReceiveContext context)
{
if (OnReceiveAsync != null && OnReceive == null)
{
throw new InvalidOperationException("Authentication token did not provide an OnReceive method.");
}
if (OnReceive != null)
{
OnReceive.Invoke(context);
}
}
public virtual async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
if (OnReceiveAsync != null && OnReceive == null)
{
throw new InvalidOperationException("Authentication token did not provide an OnReceive method.");
}
if (OnReceiveAsync != null)
{
await OnReceiveAsync.Invoke(context);
}
else
{
Receive(context);
}
}
}
}

View File

@ -0,0 +1,43 @@
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication;
using System;
namespace OAuth.AspNet.AuthServer
{
public class AuthenticationTokenReceiveContext : BaseContext
{
private readonly ISecureDataFormat<AuthenticationTicket> _secureDataFormat;
public AuthenticationTokenReceiveContext(HttpContext context, ISecureDataFormat<AuthenticationTicket> secureDataFormat, string token) : base(context)
{
if (secureDataFormat == null)
throw new ArgumentNullException(nameof(secureDataFormat));
if (token == null)
throw new ArgumentNullException(nameof(token));
_secureDataFormat = secureDataFormat;
Token = token;
}
public string Token { get; protected set; }
public AuthenticationTicket Ticket { get; protected set; }
public void DeserializeTicket(string protectedData)
{
Ticket = _secureDataFormat.Unprotect(protectedData);
}
public void SetTicket(AuthenticationTicket ticket)
{
if (ticket == null)
throw new ArgumentNullException(nameof(ticket));
Ticket = ticket;
}
}
}

View File

@ -0,0 +1,138 @@
using Microsoft.AspNet.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Data object representing the information contained in the query string of an Authorize endpoint request.
/// </summary>
public class AuthorizeEndpointRequest
{
/// <summary>
/// Creates a new instance populated with values from the query string parameters.
/// </summary>
/// <param name="parameters">Query string parameters from a request.</param>
public AuthorizeEndpointRequest(IReadableStringCollection parameters)
{
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
Scope = new List<string>();
foreach (var parameter in parameters)
{
AddParameter(parameter.Key, parameters[parameter.Key]);
}
}
/// <summary>
/// The "response_type" query string parameter of the Authorize request. Known values are "code" and "token".
/// </summary>
public string ResponseType { get; set; }
/// <summary>
/// The "response_mode" query string parameter of the Authorize request. Known values are "query", "fragment" and "form_post"
/// See also, http://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html
/// </summary>
public string ResponseMode { get; set; }
/// <summary>
/// The "client_id" query string parameter of the Authorize request.
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// The "redirect_uri" query string parameter of the Authorize request. May be absent if the server should use the
/// redirect uri known to be registered to the client id.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "By design")]
public string RedirectUri { get; set; }
/// <summary>
/// The "scope" query string parameter of the Authorize request. May be absent if the server should use default scopes.
/// </summary>
public IList<string> Scope { get; private set; }
/// <summary>
/// The "scope" query string parameter of the Authorize request. May be absent if the client does not require state to be
/// included when returning to the RedirectUri.
/// </summary>
public string State { get; set; }
/// <summary>
/// True if the "response_type" query string parameter is "code".
/// See also, http://tools.ietf.org/html/rfc6749#section-4.1.1
/// </summary>
public bool IsAuthorizationCodeGrantType
{
get { return ContainsGrantType(Constants.ResponseTypes.Code); }
}
/// <summary>
/// True if the "response_type" query string parameter is "token".
/// See also, http://tools.ietf.org/html/rfc6749#section-4.2.1
/// </summary>
public bool IsImplicitGrantType
{
get { return ContainsGrantType(Constants.ResponseTypes.Token); }
}
public bool IsFormPostResponseMode
{
get { return string.Equals(ResponseMode, Constants.ResponseModes.FormPost, StringComparison.Ordinal); }
}
/// <summary>
/// True if the "response_type" query string contains the passed responseType.
/// See also, http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html
/// </summary>
/// <param name="responseType">The responseType that is expected within the "response_type" query string</param>
/// <returns>True if the "response_type" query string contains the passed responseType.</returns>
public bool ContainsGrantType(string responseType)
{
var parts = ResponseType.Split(' ');
foreach (var part in parts)
{
if (string.Equals(part, responseType, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
private void AddParameter(string name, string value)
{
if (string.Equals(name, Constants.Parameters.ResponseType, StringComparison.Ordinal))
{
ResponseType = value;
}
else if (string.Equals(name, Constants.Parameters.ClientId, StringComparison.Ordinal))
{
ClientId = value;
}
else if (string.Equals(name, Constants.Parameters.RedirectUri, StringComparison.Ordinal))
{
RedirectUri = value;
}
else if (string.Equals(name, Constants.Parameters.Scope, StringComparison.Ordinal))
{
Scope = value.Split(' ');
}
else if (string.Equals(name, Constants.Parameters.State, StringComparison.Ordinal))
{
State = value;
}
else if (string.Equals(name, Constants.Parameters.ResponseMode, StringComparison.Ordinal))
{
ResponseMode = value;
}
}
}
}

View File

@ -0,0 +1,40 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
using System;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Base class for OAuth server endpoint contexts
/// </summary>
public class BaseOAuthEndpointContext : BaseContext
{
#region Constructors
/// <summary>
/// Creates a new instance of <see cref="BaseOAuthEndpointContext"/>.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> to use for this endpoint context.</param>
/// <param name="options">The <see cref="OAuthAuthorizationServerOptions"/> to use for this endpoint context.</param>
public BaseOAuthEndpointContext(HttpContext context, OAuthAuthorizationServerOptions options) : base(context)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
Options = options;
}
#endregion
#region Public Members
/// <summary>
/// Gets the OAuth server options.
/// </summary>
public OAuthAuthorizationServerOptions Options { get; }
#endregion
}
}

View File

@ -0,0 +1,26 @@
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Base class used for certain event contexts
/// </summary>
public abstract class BaseValidatingClientContext : BaseValidatingContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes base class used for certain event contexts
/// </summary>
protected BaseValidatingClientContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId) : base(context, options)
{
ClientId = clientId;
}
/// <summary>
/// The "client_id" parameter for the current request. The Authorization Server application is responsible for
/// validating this value identifies a registered client.
/// </summary>
public string ClientId { get; protected set; }
}
}

View File

@ -0,0 +1,113 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Base class used for certain event contexts
/// </summary>
public abstract class BaseValidatingContext<TOptions> : BaseContext
{
/// <summary>
/// Initializes base class used for certain event contexts
/// </summary>
protected BaseValidatingContext(HttpContext context, TOptions options) : base(context)
{
Options = options;
}
/// <summary>
/// The context options.
/// </summary>
public TOptions Options { get; private set; }
/// <summary>
/// True if application code has called any of the Validate methods on this context.
/// </summary>
public bool IsValidated { get; private set; }
/// <summary>
/// True if application code has called any of the SetError methods on this context.
/// </summary>
public bool HasError { get; private set; }
/// <summary>
/// The error argument provided when SetError was called on this context. This is eventually
/// returned to the client app as the OAuth "error" parameter.
/// </summary>
public string Error { get; private set; }
/// <summary>
/// The optional errorDescription argument provided when SetError was called on this context. This is eventually
/// returned to the client app as the OAuth "error_description" parameter.
/// </summary>
public string ErrorDescription { get; private set; }
/// <summary>
/// The optional errorUri argument provided when SetError was called on this context. This is eventually
/// returned to the client app as the OAuth "error_uri" parameter.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "error_uri is a string value in the protocol")]
public string ErrorUri { get; private set; }
/// <summary>
/// Marks this context as validated by the application. IsValidated becomes true and HasError becomes false as a result of calling.
/// </summary>
/// <returns>True if the validation has taken effect.</returns>
public virtual bool Validated()
{
IsValidated = true;
HasError = false;
return true;
}
/// <summary>
/// Marks this context as not validated by the application. IsValidated and HasError become false as a result of calling.
/// </summary>
public virtual void Rejected()
{
IsValidated = false;
HasError = false;
}
/// <summary>
/// Marks this context as not validated by the application and assigns various error information properties.
/// HasError becomes true and IsValidated becomes false as a result of calling.
/// </summary>
/// <param name="error">Assigned to the Error property</param>
public void SetError(string error)
{
SetError(error, null);
}
/// <summary>
/// Marks this context as not validated by the application and assigns various error information properties.
/// HasError becomes true and IsValidated becomes false as a result of calling.
/// </summary>
/// <param name="error">Assigned to the Error property</param>
/// <param name="errorDescription">Assigned to the ErrorDescription property</param>
public void SetError(string error, string errorDescription)
{
SetError(error, errorDescription, null);
}
/// <summary>
/// Marks this context as not validated by the application and assigns various error information properties.
/// HasError becomes true and IsValidated becomes false as a result of calling.
/// </summary>
/// <param name="error">Assigned to the Error property</param>
/// <param name="errorDescription">Assigned to the ErrorDescription property</param>
/// <param name="errorUri">Assigned to the ErrorUri property</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "error_uri is a string value in the protocol")]
public void SetError(string error, string errorDescription, string errorUri)
{
Error = error;
ErrorDescription = errorDescription;
ErrorUri = errorUri;
Rejected();
HasError = true;
}
}
}

View File

@ -0,0 +1,54 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using System.Security.Claims;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Base class used for certain event contexts
/// </summary>
public abstract class BaseValidatingTicketContext<TOptions> : BaseValidatingContext<TOptions> where TOptions : AuthenticationOptions
{
/// <summary>
/// Initializes base class used for certain event contexts
/// </summary>
protected BaseValidatingTicketContext(HttpContext context, TOptions options, AuthenticationTicket ticket) : base(context, options)
{
Ticket = ticket;
}
/// <summary>
/// Contains the identity and properties for the application to authenticate. If the Validated method
/// is invoked with an AuthenticationTicket or ClaimsIdentity argument, that new value is assigned to
/// this property in addition to changing IsValidated to true.
/// </summary>
public AuthenticationTicket Ticket { get; private set; }
/// <summary>
/// Replaces the ticket information on this context and marks it as as validated by the application.
/// IsValidated becomes true and HasError becomes false as a result of calling.
/// </summary>
/// <param name="ticket">Assigned to the Ticket property</param>
/// <returns>True if the validation has taken effect.</returns>
public bool Validated(AuthenticationTicket ticket)
{
Ticket = ticket;
return Validated();
}
/// <summary>
/// Alters the ticket information on this context and marks it as as validated by the application.
/// IsValidated becomes true and HasError becomes false as a result of calling.
/// </summary>
/// <param name="principal">Assigned to the Ticket.Identity property</param>
/// <returns>True if the validation has taken effect.</returns>
public bool Validated(ClaimsPrincipal principal)
{
AuthenticationProperties properties = Ticket != null ? Ticket.Properties : new AuthenticationProperties();
return Validated(new AuthenticationTicket(principal, properties, Options.AuthenticationScheme));
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Threading.Tasks;
namespace OAuth.AspNet.AuthServer
{
internal static class DefaultBehavior
{
internal static readonly Func<OAuthValidateAuthorizeRequestContext, Task> ValidateAuthorizeRequest = context =>
{
context.Validated();
return Task.FromResult<object>(null);
};
internal static readonly Func<OAuthValidateTokenRequestContext, Task> ValidateTokenRequest = context =>
{
context.Validated();
return Task.FromResult<object>(null);
};
internal static readonly Func<OAuthGrantAuthorizationCodeContext, Task> GrantAuthorizationCode = context =>
{
if (context.Ticket != null && context.Ticket.Principal != null && context.Ticket.Principal.Identity.IsAuthenticated)
{
context.Validated();
}
return Task.FromResult<object>(null);
};
internal static readonly Func<OAuthGrantRefreshTokenContext, Task> GrantRefreshToken = context =>
{
if (context.Ticket != null && context.Ticket.Principal != null && context.Ticket.Principal.Identity.IsAuthenticated)
{
context.Validated();
}
return Task.FromResult<object>(null);
};
}
}

View File

@ -0,0 +1,14 @@
using System.Threading.Tasks;
namespace OAuth.AspNet.AuthServer
{
public interface IAuthenticationTokenProvider
{
void Create(AuthenticationTokenCreateContext context);
Task CreateAsync(AuthenticationTokenCreateContext context);
void Receive(AuthenticationTokenReceiveContext context);
Task ReceiveAsync(AuthenticationTokenReceiveContext context);
}
}

View File

@ -0,0 +1,172 @@
using System.Threading.Tasks;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Interface for OAuthAuthorizationServerOptions.Provider property used by Authorization
/// Server to communicate with the web application while processing requests.
/// </summary>
public interface IOAuthAuthorizationServerProvider
{
/// <summary>
/// Called to determine if an incoming request is treated as an Authorize or Token
/// endpoint. If Options.AuthorizeEndpointPath or Options.TokenEndpointPath
/// are assigned values, then handling this event is optional and context.IsAuthorizeEndpoint and context.IsTokenEndpoint
/// will already be true if the request path matches.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task MatchEndpoint(OAuthMatchContext context);
/// <summary>
/// Called to validate that the context.ClientId is a registered "client_id", and that the context.RedirectUri a "redirect_uri"
/// registered for that client. This only occurs when processing the Authorize endpoint. The application MUST implement this
/// call, and it MUST validate both of those factors before calling context.Validated. If the context.Validated method is called
/// with a given redirectUri parameter, then IsValidated will only become true if the incoming redirect URI matches the given redirect URI.
/// If context.Validated is not called the request will not proceed further.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context);
/// <summary>
/// Called to validate that the origin of the request is a registered "client_id", and that the correct credentials for that client are
/// present on the request. If the web application accepts Basic authentication credentials,
/// context.TryGetBasicCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request header. If the web
/// application accepts "client_id" and "client_secret" as form encoded POST parameters,
/// context.TryGetFormCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request body.
/// If context.Validated is not called the request will not proceed further.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context);
/// <summary>
/// Called for each request to the Authorize endpoint to determine if the request is valid and should continue.
/// The default behavior when using the OAuthAuthorizationServerProvider is to assume well-formed requests, with
/// validated client redirect URI, should continue processing. An application may add any additional constraints.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task ValidateAuthorizeRequest(OAuthValidateAuthorizeRequestContext context);
/// <summary>
/// Called for each request to the Token endpoint to determine if the request is valid and should continue.
/// The default behavior when using the OAuthAuthorizationServerProvider is to assume well-formed requests, with
/// validated client credentials, should continue processing. An application may add any additional constraints.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task ValidateTokenRequest(OAuthValidateTokenRequestContext context);
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "authorization_code". This occurs after the Authorize
/// endpoint as redirected the user-agent back to the client with a "code" parameter, and the client is exchanging that for an "access_token".
/// The claims and properties
/// associated with the authorization code are present in the context.Ticket. The application must call context.Validated to instruct the Authorization
/// Server middleware to issue an access token based on those claims and properties. The call to context.Validated may be given a different
/// AuthenticationTicket or ClaimsIdentity in order to control which information flows from authorization code to access token.
/// The default behavior when using the OAuthAuthorizationServerProvider is to flow information from the authorization code to
/// the access token unmodified.
/// See also http://tools.ietf.org/html/rfc6749#section-4.1.3
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task GrantAuthorizationCode(OAuthGrantAuthorizationCodeContext context);
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "refresh_token". This occurs if your application has issued a "refresh_token"
/// along with the "access_token", and the client is attempting to use the "refresh_token" to acquire a new "access_token", and possibly a new "refresh_token".
/// To issue a refresh token the an Options.RefreshTokenProvider must be assigned to create the value which is returned. The claims and properties
/// associated with the refresh token are present in the context.Ticket. The application must call context.Validated to instruct the
/// Authorization Server middleware to issue an access token based on those claims and properties. The call to context.Validated may
/// be given a different AuthenticationTicket or ClaimsIdentity in order to control which information flows from the refresh token to
/// the access token. The default behavior when using the OAuthAuthorizationServerProvider is to flow information from the refresh token to
/// the access token unmodified.
/// See also http://tools.ietf.org/html/rfc6749#section-6
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task GrantRefreshToken(OAuthGrantRefreshTokenContext context);
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This occurs when the user has provided name and password
/// credentials directly into the client application's user interface, and the client application is using those to acquire an "access_token" and
/// optional "refresh_token". If the web application supports the
/// resource owner credentials grant type it must validate the context.Username and context.Password as appropriate. To issue an
/// access token the context.Validated must be called with a new ticket containing the claims about the resource owner which should be associated
/// with the access token. The application should take appropriate measures to ensure that the endpoint isn<73>t abused by malicious callers. .
/// The default behavior is to reject this grant type.
/// See also http://tools.ietf.org/html/rfc6749#section-4.3.2
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context);
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "client_credentials". This occurs when a registered client
/// application wishes to acquire an "access_token" to interact with protected resources on it's own behalf, rather than on behalf of an authenticated user.
/// If the web application supports the client credentials it may assume the context.ClientId has been validated by the ValidateClientAuthentication call.
/// To issue an access token the context.Validated must be called with a new ticket containing the claims about the client application which should be associated
/// with the access token. The application should take appropriate measures to ensure that the endpoint isn<73>t abused by malicious callers.
/// The default behavior is to reject this grant type.
/// See also http://tools.ietf.org/html/rfc6749#section-4.4.2
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task GrantClientCredentials(OAuthGrantClientCredentialsContext context);
/// <summary>
/// Called when a request to the Token andpoint arrives with a "grant_type" of any other value. If the application supports custom grant types
/// it is entirely responsible for determining if the request should result in an access_token. If context.Validated is called with ticket
/// information the response body is produced in the same way as the other standard grant types. If additional response parameters must be
/// included they may be added in the final TokenEndpoint call.
/// See also http://tools.ietf.org/html/rfc6749#section-4.5
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task GrantCustomExtension(OAuthGrantCustomExtensionContext context);
/// <summary>
/// Called at the final stage of an incoming Authorize endpoint request before the execution continues on to the web application component
/// responsible for producing the html response. Anything present in the OWIN pipeline following the Authorization Server may produce the
/// response for the Authorize page. If running on IIS any ASP.NET technology running on the server may produce the response for the
/// Authorize page. If the web application wishes to produce the response directly in the AuthorizeEndpoint call it may write to the
/// context.Response directly and should call context.RequestCompleted to stop other handlers from executing. If the web application wishes
/// to grant the authorization directly in the AuthorizeEndpoint call it cay call context.OwinContext.Authentication.SignIn with the
/// appropriate ClaimsIdentity and should call context.RequestCompleted to stop other handlers from executing.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context);
/// <summary>
/// Called at the final stage of a successful Token endpoint request. An application may implement this call in order to do any final
/// modification of the claims being used to issue access or refresh tokens. This call may also be used in order to add additional
/// response parameters to the Token endpoint's json response body.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task TokenEndpoint(OAuthTokenEndpointContext context);
/// <summary>
/// Called before the AuthorizationEndpoint redirects its response to the caller. The response could be the
/// token, when using implicit flow or the AuthorizationEndpoint when using authorization code flow.
/// An application may implement this call in order to do any final modification of the claims being used
/// to issue access or refresh tokens. This call may also be used in order to add additional
/// response parameters to the authorization endpoint's response.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
Task AuthorizationEndpointResponse(OAuthAuthorizationEndpointResponseContext context);
/// <summary>
/// Called before the TokenEndpoint redirects its response to the caller.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context);
}
}

View File

@ -0,0 +1,7 @@
SOURCE_DIR=$(HOME)/workspace/yavsc
MAKEFILE_DIR=$(SOURCE_DIR)/scripts/build/make
include $(MAKEFILE_DIR)/dnx.mk
include $(MAKEFILE_DIR)/versioning.mk
all: $(BINTARGETPATH)

View File

@ -0,0 +1,808 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.AspNet.WebUtilities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace OAuth.AspNet.AuthServer
{
public class OAuthAuthorizationServerHandler : AuthenticationHandler<OAuthAuthorizationServerOptions>
{
#region non-Public Members
private AuthorizeEndpointRequest _authorizeEndpointRequest;
private OAuthValidateClientRedirectUriContext _clientContext;
private Task SendErrorAsJsonAsync(BaseValidatingContext<OAuthAuthorizationServerOptions> validatingContext)
{
string error = validatingContext.HasError ? validatingContext.Error : Constants.Errors.InvalidRequest;
string errorDescription = validatingContext.HasError ? validatingContext.ErrorDescription : null;
string errorUri = validatingContext.HasError ? validatingContext.ErrorUri : null;
string body;
MemoryStream stream, memoryStream = null;
StreamWriter streamWriter = null;
try
{
stream = memoryStream = new MemoryStream();
streamWriter = new StreamWriter(memoryStream);
using (var writer = new JsonTextWriter(streamWriter))
{
memoryStream = null;
streamWriter = null;
writer.WriteStartObject();
writer.WritePropertyName(Constants.Parameters.Error);
writer.WriteValue(error);
if (!string.IsNullOrEmpty(errorDescription))
{
writer.WritePropertyName(Constants.Parameters.ErrorDescription);
writer.WriteValue(errorDescription);
}
if (!string.IsNullOrEmpty(errorUri))
{
writer.WritePropertyName(Constants.Parameters.ErrorUri);
writer.WriteValue(errorUri);
}
writer.WriteEndObject();
writer.Flush();
body = Encoding.UTF8.GetString(stream.ToArray());
}
}
finally
{
if (memoryStream != null)
memoryStream.Dispose();
}
Response.StatusCode = 400;
Response.ContentType = "application/json;charset=UTF-8";
Response.Headers["Cache-Control"] = "no-cache";
Response.Headers["Pragma"] = "no-cache";
Response.Headers["Expires"] = "-1";
Response.Headers["Content-Length"] = body.Length.ToString(CultureInfo.InvariantCulture);
return Response.WriteAsync(body, Context.RequestAborted);
}
private async Task<bool> SendErrorPageAsync(string error, string errorDescription, string errorUri)
{
Response.StatusCode = 400;
Response.Headers["Cache-Control"] = "no-cache";
Response.Headers["Pragma"] = "no-cache";
Response.Headers["Expires"] = "-1";
if (Options.ApplicationCanDisplayErrors)
{
Context.Items["oauth.Error"] = error;
Context.Items["oauth.ErrorDescription"] = errorDescription;
Context.Items["oauth.ErrorUri"] = errorUri;
// request is not handled - pass through to application for rendering
return false;
}
var memory = new MemoryStream();
string body;
using (var writer = new StreamWriter(memory))
{
writer.WriteLine("error: {0}", error);
if (!string.IsNullOrEmpty(errorDescription))
{
writer.WriteLine("error_description: {0}", errorDescription);
}
if (!string.IsNullOrEmpty(errorUri))
{
writer.WriteLine("error_uri: {0}", errorUri);
}
writer.Flush();
body = Encoding.UTF8.GetString(memory.ToArray());
}
Response.ContentType = "text/plain;charset=UTF-8";
Response.Headers["Content-Length"] = body.Length.ToString(CultureInfo.InvariantCulture);
await Response.WriteAsync(body, Context.RequestAborted);
// request is handled, does not pass on to application
return true;
}
private Task<bool> SendErrorRedirectAsync(OAuthValidateClientRedirectUriContext clientContext, BaseValidatingContext<OAuthAuthorizationServerOptions> validatingContext)
{
if (clientContext == null)
{
throw new ArgumentNullException("clientContext");
}
string error = validatingContext.HasError ? validatingContext.Error : Constants.Errors.InvalidRequest;
string errorDescription = validatingContext.HasError ? validatingContext.ErrorDescription : null;
string errorUri = validatingContext.HasError ? validatingContext.ErrorUri : null;
if (!clientContext.IsValidated)
{
// write error in response body if client_id or redirect_uri have not been validated
return SendErrorPageAsync(error, errorDescription, errorUri);
}
// redirect with error if client_id and redirect_uri have been validated
string location = QueryHelpers.AddQueryString(clientContext.RedirectUri, Constants.Parameters.Error, error);
if (!string.IsNullOrEmpty(errorDescription))
{
location = QueryHelpers.AddQueryString(location, Constants.Parameters.ErrorDescription, errorDescription);
}
if (!string.IsNullOrEmpty(errorUri))
{
location = QueryHelpers.AddQueryString(location, Constants.Parameters.ErrorUri, errorUri);
}
Response.Redirect(location);
// request is handled, does not pass on to application
return Task.FromResult(true);
}
private static AuthenticationTicket ReturnOutcome(OAuthValidateTokenRequestContext validatingContext, BaseValidatingContext<OAuthAuthorizationServerOptions> grantContext, AuthenticationTicket ticket, string defaultError)
{
if (!validatingContext.IsValidated)
return null;
if (!grantContext.IsValidated)
{
if (grantContext.HasError)
{
validatingContext.SetError(grantContext.Error, grantContext.ErrorDescription, grantContext.ErrorUri);
}
else
{
validatingContext.SetError(defaultError);
}
return null;
}
if (ticket == null)
{
validatingContext.SetError(defaultError);
return null;
}
return ticket;
}
private async Task<AuthenticationTicket> InvokeTokenEndpointAuthorizationCodeGrantAsync(OAuthValidateTokenRequestContext validatingContext, DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
var authorizationCodeContext = new AuthenticationTokenReceiveContext(Context, Options.AuthorizationCodeFormat, tokenEndpointRequest.AuthorizationCodeGrant.Code);
await Options.AuthorizationCodeProvider.ReceiveAsync(authorizationCodeContext);
AuthenticationTicket ticket = authorizationCodeContext.Ticket;
if (ticket == null)
{
Logger.LogError("invalid authorization code");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
if (!ticket.Properties.ExpiresUtc.HasValue ||
ticket.Properties.ExpiresUtc < currentUtc)
{
Logger.LogError("expired authorization code");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
string clientId;
if (!ticket.Properties.Items.TryGetValue(Constants.Extra.ClientId, out clientId) ||
!string.Equals(clientId, validatingContext.ClientContext.ClientId, StringComparison.Ordinal))
{
Logger.LogError("authorization code does not contain matching client_id");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
string redirectUri;
if (ticket.Properties.Items.TryGetValue(Constants.Extra.RedirectUri, out redirectUri))
{
ticket.Properties.Items.Remove(Constants.Extra.RedirectUri);
if (!string.Equals(redirectUri, tokenEndpointRequest.AuthorizationCodeGrant.RedirectUri, StringComparison.Ordinal))
{
Logger.LogError("authorization code does not contain matching redirect_uri");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
}
await Options.Provider.ValidateTokenRequest(validatingContext);
var grantContext = new OAuthGrantAuthorizationCodeContext(
Context, Options, ticket);
if (validatingContext.IsValidated)
{
await Options.Provider.GrantAuthorizationCode(grantContext);
}
return ReturnOutcome(validatingContext, grantContext, grantContext.Ticket, Constants.Errors.InvalidGrant);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(OAuthValidateTokenRequestContext validatingContext, DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
await Options.Provider.ValidateTokenRequest(validatingContext);
var grantContext = new OAuthGrantResourceOwnerCredentialsContext(
Context,
Options,
validatingContext.ClientContext.ClientId,
tokenEndpointRequest.ResourceOwnerPasswordCredentialsGrant.UserName,
tokenEndpointRequest.ResourceOwnerPasswordCredentialsGrant.Password,
tokenEndpointRequest.ResourceOwnerPasswordCredentialsGrant.Scope
);
if (validatingContext.IsValidated)
await Options.Provider.GrantResourceOwnerCredentials(grantContext);
return ReturnOutcome(validatingContext, grantContext, grantContext.Ticket, Constants.Errors.InvalidGrant);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointClientCredentialsGrantAsync(OAuthValidateTokenRequestContext validatingContext, DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
await Options.Provider.ValidateTokenRequest(validatingContext);
if (!validatingContext.IsValidated)
return null;
var grantContext = new OAuthGrantClientCredentialsContext(Context, Options, validatingContext.ClientContext.ClientId, tokenEndpointRequest.ClientCredentialsGrant.Scope);
await Options.Provider.GrantClientCredentials(grantContext);
return ReturnOutcome(validatingContext, grantContext, grantContext.Ticket, Constants.Errors.UnauthorizedClient);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointRefreshTokenGrantAsync(OAuthValidateTokenRequestContext validatingContext, DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
var refreshTokenContext = new AuthenticationTokenReceiveContext(Context, Options.RefreshTokenFormat, tokenEndpointRequest.RefreshTokenGrant.RefreshToken);
await Options.RefreshTokenProvider.ReceiveAsync(refreshTokenContext);
AuthenticationTicket ticket = refreshTokenContext.Ticket;
if (ticket == null)
{
Logger.LogError("invalid refresh token");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
if (!ticket.Properties.ExpiresUtc.HasValue || ticket.Properties.ExpiresUtc < currentUtc)
{
Logger.LogError("expired refresh token");
validatingContext.SetError(Constants.Errors.InvalidGrant);
return null;
}
await Options.Provider.ValidateTokenRequest(validatingContext);
var grantContext = new OAuthGrantRefreshTokenContext(Context, Options, ticket, validatingContext.ClientContext.ClientId);
if (validatingContext.IsValidated)
await Options.Provider.GrantRefreshToken(grantContext);
return ReturnOutcome(validatingContext, grantContext, grantContext.Ticket, Constants.Errors.InvalidGrant);
}
private async Task<AuthenticationTicket> InvokeTokenEndpointCustomGrantAsync(OAuthValidateTokenRequestContext validatingContext, DateTimeOffset currentUtc)
{
TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;
await Options.Provider.ValidateTokenRequest(validatingContext);
var grantContext = new OAuthGrantCustomExtensionContext(Context, Options, validatingContext.ClientContext.ClientId, tokenEndpointRequest.GrantType, tokenEndpointRequest.CustomExtensionGrant.Parameters);
if (validatingContext.IsValidated)
await Options.Provider.GrantCustomExtension(grantContext);
return ReturnOutcome(validatingContext, grantContext, grantContext.Ticket, Constants.Errors.UnsupportedGrantType);
}
private async Task<bool> InvokeAuthorizeEndpointAsync()
{
var authorizeRequest = new AuthorizeEndpointRequest(Request.Query);
var clientContext = new OAuthValidateClientRedirectUriContext(Context, Options, authorizeRequest.ClientId, authorizeRequest.RedirectUri);
if (!string.IsNullOrEmpty(authorizeRequest.RedirectUri))
{
bool acceptableUri = true;
Uri validatingUri;
if (!Uri.TryCreate(authorizeRequest.RedirectUri, UriKind.Absolute, out validatingUri))
{
// The redirection endpoint URI MUST be an absolute URI
// http://tools.ietf.org/html/rfc6749#section-3.1.2
acceptableUri = false;
}
else if (!string.IsNullOrEmpty(validatingUri.Fragment))
{
// The endpoint URI MUST NOT include a fragment component.
// http://tools.ietf.org/html/rfc6749#section-3.1.2
acceptableUri = false;
}
else if (!Options.AllowInsecureHttp && string.Equals(validatingUri.Scheme, "http", StringComparison.OrdinalIgnoreCase))
{
// The redirection endpoint SHOULD require the use of TLS
// http://tools.ietf.org/html/rfc6749#section-3.1.2.1
acceptableUri = false;
}
if (!acceptableUri)
{
clientContext.SetError(Constants.Errors.InvalidRequest);
return await SendErrorRedirectAsync(clientContext, clientContext);
}
}
await Options.Provider.ValidateClientRedirectUri(clientContext);
if (!clientContext.IsValidated)
{
Logger.LogVerbose("Unable to validate client information (redirect_uri)");
return await SendErrorRedirectAsync(clientContext, clientContext);
}
var validatingContext = new OAuthValidateAuthorizeRequestContext(Context, Options, authorizeRequest, clientContext);
if (string.IsNullOrEmpty(authorizeRequest.ResponseType))
{
Logger.LogVerbose("Authorize endpoint request missing required response_type parameter");
validatingContext.SetError(Constants.Errors.InvalidRequest);
}
else if (!authorizeRequest.IsAuthorizationCodeGrantType && !authorizeRequest.IsImplicitGrantType)
{
Logger.LogVerbose("Authorize endpoint request contains unsupported response_type parameter");
validatingContext.SetError(Constants.Errors.UnsupportedResponseType);
}
else
{
await Options.Provider.ValidateAuthorizeRequest(validatingContext);
}
if (!validatingContext.IsValidated)
{
// an invalid request is not processed further
return await SendErrorRedirectAsync(clientContext, validatingContext);
}
_clientContext = clientContext;
_authorizeEndpointRequest = authorizeRequest;
var authorizeEndpointContext = new OAuthAuthorizeEndpointContext(Context, Options, authorizeRequest);
await Options.Provider.AuthorizeEndpoint(authorizeEndpointContext);
return authorizeEndpointContext.IsRequestCompleted;
}
private async Task InvokeTokenEndpointAsync()
{
DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
// remove milliseconds in case they don't round-trip
currentUtc = currentUtc.Subtract(TimeSpan.FromMilliseconds(currentUtc.Millisecond));
IFormCollection form = await Request.ReadFormAsync();
var clientContext = new OAuthValidateClientAuthenticationContext(Context, Options, form);
await Options.Provider.ValidateClientAuthentication(clientContext);
if (!clientContext.IsValidated)
{
Logger.LogError("clientID is not valid.");
if (!clientContext.HasError)
clientContext.SetError(Constants.Errors.InvalidClient);
await SendErrorAsJsonAsync(clientContext);
return;
}
var tokenEndpointRequest = new TokenEndpointRequest(form);
var validatingContext = new OAuthValidateTokenRequestContext(Context, Options, tokenEndpointRequest, clientContext);
AuthenticationTicket ticket = null;
if (tokenEndpointRequest.IsAuthorizationCodeGrantType)
{
// Authorization Code Grant http://tools.ietf.org/html/rfc6749#section-4.1
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.1.3
ticket = await InvokeTokenEndpointAuthorizationCodeGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsResourceOwnerPasswordCredentialsGrantType)
{
// Resource Owner Password Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.3
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.3.2
ticket = await InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsClientCredentialsGrantType)
{
// Client Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.4
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.4.2
ticket = await InvokeTokenEndpointClientCredentialsGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsRefreshTokenGrantType)
{
// Refreshing an Access Token
// http://tools.ietf.org/html/rfc6749#section-6
ticket = await InvokeTokenEndpointRefreshTokenGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsCustomExtensionGrantType)
{
// Defining New Authorization Grant Types
// http://tools.ietf.org/html/rfc6749#section-8.3
ticket = await InvokeTokenEndpointCustomGrantAsync(validatingContext, currentUtc);
}
else
{
// Error Response http://tools.ietf.org/html/rfc6749#section-5.2
// The authorization grant type is not supported by the
// authorization server.
Logger.LogError("grant type is not recognized");
validatingContext.SetError(Constants.Errors.UnsupportedGrantType);
}
if (ticket == null)
{
await SendErrorAsJsonAsync(validatingContext);
return;
}
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);
var tokenEndpointContext = new OAuthTokenEndpointContext(Context, Options, ticket, tokenEndpointRequest);
await Options.Provider.TokenEndpoint(tokenEndpointContext);
if (tokenEndpointContext.TokenIssued)
{
ticket = new AuthenticationTicket(tokenEndpointContext.Principal, tokenEndpointContext.Properties, tokenEndpointContext.Options.AuthenticationScheme);
}
else
{
Logger.LogError("Token was not issued to tokenEndpointContext");
validatingContext.SetError(Constants.Errors.InvalidGrant);
await SendErrorAsJsonAsync(validatingContext);
return;
}
var accessTokenContext = new AuthenticationTokenCreateContext(
Context,
Options.AccessTokenFormat,
ticket);
await Options.AccessTokenProvider.CreateAsync(accessTokenContext);
string accessToken = accessTokenContext.Token;
if (string.IsNullOrEmpty(accessToken))
{
accessToken = accessTokenContext.SerializeTicket();
}
DateTimeOffset? accessTokenExpiresUtc = ticket.Properties.ExpiresUtc;
var refreshTokenCreateContext = new AuthenticationTokenCreateContext(Context, Options.RefreshTokenFormat, accessTokenContext.Ticket);
await Options.RefreshTokenProvider.CreateAsync(refreshTokenCreateContext);
string refreshToken = refreshTokenCreateContext.Token;
var tokenEndpointResponseContext = new OAuthTokenEndpointResponseContext(Context, Options, ticket, tokenEndpointRequest, accessToken, tokenEndpointContext.AdditionalResponseParameters);
await Options.Provider.TokenEndpointResponse(tokenEndpointResponseContext);
MemoryStream stream, memoryStream = null;
string body;
try
{
stream = memoryStream = new MemoryStream();
using (var writer = new JsonTextWriter(new StreamWriter(memoryStream)))
{
memoryStream = null;
writer.WriteStartObject();
writer.WritePropertyName(Constants.Parameters.AccessToken);
writer.WriteValue(accessToken);
writer.WritePropertyName(Constants.Parameters.TokenType);
writer.WriteValue(Constants.TokenTypes.Bearer);
if (accessTokenExpiresUtc.HasValue)
{
TimeSpan? expiresTimeSpan = accessTokenExpiresUtc - currentUtc;
var expiresIn = (long)expiresTimeSpan.Value.TotalSeconds;
if (expiresIn > 0)
{
writer.WritePropertyName(Constants.Parameters.ExpiresIn);
writer.WriteValue(expiresIn);
}
}
if (!string.IsNullOrEmpty(refreshToken))
{
writer.WritePropertyName(Constants.Parameters.RefreshToken);
writer.WriteValue(refreshToken);
}
foreach (var additionalResponseParameter in tokenEndpointResponseContext.AdditionalResponseParameters)
{
writer.WritePropertyName(additionalResponseParameter.Key);
writer.WriteValue(additionalResponseParameter.Value);
}
writer.WriteEndObject();
writer.Flush();
body = Encoding.UTF8.GetString(stream.ToArray());
Response.ContentType = "application/json;charset=UTF-8";
Response.Headers["Cache-Control"] = "no-cache";
Response.Headers["Pragma"] = "no-cache";
Response.Headers["Expires"] = "-1";
Response.ContentLength = Encoding.UTF8.GetByteCount(body);
}
}
finally
{
if (memoryStream != null)
memoryStream.Dispose();
}
await Response.WriteAsync(body, Encoding.UTF8, Context.RequestAborted);
}
private class Appender
{
private readonly char _delimiter;
private readonly StringBuilder _sb;
private bool _hasDelimiter;
public Appender(string value, char delimiter)
{
_sb = new StringBuilder(value);
_delimiter = delimiter;
_hasDelimiter = value.IndexOf(delimiter) != -1;
}
public Appender Append(string name, string value)
{
_sb.Append(_hasDelimiter ? '&' : _delimiter)
.Append(Uri.EscapeDataString(name))
.Append('=')
.Append(Uri.EscapeDataString(value));
_hasDelimiter = true;
return this;
}
public override string ToString()
{
return _sb.ToString();
}
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
return Task.FromResult<AuthenticateResult>(null);
}
#endregion
#region Public Members
public override async Task<bool> HandleRequestAsync()
{
var matchRequestContext = new OAuthMatchContext(Context, Options);
if (Options.AuthorizeEndpointPath.HasValue && Options.AuthorizeEndpointPath == Request.Path)
{
matchRequestContext.MatchesAuthorizeEndpoint();
}
else if (Options.TokenEndpointPath.HasValue && Options.TokenEndpointPath == Request.Path)
{
matchRequestContext.MatchesTokenEndpoint();
}
await Options.Provider.MatchEndpoint(matchRequestContext);
if (matchRequestContext.HandledResponse)
return true;
if (matchRequestContext.Skipped)
return false;
if (matchRequestContext.IsAuthorizeEndpoint || matchRequestContext.IsTokenEndpoint)
{
if (!Options.AllowInsecureHttp && !Context.Request.IsHttps)
{
Logger.LogWarning("Authorization server ignoring http request because AllowInsecureHttp is false.");
return false;
}
if (matchRequestContext.IsAuthorizeEndpoint)
return await InvokeAuthorizeEndpointAsync();
if (matchRequestContext.IsTokenEndpoint)
{
await InvokeTokenEndpointAsync();
return true;
}
}
return false;
}
protected override async Task HandleSignInAsync(SignInContext context)
{
// only successful results of an authorize request are altered
if (_clientContext == null || _authorizeEndpointRequest == null || Response.StatusCode != 200)
return;
if (context?.Principal == null)
return;
AuthenticationResponseGrant signin = new AuthenticationResponseGrant(context.Principal, new AuthenticationProperties(context.Properties));
var returnParameter = new Dictionary<string, string>();
if (_authorizeEndpointRequest.IsAuthorizationCodeGrantType)
{
DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
signin.Properties.IssuedUtc = currentUtc;
signin.Properties.ExpiresUtc = currentUtc.Add(Options.AuthorizationCodeExpireTimeSpan);
// associate client_id with all subsequent tickets
signin.Properties.Items[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId;
if (!string.IsNullOrEmpty(_authorizeEndpointRequest.RedirectUri))
{
// keep original request parameter for later comparison
signin.Properties.Items[Constants.Extra.RedirectUri] = _authorizeEndpointRequest.RedirectUri;
}
var tokenCreationContext = new AuthenticationTokenCreateContext(Context, Options.AuthorizationCodeFormat, new AuthenticationTicket(signin.Principal, signin.Properties, signin.Identity.AuthenticationType));
await Options.AuthorizationCodeProvider.CreateAsync(tokenCreationContext);
string code = tokenCreationContext.Token;
if (string.IsNullOrEmpty(code))
{
Logger.LogError("response_type code requires an Options.AuthorizationCodeProvider implementing a single-use token.");
var errorContext = new OAuthValidateAuthorizeRequestContext(Context, Options, _authorizeEndpointRequest, _clientContext);
errorContext.SetError(Constants.Errors.UnsupportedResponseType);
await SendErrorRedirectAsync(_clientContext, errorContext);
return;
}
var authResponseContext = new OAuthAuthorizationEndpointResponseContext(Context, Options, new AuthenticationTicket(signin.Principal, signin.Properties, signin.Identity.AuthenticationType), _authorizeEndpointRequest, null, code);
await Options.Provider.AuthorizationEndpointResponse(authResponseContext);
foreach (var parameter in authResponseContext.AdditionalResponseParameters)
{
returnParameter[parameter.Key] = parameter.Value.ToString();
}
returnParameter[Constants.Parameters.Code] = code;
if (!string.IsNullOrEmpty(_authorizeEndpointRequest.State))
{
returnParameter[Constants.Parameters.State] = _authorizeEndpointRequest.State;
}
string location = string.Empty;
if (_authorizeEndpointRequest.IsFormPostResponseMode)
{
location = Options.FormPostEndpoint.ToString();
returnParameter[Constants.Parameters.RedirectUri] = _clientContext.RedirectUri;
}
else
{
location = _clientContext.RedirectUri;
}
foreach (var key in returnParameter.Keys)
{
location = QueryHelpers.AddQueryString(location, key, returnParameter[key]);
}
Response.Redirect(location);
}
else if (_authorizeEndpointRequest.IsImplicitGrantType)
{
string location = _clientContext.RedirectUri;
DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
signin.Properties.IssuedUtc = currentUtc;
signin.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);
// associate client_id with access token
signin.Properties.Items[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId;
var accessTokenContext = new AuthenticationTokenCreateContext(Context, Options.AccessTokenFormat, new AuthenticationTicket(signin.Principal, signin.Properties, signin.Identity.AuthenticationType));
await Options.AccessTokenProvider.CreateAsync(accessTokenContext);
string accessToken = accessTokenContext.Token;
if (string.IsNullOrEmpty(accessToken))
{
accessToken = accessTokenContext.SerializeTicket();
}
DateTimeOffset? accessTokenExpiresUtc = accessTokenContext.Ticket.Properties.ExpiresUtc;
var appender = new Appender(location, '#');
appender.Append(Constants.Parameters.AccessToken, accessToken)
.Append(Constants.Parameters.TokenType, Constants.TokenTypes.Bearer);
if (accessTokenExpiresUtc.HasValue)
{
TimeSpan? expiresTimeSpan = accessTokenExpiresUtc - currentUtc;
var expiresIn = (long)(expiresTimeSpan.Value.TotalSeconds + .5);
appender.Append(Constants.Parameters.ExpiresIn, expiresIn.ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrEmpty(_authorizeEndpointRequest.State))
{
appender.Append(Constants.Parameters.State, _authorizeEndpointRequest.State);
}
var authResponseContext = new OAuthAuthorizationEndpointResponseContext(Context, Options, new AuthenticationTicket(signin.Principal, signin.Properties, signin.Identity.AuthenticationType), _authorizeEndpointRequest, accessToken, null);
await Options.Provider.AuthorizationEndpointResponse(authResponseContext);
foreach (var parameter in authResponseContext.AdditionalResponseParameters)
{
appender.Append(parameter.Key, parameter.Value.ToString());
}
Response.Redirect(appender.ToString());
}
}
#endregion
}
}

View File

@ -0,0 +1,85 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.WebEncoders;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Authorization Server middleware component which is added to an OWIN pipeline. This class is not
/// created by application code directly, instead it is added by calling the the IAppBuilder UseOAuthAuthorizationServer
/// extension method.
/// </summary>
public class OAuthAuthorizationServerMiddleware : AuthenticationMiddleware<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Authorization Server middleware component which is added to an OWIN pipeline. This constructor is not
/// called by application code directly, instead it is added by calling the the IAppBuilder UseOAuthAuthorizationServer
/// extension method.
/// </summary>
public OAuthAuthorizationServerMiddleware(RequestDelegate next, OAuthAuthorizationServerOptions options, ILoggerFactory loggerFactory, IDataProtectionProvider dataProtectionProvider, IUrlEncoder encoder) : base(next, options, loggerFactory, encoder)
{
if (Options.Provider == null)
{
Options.Provider = new OAuthAuthorizationServerProvider();
}
if (Options.AuthorizationCodeFormat == null)
{
IDataProtector dataProtecter = dataProtectionProvider.CreateProtector(typeof(OAuthAuthorizationServerMiddleware).FullName, "Authentication_Code", "v1");
Options.AuthorizationCodeFormat = new TicketDataFormat(dataProtecter);
}
if (Options.RefreshTokenFormat == null)
{
IDataProtector dataProtecter = dataProtectionProvider.CreateProtector(typeof(OAuthAuthorizationServerMiddleware).FullName, "Refresh_Token", "v1");
Options.RefreshTokenFormat = new TicketDataFormat(dataProtecter);
}
if (Options.TokenDataProtector == null)
{
#if DNXCORE50
Options.TokenDataProtector = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer");
#else
Options.TokenDataProtector = new MonoDataProtectionProvider("OAuth.AspNet.AuthServer").CreateProtector("OAuth.Data.Protector");
#endif
}
if (Options.AccessTokenFormat == null)
{
IDataProtector dataProtecter = Options.TokenDataProtector.CreateProtector("Access_Token", "v1");
Options.AccessTokenFormat = new TicketDataFormat(dataProtecter);
}
if (Options.AuthorizationCodeProvider == null)
{
Options.AuthorizationCodeProvider = new AuthenticationTokenProvider();
}
if (Options.AccessTokenProvider == null)
{
Options.AccessTokenProvider = new AuthenticationTokenProvider();
}
if (Options.RefreshTokenProvider == null)
{
Options.RefreshTokenProvider = new AuthenticationTokenProvider();
}
}
/// <summary>
/// Called by the AuthenticationMiddleware base class to create a per-request handler.
/// </summary>
/// <returns>A new instance of the request handler</returns>
protected override AuthenticationHandler<OAuthAuthorizationServerOptions> CreateHandler()
{
return new OAuthAuthorizationServerHandler();
}
}
}

View File

@ -0,0 +1,136 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http;
using System;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Options class provides information needed to control Authorization Server middleware behavior
/// </summary>
public class OAuthAuthorizationServerOptions : AuthenticationOptions
{
/// <summary>
/// Creates an instance of authorization server options with default values.
/// </summary>
public OAuthAuthorizationServerOptions()
{
AuthenticationScheme = OAuthDefaults.AuthenticationType;
AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5);
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20);
SystemClock = new SystemClock();
}
/// <summary>
/// The request path where client applications will redirect the user-agent in order to
/// obtain user consent to issue a token. Must begin with a leading slash, like "/Authorize".
/// </summary>
public PathString AuthorizeEndpointPath { get; set; }
/// <summary>
/// The request path client applications communicate with directly as part of the OAuth protocol.
/// Must begin with a leading slash, like "/Token". If the client is issued a client_secret, it must
/// be provided to this endpoint.
/// </summary>
public PathString TokenEndpointPath { get; set; }
/// <summary>
/// The object provided by the application to process events raised by the Authorization Server middleware.
/// The application may implement the interface fully, or it may create an instance of OAuthAuthorizationServerProvider
/// and assign delegates only to the events it wants to process.
/// </summary>
public IOAuthAuthorizationServerProvider Provider { get; set; }
/// <summary>
/// The data format used to protect and unprotect the information contained in the authorization code.
/// If not provided by the application the default data protection provider depends on the host server.
/// The SystemWeb host on IIS will use ASP.NET machine key data protection, and HttpListener and other self-hosted
/// servers will use DPAPI data protection.
/// </summary>
public ISecureDataFormat<AuthenticationTicket> AuthorizationCodeFormat { get; set; }
/// <summary>
/// The data protection provider used to protect token information.
/// </summary>
public IDataProtector TokenDataProtector { get; set; }
/// <summary>
/// The data format used to protect the information contained in the access token.
/// If not provided by the application the default data protection provider depends on the host server.
/// The SystemWeb host on IIS will use ASP.NET machine key data protection, and HttpListener and other self-hosted
/// servers will use DPAPI data protection. If a different access token
/// provider or format is assigned, a compatible instance must be assigned to the OAuthBearerAuthenticationOptions.AccessTokenProvider
/// or OAuthBearerAuthenticationOptions.AccessTokenFormat property of the resource server.
/// </summary>
public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; set; }
/// <summary>
/// The data format used to protect and unprotect the information contained in the refresh token.
/// If not provided by the application the default data protection provider depends on the host server.
/// The SystemWeb host on IIS will use ASP.NET machine key data protection, and HttpListener and other self-hosted
/// servers will use DPAPI data protection.
/// </summary>
public ISecureDataFormat<AuthenticationTicket> RefreshTokenFormat { get; set; }
/// <summary>
/// The period of time the authorization code remains valid after being issued. The default is five minutes.
/// This time span must also take into account clock synchronization between servers in a web farm, so a very
/// brief value could result in unexpectedly expired tokens.
/// </summary>
public TimeSpan AuthorizationCodeExpireTimeSpan { get; set; }
/// <summary>
/// The period of time the access token remains valid after being issued. The default is twenty minutes.
/// The client application is expected to refresh or acquire a new access token after the token has expired.
/// </summary>
public TimeSpan AccessTokenExpireTimeSpan { get; set; }
/// <summary>
/// Produces a single-use authorization code to return to the client application. For the OAuth server to be secure the
/// application MUST provide an instance for AuthorizationCodeProvider where the token produced by the OnCreate or OnCreateAsync event
/// is considered valid for only one call to OnReceive or OnReceiveAsync.
/// </summary>
public IAuthenticationTokenProvider AuthorizationCodeProvider { get; set; }
/// <summary>
/// Produces a bearer token the client application will typically be providing to resource server as the authorization bearer
/// http request header. If not provided the token produced on the server's default data protection. If a different access token
/// provider or format is assigned, a compatible instance must be assigned to the OAuthBearerAuthenticationOptions.AccessTokenProvider
/// or OAuthBearerAuthenticationOptions.AccessTokenFormat property of the resource server.
/// </summary>
public IAuthenticationTokenProvider AccessTokenProvider { get; set; }
/// <summary>
/// Produces a refresh token which may be used to produce a new access token when needed. If not provided the authorization server will
/// not return refresh tokens from the /Token endpoint.
/// </summary>
public IAuthenticationTokenProvider RefreshTokenProvider { get; set; }
/// <summary>
/// Set to true if the web application is able to render error messages on the /Authorize endpoint. This is only needed for cases where
/// the browser is not redirected back to the client application, for example, when the client_id or redirect_uri are incorrect. The
/// /Authorize endpoint should expect to see "oauth.Error", "oauth.ErrorDescription", "oauth.ErrorUri" properties added to the owin environment.
/// </summary>
public bool ApplicationCanDisplayErrors { get; set; }
/// <summary>
/// Used to know what the current clock time is when calculating or validating token expiration. When not assigned default is based on
/// DateTimeOffset.UtcNow. This is typically needed only for unit testing.
/// </summary>
public ISystemClock SystemClock { get; set; }
/// <summary>
/// True to allow authorize and token requests to arrive on http URI addresses, and to allow incoming
/// redirect_uri authorize request parameter to have http URI addresses.
/// </summary>
public bool AllowInsecureHttp { get; set; }
/// <summary>
/// Endpoint responsible for Form Post Response Mode
/// See also, http://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html
/// </summary>
public PathString FormPostEndpoint { get; set; }
}
}

View File

@ -0,0 +1,378 @@
using System;
using System.Threading.Tasks;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Default implementation of IOAuthAuthorizationServerProvider used by Authorization
/// Server to communicate with the web application while processing requests. OAuthAuthorizationServerProvider provides some default behavior,
/// may be used as a virtual base class, and offers delegate properties which may be used to
/// handle individual calls without declaring a new class type.
/// </summary>
public class OAuthAuthorizationServerProvider : IOAuthAuthorizationServerProvider
{
/// <summary>
/// Creates new instance of default provider behavior
/// </summary>
public OAuthAuthorizationServerProvider()
{
OnMatchEndpoint = context => Task.FromResult<object>(null);
OnValidateClientRedirectUri = context => Task.FromResult<object>(null);
OnValidateClientAuthentication = context => Task.FromResult<object>(null);
OnValidateAuthorizeRequest = DefaultBehavior.ValidateAuthorizeRequest;
OnValidateTokenRequest = DefaultBehavior.ValidateTokenRequest;
OnGrantAuthorizationCode = DefaultBehavior.GrantAuthorizationCode;
OnGrantResourceOwnerCredentials = context => Task.FromResult<object>(null);
OnGrantRefreshToken = DefaultBehavior.GrantRefreshToken;
OnGrantClientCredentials = context => Task.FromResult<object>(null);
OnGrantCustomExtension = context => Task.FromResult<object>(null);
OnAuthorizeEndpoint = context => Task.FromResult<object>(null);
OnTokenEndpoint = context => Task.FromResult<object>(null);
OnAuthorizationEndpointResponse = context => Task.FromResult<object>(null);
OnTokenEndpointResponse = context => Task.FromResult<object>(null);
}
/// <summary>
/// Called to determine if an incoming request is treated as an Authorize or Token
/// endpoint. If Options.AuthorizeEndpointPath or Options.TokenEndpointPath
/// are assigned values, then handling this event is optional and context.IsAuthorizeEndpoint and context.IsTokenEndpoint
/// will already be true if the request path matches.
/// </summary>
public Func<OAuthMatchContext, Task> OnMatchEndpoint { get; set; }
/// <summary>
/// Called to validate that the context.ClientId is a registered "client_id", and that the context.RedirectUri a "redirect_uri"
/// registered for that client. This only occurs when processing the Authorize endpoint. The application MUST implement this
/// call, and it MUST validate both of those factors before calling context.Validated. If the context.Validated method is called
/// with a given redirectUri parameter, then IsValidated will only become true if the incoming redirect URI matches the given redirect URI.
/// If context.Validated is not called the request will not proceed further.
/// </summary>
public Func<OAuthValidateClientRedirectUriContext, Task> OnValidateClientRedirectUri { get; set; }
/// <summary>
/// Called to validate that the origin of the request is a registered "client_id", and that the correct credentials for that client are
/// present on the request. If the web application accepts Basic authentication credentials,
/// context.TryGetBasicCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request header. If the web
/// application accepts "client_id" and "client_secret" as form encoded POST parameters,
/// context.TryGetFormCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request body.
/// If context.Validated is not called the request will not proceed further.
/// </summary>
public Func<OAuthValidateClientAuthenticationContext, Task> OnValidateClientAuthentication { get; set; }
/// <summary>
/// Called for each request to the Authorize endpoint to determine if the request is valid and should continue.
/// The default behavior when using the OAuthAuthorizationServerProvider is to assume well-formed requests, with
/// validated client redirect URI, should continue processing. An application may add any additional constraints.
/// </summary>
public Func<OAuthValidateAuthorizeRequestContext, Task> OnValidateAuthorizeRequest { get; set; }
/// <summary>
/// Called for each request to the Token endpoint to determine if the request is valid and should continue.
/// The default behavior when using the OAuthAuthorizationServerProvider is to assume well-formed requests, with
/// validated client credentials, should continue processing. An application may add any additional constraints.
/// </summary>
public Func<OAuthValidateTokenRequestContext, Task> OnValidateTokenRequest { get; set; }
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "authorization_code". This occurs after the Authorize
/// endpoint as redirected the user-agent back to the client with a "code" parameter, and the client is exchanging that for an "access_token".
/// The claims and properties
/// associated with the authorization code are present in the context.Ticket. The application must call context.Validated to instruct the Authorization
/// Server middleware to issue an access token based on those claims and properties. The call to context.Validated may be given a different
/// AuthenticationTicket or ClaimsIdentity in order to control which information flows from authorization code to access token.
/// The default behavior when using the OAuthAuthorizationServerProvider is to flow information from the authorization code to
/// the access token unmodified.
/// See also http://tools.ietf.org/html/rfc6749#section-4.1.3
/// </summary>
public Func<OAuthGrantAuthorizationCodeContext, Task> OnGrantAuthorizationCode { get; set; }
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This occurs when the user has provided name and password
/// credentials directly into the client application's user interface, and the client application is using those to acquire an "access_token" and
/// optional "refresh_token". If the web application supports the
/// resource owner credentials grant type it must validate the context.Username and context.Password as appropriate. To issue an
/// access token the context.Validated must be called with a new ticket containing the claims about the resource owner which should be associated
/// with the access token. The application should take appropriate measures to ensure that the endpoint isn<73>t abused by malicious callers.
/// The default behavior is to reject this grant type.
/// See also http://tools.ietf.org/html/rfc6749#section-4.3.2
/// </summary>
public Func<OAuthGrantResourceOwnerCredentialsContext, Task> OnGrantResourceOwnerCredentials { get; set; }
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "client_credentials". This occurs when a registered client
/// application wishes to acquire an "access_token" to interact with protected resources on it's own behalf, rather than on behalf of an authenticated user.
/// If the web application supports the client credentials it may assume the context.ClientId has been validated by the ValidateClientAuthentication call.
/// To issue an access token the context.Validated must be called with a new ticket containing the claims about the client application which should be associated
/// with the access token. The application should take appropriate measures to ensure that the endpoint isn<73>t abused by malicious callers.
/// The default behavior is to reject this grant type.
/// See also http://tools.ietf.org/html/rfc6749#section-4.4.2
/// </summary>
public Func<OAuthGrantClientCredentialsContext, Task> OnGrantClientCredentials { get; set; }
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "refresh_token". This occurs if your application has issued a "refresh_token"
/// along with the "access_token", and the client is attempting to use the "refresh_token" to acquire a new "access_token", and possibly a new "refresh_token".
/// To issue a refresh token the an Options.RefreshTokenProvider must be assigned to create the value which is returned. The claims and properties
/// associated with the refresh token are present in the context.Ticket. The application must call context.Validated to instruct the
/// Authorization Server middleware to issue an access token based on those claims and properties. The call to context.Validated may
/// be given a different AuthenticationTicket or ClaimsIdentity in order to control which information flows from the refresh token to
/// the access token. The default behavior when using the OAuthAuthorizationServerProvider is to flow information from the refresh token to
/// the access token unmodified.
/// See also http://tools.ietf.org/html/rfc6749#section-6
/// </summary>
public Func<OAuthGrantRefreshTokenContext, Task> OnGrantRefreshToken { get; set; }
/// <summary>
/// Called when a request to the Token andpoint arrives with a "grant_type" of any other value. If the application supports custom grant types
/// it is entirely responsible for determining if the request should result in an access_token. If context.Validated is called with ticket
/// information the response body is produced in the same way as the other standard grant types. If additional response parameters must be
/// included they may be added in the final TokenEndpoint call.
/// See also http://tools.ietf.org/html/rfc6749#section-4.5
/// </summary>
public Func<OAuthGrantCustomExtensionContext, Task> OnGrantCustomExtension { get; set; }
/// <summary>
/// Called at the final stage of an incoming Authorize endpoint request before the execution continues on to the web application component
/// responsible for producing the html response. Anything present in the OWIN pipeline following the Authorization Server may produce the
/// response for the Authorize page. If running on IIS any ASP.NET technology running on the server may produce the response for the
/// Authorize page. If the web application wishes to produce the response directly in the AuthorizeEndpoint call it may write to the
/// context.Response directly and should call context.RequestCompleted to stop other handlers from executing. If the web application wishes
/// to grant the authorization directly in the AuthorizeEndpoint call it cay call context.OwinContext.Authentication.SignIn with the
/// appropriate ClaimsIdentity and should call context.RequestCompleted to stop other handlers from executing.
/// </summary>
public Func<OAuthAuthorizeEndpointContext, Task> OnAuthorizeEndpoint { get; set; }
/// <summary>
/// Called at the final stage of a successful Token endpoint request. An application may implement this call in order to do any final
/// modification of the claims being used to issue access or refresh tokens. This call may also be used in order to add additional
/// response parameters to the Token endpoint's json response body.
/// </summary>
public Func<OAuthTokenEndpointContext, Task> OnTokenEndpoint { get; set; }
/// <summary>
/// Called before the AuthorizationEndpoint redirects its response to the caller. The response could be the
/// token, when using implicit flow or the AuthorizationEndpoint when using authorization code flow.
/// An application may implement this call in order to do any final modification of the claims being used
/// to issue access or refresh tokens. This call may also be used in order to add additional
/// response parameters to the authorization endpoint's response.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public Func<OAuthAuthorizationEndpointResponseContext, Task> OnAuthorizationEndpointResponse { get; set; }
/// <summary>
/// Called before the TokenEndpoint redirects its response to the caller.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Func<OAuthTokenEndpointResponseContext, Task> OnTokenEndpointResponse { get; set; }
/// <summary>
/// Called to determine if an incoming request is treated as an Authorize or Token
/// endpoint. If Options.AuthorizeEndpointPath or Options.TokenEndpointPath
/// are assigned values, then handling this event is optional and context.IsAuthorizeEndpoint and context.IsTokenEndpoint
/// will already be true if the request path matches.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task MatchEndpoint(OAuthMatchContext context)
{
return OnMatchEndpoint.Invoke(context);
}
/// <summary>
/// Called to validate that the context.ClientId is a registered "client_id", and that the context.RedirectUri a "redirect_uri"
/// registered for that client. This only occurs when processing the Authorize endpoint. The application MUST implement this
/// call, and it MUST validate both of those factors before calling context.Validated. If the context.Validated method is called
/// with a given redirectUri parameter, then IsValidated will only become true if the incoming redirect URI matches the given redirect URI.
/// If context.Validated is not called the request will not proceed further.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
return OnValidateClientRedirectUri.Invoke(context);
}
/// <summary>
/// Called to validate that the origin of the request is a registered "client_id", and that the correct credentials for that client are
/// present on the request. If the web application accepts Basic authentication credentials,
/// context.TryGetBasicCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request header. If the web
/// application accepts "client_id" and "client_secret" as form encoded POST parameters,
/// context.TryGetFormCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request body.
/// If context.Validated is not called the request will not proceed further.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
return OnValidateClientAuthentication.Invoke(context);
}
/// <summary>
/// Called for each request to the Authorize endpoint to determine if the request is valid and should continue.
/// The default behavior when using the OAuthAuthorizationServerProvider is to assume well-formed requests, with
/// validated client redirect URI, should continue processing. An application may add any additional constraints.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task ValidateAuthorizeRequest(OAuthValidateAuthorizeRequestContext context)
{
return OnValidateAuthorizeRequest.Invoke(context);
}
/// <summary>
/// Called for each request to the Token endpoint to determine if the request is valid and should continue.
/// The default behavior when using the OAuthAuthorizationServerProvider is to assume well-formed requests, with
/// validated client credentials, should continue processing. An application may add any additional constraints.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task ValidateTokenRequest(OAuthValidateTokenRequestContext context)
{
return OnValidateTokenRequest.Invoke(context);
}
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "authorization_code". This occurs after the Authorize
/// endpoint as redirected the user-agent back to the client with a "code" parameter, and the client is exchanging that for an "access_token".
/// The claims and properties
/// associated with the authorization code are present in the context.Ticket. The application must call context.Validated to instruct the Authorization
/// Server middleware to issue an access token based on those claims and properties. The call to context.Validated may be given a different
/// AuthenticationTicket or ClaimsIdentity in order to control which information flows from authorization code to access token.
/// The default behavior when using the OAuthAuthorizationServerProvider is to flow information from the authorization code to
/// the access token unmodified.
/// See also http://tools.ietf.org/html/rfc6749#section-4.1.3
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task GrantAuthorizationCode(OAuthGrantAuthorizationCodeContext context)
{
return OnGrantAuthorizationCode.Invoke(context);
}
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "refresh_token". This occurs if your application has issued a "refresh_token"
/// along with the "access_token", and the client is attempting to use the "refresh_token" to acquire a new "access_token", and possibly a new "refresh_token".
/// To issue a refresh token the an Options.RefreshTokenProvider must be assigned to create the value which is returned. The claims and properties
/// associated with the refresh token are present in the context.Ticket. The application must call context.Validated to instruct the
/// Authorization Server middleware to issue an access token based on those claims and properties. The call to context.Validated may
/// be given a different AuthenticationTicket or ClaimsIdentity in order to control which information flows from the refresh token to
/// the access token. The default behavior when using the OAuthAuthorizationServerProvider is to flow information from the refresh token to
/// the access token unmodified.
/// See also http://tools.ietf.org/html/rfc6749#section-6
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
{
return OnGrantRefreshToken.Invoke(context);
}
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This occurs when the user has provided name and password
/// credentials directly into the client application's user interface, and the client application is using those to acquire an "access_token" and
/// optional "refresh_token". If the web application supports the
/// resource owner credentials grant type it must validate the context.Username and context.Password as appropriate. To issue an
/// access token the context.Validated must be called with a new ticket containing the claims about the resource owner which should be associated
/// with the access token. The application should take appropriate measures to ensure that the endpoint isn<73>t abused by malicious callers.
/// The default behavior is to reject this grant type.
/// See also http://tools.ietf.org/html/rfc6749#section-4.3.2
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
return OnGrantResourceOwnerCredentials.Invoke(context);
}
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of "client_credentials". This occurs when a registered client
/// application wishes to acquire an "access_token" to interact with protected resources on it's own behalf, rather than on behalf of an authenticated user.
/// If the web application supports the client credentials it may assume the context.ClientId has been validated by the ValidateClientAuthentication call.
/// To issue an access token the context.Validated must be called with a new ticket containing the claims about the client application which should be associated
/// with the access token. The application should take appropriate measures to ensure that the endpoint isn<73>t abused by malicious callers.
/// The default behavior is to reject this grant type.
/// See also http://tools.ietf.org/html/rfc6749#section-4.4.2
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
{
return OnGrantClientCredentials.Invoke(context);
}
/// <summary>
/// Called when a request to the Token endpoint arrives with a "grant_type" of any other value. If the application supports custom grant types
/// it is entirely responsible for determining if the request should result in an access_token. If context.Validated is called with ticket
/// information the response body is produced in the same way as the other standard grant types. If additional response parameters must be
/// included they may be added in the final TokenEndpoint call.
/// See also http://tools.ietf.org/html/rfc6749#section-4.5
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
{
return OnGrantCustomExtension.Invoke(context);
}
/// <summary>
/// Called at the final stage of an incoming Authorize endpoint request before the execution continues on to the web application component
/// responsible for producing the html response. Anything present in the OWIN pipeline following the Authorization Server may produce the
/// response for the Authorize page. If running on IIS any ASP.NET technology running on the server may produce the response for the
/// Authorize page. If the web application wishes to produce the response directly in the AuthorizeEndpoint call it may write to the
/// context.Response directly and should call context.RequestCompleted to stop other handlers from executing. If the web application wishes
/// to grant the authorization directly in the AuthorizeEndpoint call it cay call context.OwinContext.Authentication.SignIn with the
/// appropriate ClaimsIdentity and should call context.RequestCompleted to stop other handlers from executing.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task AuthorizeEndpoint(OAuthAuthorizeEndpointContext context)
{
return OnAuthorizeEndpoint.Invoke(context);
}
/// <summary>
/// Called at the final stage of a successful Token endpoint request. An application may implement this call in order to do any final
/// modification of the claims being used to issue access or refresh tokens. This call may also be used in order to add additional
/// response parameters to the Token endpoint's json response body.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task TokenEndpoint(OAuthTokenEndpointContext context)
{
return OnTokenEndpoint.Invoke(context);
}
/// <summary>
/// Called before the AuthorizationEndpoint redirects its response to the caller. The response could be the
/// token, when using implicit flow or the AuthorizationEndpoint when using authorization code flow.
/// An application may implement this call in order to do any final modification of the claims being used
/// to issue access or refresh tokens. This call may also be used in order to add additional
/// response parameters to the authorization endpoint's response.
/// </summary>
/// <param name="context">The context of the event carries information in and results out.</param>
/// <returns>Task to enable asynchronous execution</returns>
public virtual Task AuthorizationEndpointResponse(OAuthAuthorizationEndpointResponseContext context)
{
return OnAuthorizationEndpointResponse.Invoke(context);
}
/// <summary>
/// Called before the TokenEndpoint redirects its response to the caller.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public virtual Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
{
return OnTokenEndpointResponse.Invoke(context);
}
}
}

View File

@ -0,0 +1,33 @@
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// An event raised after the Authorization Server has processed the request, but before it is passed on to the web application.
/// Calling RequestCompleted will prevent the request from passing on to the web application.
/// </summary>
public class OAuthAuthorizeEndpointContext : BaseOAuthEndpointContext
{
/// <summary>
/// Creates an instance of this context
/// </summary>
public OAuthAuthorizeEndpointContext(HttpContext context, OAuthAuthorizationServerOptions options, AuthorizeEndpointRequest authorizeRequest) : base(context, options)
{
AuthorizeRequest = authorizeRequest;
}
/// <summary>
/// Gets OAuth authorization request data.
/// </summary>
public AuthorizeEndpointRequest AuthorizeRequest { get; private set; }
public bool IsRequestCompleted { get; private set; }
public void RequestCompleted()
{
IsRequestCompleted = true;
}
}
}

View File

@ -0,0 +1,69 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information when processing an Authorization Response
/// </summary>
public class OAuthAuthorizationEndpointResponseContext : BaseOAuthEndpointContext
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthAuthorizationEndpointResponseContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="ticket"></param>
/// <param name="tokenEndpointRequest"></param>
public OAuthAuthorizationEndpointResponseContext(HttpContext context, OAuthAuthorizationServerOptions options, AuthenticationTicket ticket, AuthorizeEndpointRequest authorizeEndpointRequest, string accessToken, string authorizationCode) : base(context, options)
{
if (ticket == null)
{
throw new ArgumentNullException("ticket");
}
Principal = ticket.Principal;
Properties = ticket.Properties;
AuthorizeEndpointRequest = authorizeEndpointRequest;
AdditionalResponseParameters = new Dictionary<string, object>(StringComparer.Ordinal);
AccessToken = accessToken;
AuthorizationCode = authorizationCode;
}
/// <summary>
/// Gets the identity of the resource owner.
/// </summary>
public ClaimsPrincipal Principal { get; private set; }
/// <summary>
/// Dictionary containing the state of the authentication session.
/// </summary>
public AuthenticationProperties Properties { get; private set; }
/// <summary>
/// Gets information about the authorize endpoint request.
/// </summary>
public AuthorizeEndpointRequest AuthorizeEndpointRequest { get; private set; }
/// <summary>
/// Enables additional values to be appended to the token response.
/// </summary>
public IDictionary<string, object> AdditionalResponseParameters { get; private set; }
/// <summary>
/// The serialized Access-Token. Depending on the flow, it can be null.
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// The created Authorization-Code. Depending on the flow, it can be null.
/// </summary>
public string AuthorizationCode { get; private set; }
}
}

View File

@ -0,0 +1,70 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace OAuth.AspNet.AuthServer
{
public static class Constants
{
public static class Parameters
{
public const string ResponseType = "response_type";
public const string GrantType = "grant_type";
public const string ClientId = "client_id";
public const string ClientSecret = "client_secret";
public const string RedirectUri = "redirect_uri";
public const string Scope = "scope";
public const string State = "state";
public const string Code = "code";
public const string RefreshToken = "refresh_token";
public const string Username = "username";
public const string Password = "password";
public const string Error = "error";
public const string ErrorDescription = "error_description";
public const string ErrorUri = "error_uri";
public const string ExpiresIn = "expires_in";
public const string AccessToken = "access_token";
public const string TokenType = "token_type";
public const string ResponseMode = "response_mode";
}
public static class ResponseTypes
{
public const string Code = "code";
public const string Token = "token";
}
public static class GrantTypes
{
public const string AuthorizationCode = "authorization_code";
public const string ClientCredentials = "client_credentials";
public const string RefreshToken = "refresh_token";
public const string Password = "password";
}
public static class TokenTypes
{
public const string Bearer = "bearer";
}
public static class Errors
{
public const string InvalidRequest = "invalid_request";
public const string InvalidClient = "invalid_client";
public const string InvalidGrant = "invalid_grant";
public const string UnsupportedResponseType = "unsupported_response_type";
public const string UnsupportedGrantType = "unsupported_grant_type";
public const string UnauthorizedClient = "unauthorized_client";
}
public static class Extra
{
public const string ClientId = "client_id";
public const string RedirectUri = "redirect_uri";
}
public static class ResponseModes
{
public const string FormPost = "form_post";
}
}
}

View File

@ -0,0 +1,15 @@

namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Default values used by authorization server and bearer authentication.
/// </summary>
public static class OAuthDefaults
{
/// <summary>
/// Default value for AuthenticationType property in the OAuthBearerAuthenticationOptions and
/// OAuthAuthorizationServerOptions.
/// </summary>
public const string AuthenticationType = "Bearer";
}
}

View File

@ -0,0 +1,21 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information when handling an OAuth authorization code grant.
/// </summary>
public class OAuthGrantAuthorizationCodeContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthGrantAuthorizationCodeContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="ticket"></param>
public OAuthGrantAuthorizationCodeContext(HttpContext context, OAuthAuthorizationServerOptions options, AuthenticationTicket ticket) : base(context, options, ticket) { }
}
}

View File

@ -0,0 +1,36 @@
using Microsoft.AspNet.Http;
using System.Collections.Generic;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used in handling an OAuth client credentials grant.
/// </summary>
public class OAuthGrantClientCredentialsContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthGrantClientCredentialsContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="clientId"></param>
/// <param name="scope"></param>
public OAuthGrantClientCredentialsContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, IList<string> scope) : base(context, options, null)
{
ClientId = clientId;
Scope = scope;
}
/// <summary>
/// OAuth client id.
/// </summary>
public string ClientId { get; private set; }
/// <summary>
/// List of scopes allowed by the resource owner.
/// </summary>
public IList<string> Scope { get; private set; }
}
}

View File

@ -0,0 +1,42 @@
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used when handling OAuth extension grant types.
/// </summary>
public class OAuthGrantCustomExtensionContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthGrantCustomExtensionContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="clientId"></param>
/// <param name="grantType"></param>
/// <param name="parameters"></param>
public OAuthGrantCustomExtensionContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string grantType, IReadableStringCollection parameters) : base(context, options, null)
{
ClientId = clientId;
GrantType = grantType;
Parameters = parameters;
}
/// <summary>
/// Gets the OAuth client id.
/// </summary>
public string ClientId { get; private set; }
/// <summary>
/// Gets the name of the OAuth extension grant type.
/// </summary>
public string GrantType { get; private set; }
/// <summary>
/// Gets a list of additional parameters from the token request.
/// </summary>
public IReadableStringCollection Parameters { get; private set; }
}
}

View File

@ -0,0 +1,30 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used when granting an OAuth refresh token.
/// </summary>
public class OAuthGrantRefreshTokenContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthGrantRefreshTokenContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="ticket"></param>
/// <param name="clientId"></param>
public OAuthGrantRefreshTokenContext(HttpContext context, OAuthAuthorizationServerOptions options, AuthenticationTicket ticket, string clientId) : base(context, options, ticket)
{
ClientId = clientId;
}
/// <summary>
/// The OAuth client id.
/// </summary>
public string ClientId { get; private set; }
}
}

View File

@ -0,0 +1,50 @@
using Microsoft.AspNet.Http;
using System.Collections.Generic;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used in handling an OAuth resource owner grant.
/// </summary>
public class OAuthGrantResourceOwnerCredentialsContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthGrantResourceOwnerCredentialsContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="clientId"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="scope"></param>
public OAuthGrantResourceOwnerCredentialsContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string userName, string password, IList<string> scope) : base(context, options, null)
{
ClientId = clientId;
UserName = userName;
Password = password;
Scope = scope;
}
/// <summary>
/// OAuth client id.
/// </summary>
public string ClientId { get; private set; }
/// <summary>
/// Resource owner username.
/// </summary>
public string UserName { get; private set; }
/// <summary>
/// Resource owner password.
/// </summary>
public string Password { get; private set; }
/// <summary>
/// List of scopes allowed by the resource owner.
/// </summary>
public IList<string> Scope { get; private set; }
}
}

View File

@ -0,0 +1,74 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
using System;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides notification used for determining the OAuth flow type based on the request.
/// </summary>
public class OAuthMatchContext : BaseControlContext
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="OAuthMatchContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
public OAuthMatchContext(HttpContext context, OAuthAuthorizationServerOptions options) : base(context)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
Options = options;
}
#endregion
#region Public Members
public OAuthAuthorizationServerOptions Options { get; }
/// <summary>
/// Gets whether or not the endpoint is an OAuth authorize endpoint.
/// </summary>
public bool IsAuthorizeEndpoint { get; private set; }
/// <summary>
/// Gets whether or not the endpoint is an OAuth token endpoint.
/// </summary>
public bool IsTokenEndpoint { get; private set; }
/// <summary>
/// Sets the endpoint type to authorize endpoint.
/// </summary>
public void MatchesAuthorizeEndpoint()
{
IsAuthorizeEndpoint = true;
IsTokenEndpoint = false;
}
/// <summary>
/// Sets the endpoint type to token endpoint.
/// </summary>
public void MatchesTokenEndpoint()
{
IsAuthorizeEndpoint = false;
IsTokenEndpoint = true;
}
/// <summary>
/// Sets the endpoint type to neither authorize nor token.
/// </summary>
public void MatchesNothing()
{
IsAuthorizeEndpoint = false;
IsTokenEndpoint = false;
}
#endregion
}
}

View File

@ -0,0 +1,75 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used when processing an OAuth token request.
/// </summary>
public class OAuthTokenEndpointContext : BaseOAuthEndpointContext
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthTokenEndpointContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="ticket"></param>
/// <param name="tokenEndpointRequest"></param>
public OAuthTokenEndpointContext(HttpContext context, OAuthAuthorizationServerOptions options, AuthenticationTicket ticket, TokenEndpointRequest tokenEndpointRequest) : base(context, options)
{
if (ticket == null)
{
throw new ArgumentNullException("ticket");
}
Principal = ticket.Principal;
Properties = ticket.Properties;
TokenEndpointRequest = tokenEndpointRequest;
AdditionalResponseParameters = new Dictionary<string, object>(StringComparer.Ordinal);
TokenIssued = Principal != null;
}
/// <summary>
/// Gets the identity of the resource owner.
/// </summary>
public ClaimsPrincipal Principal { get; private set; }
/// <summary>
/// Dictionary containing the state of the authentication session.
/// </summary>
public AuthenticationProperties Properties { get; private set; }
/// <summary>
/// Gets information about the token endpoint request.
/// </summary>
public TokenEndpointRequest TokenEndpointRequest { get; set; }
/// <summary>
/// Gets whether or not the token should be issued.
/// </summary>
public bool TokenIssued { get; private set; }
/// <summary>
/// Enables additional values to be appended to the token response.
/// </summary>
public IDictionary<string, object> AdditionalResponseParameters { get; private set; }
/// <summary>
/// Issues the token.
/// </summary>
/// <param name="principal"></param>
/// <param name="properties"></param>
public void Issue(ClaimsPrincipal principal, AuthenticationProperties properties)
{
Principal = principal;
Properties = properties;
TokenIssued = true;
}
}
}

View File

@ -0,0 +1,82 @@
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used at the end of a token-endpoint-request.
/// </summary>
public class OAuthTokenEndpointResponseContext : BaseOAuthEndpointContext
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthTokenEndpointResponseContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="ticket"></param>
/// <param name="tokenEndpointRequest"></param>
public OAuthTokenEndpointResponseContext(HttpContext context, OAuthAuthorizationServerOptions options, AuthenticationTicket ticket, TokenEndpointRequest tokenEndpointRequest, string accessToken, IDictionary<string, object> additionalResponseParameters) : base(context, options)
{
if (ticket == null)
{
throw new ArgumentNullException("ticket");
}
Principal = ticket.Principal;
Properties = ticket.Properties;
TokenEndpointRequest = tokenEndpointRequest;
AdditionalResponseParameters = new Dictionary<string, object>(StringComparer.Ordinal);
TokenIssued = Principal != null;
AccessToken = accessToken;
AdditionalResponseParameters = additionalResponseParameters;
}
/// <summary>
/// Gets the identity of the resource owner.
/// </summary>
public ClaimsPrincipal Principal { get; private set; }
/// <summary>
/// Dictionary containing the state of the authentication session.
/// </summary>
public AuthenticationProperties Properties { get; private set; }
/// <summary>
/// The issued Access-Token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Gets information about the token endpoint request.
/// </summary>
public TokenEndpointRequest TokenEndpointRequest { get; set; }
/// <summary>
/// Gets whether or not the token should be issued.
/// </summary>
public bool TokenIssued { get; private set; }
/// <summary>
/// Enables additional values to be appended to the token response.
/// </summary>
public IDictionary<string, object> AdditionalResponseParameters { get; private set; }
/// <summary>
/// Issues the token.
/// </summary>
/// <param name="principal"></param>
/// <param name="properties"></param>
public void Issue(ClaimsPrincipal principal, AuthenticationProperties properties)
{
Principal = principal;
Properties = properties;
TokenIssued = true;
}
}
}

View File

@ -0,0 +1,35 @@
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used in validating an OAuth authorization request.
/// </summary>
public class OAuthValidateAuthorizeRequestContext : BaseValidatingContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthValidateAuthorizeRequestContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="authorizeRequest"></param>
/// <param name="clientContext"></param>
public OAuthValidateAuthorizeRequestContext(HttpContext context, OAuthAuthorizationServerOptions options, AuthorizeEndpointRequest authorizeRequest, OAuthValidateClientRedirectUriContext clientContext) : base(context, options)
{
AuthorizeRequest = authorizeRequest;
ClientContext = clientContext;
}
/// <summary>
/// Gets OAuth authorization request data.
/// </summary>
public AuthorizeEndpointRequest AuthorizeRequest { get; private set; }
/// <summary>
/// Gets data about the OAuth client.
/// </summary>
public OAuthValidateClientRedirectUriContext ClientContext { get; private set; }
}
}

View File

@ -0,0 +1,106 @@
using Microsoft.AspNet.Http;
using System;
using System.Text;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Contains information about the client credentials.
/// </summary>
public class OAuthValidateClientAuthenticationContext : BaseValidatingClientContext
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthValidateClientAuthenticationContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="parameters"></param>
public OAuthValidateClientAuthenticationContext(HttpContext context, OAuthAuthorizationServerOptions options, IReadableStringCollection parameters) : base(context, options, null)
{
Parameters = parameters;
}
/// <summary>
/// Gets the set of form parameters from the request.
/// </summary>
public IReadableStringCollection Parameters { get; private set; }
/// <summary>
/// Sets the client id and marks the context as validated by the application.
/// </summary>
/// <param name="clientId"></param>
/// <returns></returns>
public bool Validated(string clientId)
{
ClientId = clientId;
return Validated();
}
/// <summary>
/// Extracts HTTP basic authentication credentials from the HTTP authenticate header.
/// </summary>
/// <param name="clientId"></param>
/// <param name="clientSecret"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Optimized for usage")]
public bool TryGetBasicCredentials(out string clientId, out string clientSecret)
{
// Client Authentication http://tools.ietf.org/html/rfc6749#section-2.3
// Client Authentication Password http://tools.ietf.org/html/rfc6749#section-2.3.1
string authorization = Request.Headers["Authorization"];
if (!string.IsNullOrWhiteSpace(authorization) && authorization.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
{
try
{
byte[] data = Convert.FromBase64String(authorization.Substring("Basic ".Length).Trim());
string text = Encoding.UTF8.GetString(data);
int delimiterIndex = text.IndexOf(':');
if (delimiterIndex >= 0)
{
clientId = text.Substring(0, delimiterIndex);
clientSecret = text.Substring(delimiterIndex + 1);
ClientId = clientId;
return true;
}
}
catch (FormatException)
{
// Bad Base64 string
}
catch (ArgumentException)
{
// Bad utf-8 string
}
}
clientId = null;
clientSecret = null;
return false;
}
/// <summary>
/// Extracts forms authentication credentials from the HTTP request body.
/// </summary>
/// <param name="clientId"></param>
/// <param name="clientSecret"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Optimized for usage")]
public bool TryGetFormCredentials(out string clientId, out string clientSecret)
{
clientId = Parameters[Constants.Parameters.ClientId];
if (!string.IsNullOrEmpty(clientId))
{
clientSecret = Parameters[Constants.Parameters.ClientSecret];
ClientId = clientId;
return true;
}
clientId = null;
clientSecret = null;
return false;
}
}
}

View File

@ -0,0 +1,71 @@
using Microsoft.AspNet.Http;
using System;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Contains data about the OAuth client redirect URI
/// </summary>
public class OAuthValidateClientRedirectUriContext : BaseValidatingClientContext
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthValidateClientRedirectUriContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="clientId"></param>
/// <param name="redirectUri"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Justification = "redirect_uri is a string parameter")]
public OAuthValidateClientRedirectUriContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string redirectUri) : base(context, options, clientId)
{
RedirectUri = redirectUri;
}
/// <summary>
/// Gets the client redirect URI
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "redirect_uri is a string parameter")]
public string RedirectUri { get; private set; }
/// <summary>
/// Marks this context as validated by the application. IsValidated becomes true and HasError becomes false as a result of calling.
/// </summary>
/// <returns></returns>
public override bool Validated()
{
if (string.IsNullOrEmpty(RedirectUri))
{
// Don't allow default validation when redirect_uri not provided with request
return false;
}
return base.Validated();
}
/// <summary>
/// Checks the redirect URI to determine whether it equals <see cref="RedirectUri"/>.
/// </summary>
/// <param name="redirectUri"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "redirect_uri is a string parameter")]
public bool Validated(string redirectUri)
{
if (redirectUri == null)
{
throw new ArgumentNullException("redirectUri");
}
if (!string.IsNullOrEmpty(RedirectUri) &&
!string.Equals(RedirectUri, redirectUri, StringComparison.Ordinal))
{
// Don't allow validation to alter redirect_uri provided with request
return false;
}
RedirectUri = redirectUri;
return Validated();
}
}
}

View File

@ -0,0 +1,35 @@
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used in validating an OAuth token request.
/// </summary>
public class OAuthValidateTokenRequestContext : BaseValidatingContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthValidateTokenRequestContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="tokenRequest"></param>
/// <param name="clientContext"></param>
public OAuthValidateTokenRequestContext(HttpContext context, OAuthAuthorizationServerOptions options, TokenEndpointRequest tokenRequest, BaseValidatingClientContext clientContext) : base(context, options)
{
TokenRequest = tokenRequest;
ClientContext = clientContext;
}
/// <summary>
/// Gets the token request data.
/// </summary>
public TokenEndpointRequest TokenRequest { get; private set; }
/// <summary>
/// Gets information about the client.
/// </summary>
public BaseValidatingClientContext ClientContext { get; private set; }
}
}

View File

@ -0,0 +1,164 @@
using Microsoft.AspNet.Http;
using System;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Data object representing the information contained in form encoded body of a Token endpoint request.
/// </summary>
public class TokenEndpointRequest
{
/// <summary>
/// Creates a new instance populated with values from the form encoded body parameters.
/// </summary>
/// <param name="parameters">Form encoded body parameters from a request.</param>
public TokenEndpointRequest(IReadableStringCollection parameters)
{
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
Parameters = parameters;
GrantType = parameters[Constants.Parameters.GrantType];
ClientId = parameters[Constants.Parameters.ClientId];
if (string.Equals(GrantType, Constants.GrantTypes.AuthorizationCode, StringComparison.Ordinal))
{
AuthorizationCodeGrant = new TokenEndpointRequestAuthorizationCode
{
Code = parameters[Constants.Parameters.Code],
RedirectUri = parameters[Constants.Parameters.RedirectUri],
};
}
else if (string.Equals(GrantType, Constants.GrantTypes.ClientCredentials, StringComparison.Ordinal))
{
ClientCredentialsGrant = new TokenEndpointRequestClientCredentials
{
Scope = ((string)parameters[Constants.Parameters.Scope] ?? string.Empty).Split(' ')
};
}
else if (string.Equals(GrantType, Constants.GrantTypes.RefreshToken, StringComparison.Ordinal))
{
RefreshTokenGrant = new TokenEndpointRequestRefreshToken
{
RefreshToken = parameters[Constants.Parameters.RefreshToken],
Scope = ((string)parameters[Constants.Parameters.Scope] ?? string.Empty).Split(' ')
};
}
else if (string.Equals(GrantType, Constants.GrantTypes.Password, StringComparison.Ordinal))
{
ResourceOwnerPasswordCredentialsGrant = new TokenEndpointRequestResourceOwnerPasswordCredentials
{
UserName = parameters[Constants.Parameters.Username],
Password = parameters[Constants.Parameters.Password],
Scope = ((string)parameters[Constants.Parameters.Scope] ?? string.Empty).Split(' ')
};
}
else if (!string.IsNullOrEmpty(GrantType))
{
CustomExtensionGrant = new TokenEndpointRequestCustomExtension
{
Parameters = parameters,
};
}
else
{
throw new ArgumentException("No grant type found in the request");
}
}
/// <summary>
/// The form encoded body parameters of the Token endpoint request
/// </summary>
public IReadableStringCollection Parameters { get; private set; }
/// <summary>
/// The "grant_type" parameter of the Token endpoint request. This parameter is required.
/// </summary>
public string GrantType { get; private set; }
/// <summary>
/// The "client_id" parameter of the Token endpoint request. This parameter is optional. It might not
/// be present if the request is authenticated in a different way, for example, by using basic authentication
/// credentials.
/// </summary>
public string ClientId { get; private set; }
/// <summary>
/// Data object available when the "grant_type" is "authorization_code".
/// See also http://tools.ietf.org/html/rfc6749#section-4.1.3
/// </summary>
public TokenEndpointRequestAuthorizationCode AuthorizationCodeGrant { get; private set; }
/// <summary>
/// Data object available when the "grant_type" is "client_credentials".
/// See also http://tools.ietf.org/html/rfc6749#section-4.4.2
/// </summary>
public TokenEndpointRequestClientCredentials ClientCredentialsGrant { get; private set; }
/// <summary>
/// Data object available when the "grant_type" is "refresh_token".
/// See also http://tools.ietf.org/html/rfc6749#section-6
/// </summary>
public TokenEndpointRequestRefreshToken RefreshTokenGrant { get; private set; }
/// <summary>
/// Data object available when the "grant_type" is "password".
/// See also http://tools.ietf.org/html/rfc6749#section-4.3.2
/// </summary>
public TokenEndpointRequestResourceOwnerPasswordCredentials ResourceOwnerPasswordCredentialsGrant { get; private set; }
/// <summary>
/// Data object available when the "grant_type" is unrecognized.
/// See also http://tools.ietf.org/html/rfc6749#section-4.5
/// </summary>
public TokenEndpointRequestCustomExtension CustomExtensionGrant { get; private set; }
/// <summary>
/// True when the "grant_type" is "authorization_code".
/// See also http://tools.ietf.org/html/rfc6749#section-4.1.3
/// </summary>
public bool IsAuthorizationCodeGrantType
{
get { return AuthorizationCodeGrant != null; }
}
/// <summary>
/// True when the "grant_type" is "client_credentials".
/// See also http://tools.ietf.org/html/rfc6749#section-4.4.2
/// </summary>
public bool IsClientCredentialsGrantType
{
get { return ClientCredentialsGrant != null; }
}
/// <summary>
/// True when the "grant_type" is "refresh_token".
/// See also http://tools.ietf.org/html/rfc6749#section-6
/// </summary>
public bool IsRefreshTokenGrantType
{
get { return RefreshTokenGrant != null; }
}
/// <summary>
/// True when the "grant_type" is "password".
/// See also http://tools.ietf.org/html/rfc6749#section-4.3.2
/// </summary>
public bool IsResourceOwnerPasswordCredentialsGrantType
{
get { return ResourceOwnerPasswordCredentialsGrant != null; }
}
/// <summary>
/// True when the "grant_type" is unrecognized.
/// See also http://tools.ietf.org/html/rfc6749#section-4.5
/// </summary>
public bool IsCustomExtensionGrantType
{
get { return CustomExtensionGrant != null; }
}
}
}

View File

@ -0,0 +1,23 @@
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Data object used by TokenEndpointRequest when the "grant_type" is "authorization_code".
/// </summary>
public class TokenEndpointRequestAuthorizationCode
{
/// <summary>
/// The value passed to the Token endpoint in the "code" parameter
/// </summary>
public string Code { get; set; }
/// <summary>
/// The value passed to the Token endpoint in the "redirect_uri" parameter. This MUST be provided by the caller
/// if the original visit to the Authorize endpoint contained a "redirect_uri" parameter.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "By design")]
public string RedirectUri { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using System.Collections.Generic;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Data object used by TokenEndpointRequest when the "grant_type" is "client_credentials".
/// </summary>
public class TokenEndpointRequestClientCredentials
{
/// <summary>
/// The value passed to the Token endpoint in the "scope" parameter
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This class is just for passing data through.")]
public IList<string> Scope { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.AspNet.Http;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Data object used by TokenEndpointRequest which contains parameter information when the "grant_type" is unrecognized.
/// </summary>
public class TokenEndpointRequestCustomExtension
{
/// <summary>
/// The parameter information when the "grant_type" is unrecognized.
/// </summary>
public IReadableStringCollection Parameters { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using System.Collections.Generic;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Data object used by TokenEndpointRequest when the "grant_type" parameter is "refresh_token".
/// </summary>
public class TokenEndpointRequestRefreshToken
{
/// <summary>
/// The value passed to the Token endpoint in the "refresh_token" parameter
/// </summary>
public string RefreshToken { get; set; }
/// <summary>
/// The value passed to the Token endpoint in the "scope" parameter
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This is just a data container object.")]
public IList<string> Scope { get; set; }
}
}

Some files were not shown because too many files have changed in this diff Show More