commentaire nul

This commit is contained in:
2016-06-07 00:20:05 +02:00
parent cac49facaa
commit 46f5c107b8
10 changed files with 545 additions and 16 deletions

View File

@ -1,18 +1,16 @@

using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Mvc;
namespace Mvc.Client.Controllers {
public class AuthenticationController : Controller {
[HttpGet("~/signin")]
public ActionResult SignIn() {
// Instruct the OIDC client middleware to redirect the user agent to the identity provider.
// Note: the authenticationType parameter must match the value configured in Startup.cs
var properties = new AuthenticationProperties { RedirectUri = "http://localhost:5002/signin-oidc" };
return new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme, properties);
var properties = new AuthenticationProperties { RedirectUri = "http://localhost:5002/signin-yavsc" };
return new ChallengeResult("yavsc", properties);
}
}

View File

@ -12,6 +12,8 @@ using Microsoft.AspNet.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Authentication.Cookies;
using Yavsc.Auth;
using Microsoft.Extensions.WebEncoders;
namespace testOauthClient
{
@ -36,6 +38,8 @@ namespace testOauthClient
options.SignInScheme = "ClientCookie";
});
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>();
services.AddAuthentication();
services.AddMvc();
@ -60,6 +64,20 @@ namespace testOauthClient
options.AuthenticationDescriptions.Clear();
});
app.UseStaticFiles();
app.UseOAuthAuthentication(
options => { 
options.AuthenticationScheme="yavsc";
options.AuthorizationEndpoint="http://dev.pschneider.fr/signin";
options.TokenEndpoint="http://dev.pschneider.fr/token";
options.AutomaticAuthenticate=true;
options.AutomaticChallenge=true;
options.CallbackPath=new PathString("/signin-yavsc");
options.ClaimsIssuer="http://dev.pschneider.fr";
options.ClientId="016c5ae4-f4cd-40e3-b250-13701c871ecd";
options.ClientSecret="blahblah";
}
);
app.UseCookieAuthentication(new CookieAuthenticationOptions {
AutomaticAuthenticate = true,
AutomaticChallenge = true,
@ -70,9 +88,8 @@ namespace testOauthClient
LogoutPath = new PathString("/signout")
});
app.UseOpenIdConnectAuthentication(
/* app.UseOpenIdConnectAuthentication(
options => {
options.AuthenticationScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.RequireHttpsMetadata = false;
@ -97,7 +114,7 @@ namespace testOauthClient
options.Scope.Clear();
options.Scope.Add("openid");
// .Add("api-resource-controller");
});
}); */
app.UseMvc(routes =>

View File

@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.OAuth;
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.Linq;
namespace Yavsc.Auth
{
internal class YavscOAuthHandler : OAuthHandler<YavscOAuthOptions>
{
private ILogger _logger;
HttpClient _backchannel;
private SharedAuthenticationOptions _sharedOptions;
public YavscOAuthHandler(HttpClient httpClient, SharedAuthenticationOptions sharedOptions, ILogger logger)
: base(httpClient)
{
_backchannel = httpClient;
_logger = logger;
_sharedOptions = sharedOptions;
}
// TODO: Abstract this properties override pattern into the base class?
protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
{
var scope = FormatScope();
var queryStrings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
queryStrings.Add("response_type", "code");
queryStrings.Add("client_id", Options.ClientId);
queryStrings.Add("redirect_uri", redirectUri);
AddQueryString(queryStrings, properties, "scope", scope);
AddQueryString(queryStrings, properties, "access_type", Options.AccessType );
AddQueryString(queryStrings, properties, "approval_prompt");
AddQueryString(queryStrings, properties, "login_hint");
var state = Options.StateDataFormat.Protect(properties);
queryStrings.Add("state", state);
var authorizationEndpoint = QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, queryStrings);
return authorizationEndpoint;
}
private static void AddQueryString(IDictionary<string, string> queryStrings, AuthenticationProperties properties,
string name, string defaultValue = null)
{
string value;
if (!properties.Items.TryGetValue(name, out value))
{
value = defaultValue;
}
else
{
// Remove the parameter from AuthenticationProperties so it won't be serialized to state parameter
properties.Items.Remove(name);
}
queryStrings[name] = value;
}
protected new async Task<AuthenticationTicket> AuthenticateAsync(AuthenticateContext context)
{
AuthenticationProperties properties = null;
try
{
// ASP.Net Identity requires the NameIdentitifer field to be set or it won't
// accept the external login (AuthenticationManagerExtensions.GetExternalLoginInfo)
string code = null;
string state = null;
IReadableStringCollection query = Request.Query;
IList<string> values = query["code"];
if (values != null && values.Count == 1)
{
code = values[0];
}
values = query["state"];
if (values != null && values.Count == 1)
{
state = values[0];
}
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties))
{
return new AuthenticationTicket(null, properties, this.Options.AuthenticationScheme);
}
string requestPrefix = Request.Scheme + "://" + Request.Host;
string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
// Build up the body for the token request
var body = new List<KeyValuePair<string, string>>();
body.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
body.Add(new KeyValuePair<string, string>("code", code));
body.Add(new KeyValuePair<string, string>("redirect_uri", redirectUri));
body.Add(new KeyValuePair<string, string>("client_id", Options.ClientId));
body.Add(new KeyValuePair<string, string>("client_secret", Options.ClientSecret));
// Request the token
HttpResponseMessage tokenResponse =
await _backchannel.PostAsync(Options.TokenEndpoint, new FormUrlEncodedContent(body));
tokenResponse.EnsureSuccessStatusCode();
string text = await tokenResponse.Content.ReadAsStringAsync();
// Deserializes the token response
JObject response = JObject.Parse(text);
string accessToken = response.Value<string>("access_token");
if (string.IsNullOrWhiteSpace(accessToken))
{
_logger.LogWarning("Access token was not found");
return new AuthenticationTicket(null, properties, this.Options.AuthenticationScheme);
}
// Get the user
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint);
request.Headers.Authorization = new AuthenticationHeaderValue(this.Options.AuthenticationScheme, accessToken);
HttpResponseMessage graphResponse = await _backchannel.SendAsync(request);
graphResponse.EnsureSuccessStatusCode();
text = await graphResponse.Content.ReadAsStringAsync();
JObject user = JObject.Parse(text);
// Read user data
var id = new ClaimsIdentity(
_sharedOptions.SignInScheme,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
context.Authenticated(new ClaimsPrincipal(id)
, new Dictionary<string,string>(), new Dictionary<string,object>{
{ "John" , (object) "Doe" }
});
return new AuthenticationTicket(context.Principal, properties, _sharedOptions.SignInScheme);
}
catch (Exception ex)
{
_logger.LogError("Authentication failed", ex);
return new AuthenticationTicket(null, properties, this.Options.AuthenticationScheme);
}
}
}
}

View File

@ -0,0 +1,80 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.WebEncoders;
namespace Yavsc.Auth
{
/// <summary>
/// An ASP.NET Core middleware for authenticating users using Google OAuth 2.0.
/// </summary>
public class YavscOAuthMiddleware : OAuthMiddleware<YavscOAuthOptions>
{
private RequestDelegate _next;
private ILogger _logger;
private SharedAuthenticationOptions _sharedOptions;
/// <summary>
/// Initializes a new <see cref="GoogleMiddleware"/>.
/// </summary>
/// <param name="next">The next middleware in the HTTP pipeline to invoke.</param>
/// <param name="dataProtectionProvider"></param>
/// <param name="loggerFactory"></param>
/// <param name="encoder"></param>
/// <param name="sharedOptions"></param>
/// <param name="options">Configuration options for the middleware.</param>
public YavscOAuthMiddleware(
RequestDelegate next,
IDataProtectionProvider dataProtectionProvider,
ILoggerFactory loggerFactory,
UrlEncoder encoder,
IOptions<SharedAuthenticationOptions> sharedOptions,
YavscOAuthOptions options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
_next = next;
if (dataProtectionProvider == null)
{
throw new ArgumentNullException(nameof(dataProtectionProvider));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
_logger = loggerFactory.CreateLogger<YavscOAuthMiddleware>();
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (sharedOptions == null)
{
throw new ArgumentNullException(nameof(sharedOptions));
}
_sharedOptions = sharedOptions.Value;
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
}
protected override AuthenticationHandler<YavscOAuthOptions> CreateHandler()
{
return new YavscOAuthHandler(Backchannel,_sharedOptions,_logger);
}
}
}

View File

@ -0,0 +1,24 @@
using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Http;
public class YavscOAuthOptions : OAuthOptions {
public YavscOAuthOptions()
{
AuthenticationScheme = "yavsc";
DisplayName = AuthenticationScheme;
CallbackPath = new PathString("/signin-yavsc");
AuthorizationEndpoint = "http://dev.pschneider.fr/connect/authorize";
TokenEndpoint = "http://dev.pschneider.fr/api/token/get";
UserInformationEndpoint = "http://dev.pschneider.fr/api/userinfo";
Scope.Add("openid");
Scope.Add("profile");
Scope.Add("email");
}
/// <summary>
/// access_type. Set to 'offline' to request a refresh token.
/// </summary>
public string AccessType { get; set; }
}

View File

@ -6,5 +6,11 @@
"System": "Information",
"Microsoft": "Information"
}
},
"Authentication": { 
"Yavsc": {
"ClientId": "016c5ae4-f4cd-40e3-b250-13701c871ecd",
"ClientSecret": "blahblah"
}
}
}

View File

@ -7,6 +7,9 @@
"defaultNamespace": "testOauthClient"
},
"dependencies": {
"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-rc1-final",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
"Microsoft.AspNet.Authentication.OAuth": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
@ -18,9 +21,7 @@
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-rc1-final",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final"
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel --server.urls=http://*:5002"