OAuth Api call success
This commit is contained in:
@ -1,147 +0,0 @@
|
||||
//
|
||||
// YavscAuthenticationHandler.cs
|
||||
//
|
||||
// Author:
|
||||
// Paul Schneider <paul@pschneider.fr>
|
||||
//
|
||||
// Copyright (c) 2016 GNU GPL
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yavsc.Authentication
|
||||
{
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
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.Extensions.Logging;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
public static class YavscAuthenticationExtensions
|
||||
{
|
||||
}
|
||||
|
||||
class YavscAuthenticationHandler : OAuthHandler<YavscAuthenticationOptions>
|
||||
{
|
||||
private ILogger _logger;
|
||||
private HttpClient _backchannel;
|
||||
|
||||
public YavscAuthenticationHandler(HttpClient backchannel, ILogger logger) : base (backchannel)
|
||||
{
|
||||
_backchannel = backchannel;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
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(
|
||||
Options.SignInAsAuthenticationType,
|
||||
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, Options.SignInAsAuthenticationType);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError("Authentication failed", ex);
|
||||
return new AuthenticationTicket(null, properties, this.Options.AuthenticationScheme);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,102 +0,0 @@
|
||||
//
|
||||
// YavscAuthenticationMiddleware.cs
|
||||
//
|
||||
// Author:
|
||||
// Paul Schneider <paul@pschneider.fr>
|
||||
//
|
||||
// Copyright (c) 2016 GNU GPL
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
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.Authentication
|
||||
{
|
||||
public class YavscAuthenticationMiddleware : OAuthMiddleware<YavscAuthenticationOptions>
|
||||
{
|
||||
RequestDelegate _next;
|
||||
ILogger _logger;
|
||||
|
||||
public YavscAuthenticationMiddleware(
|
||||
RequestDelegate next,
|
||||
IDataProtectionProvider dataProtectionProvider,
|
||||
ILoggerFactory loggerFactory,
|
||||
UrlEncoder encoder,
|
||||
IOptions<SharedAuthenticationOptions> sharedOptions,
|
||||
YavscAuthenticationOptions 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<YavscAuthenticationMiddleware>();
|
||||
|
||||
if (encoder == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(encoder));
|
||||
}
|
||||
|
||||
if (sharedOptions == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(sharedOptions));
|
||||
}
|
||||
|
||||
if (options == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
if(string.IsNullOrEmpty(options.SignInAsAuthenticationType))
|
||||
{
|
||||
options.SignInAsAuthenticationType = sharedOptions.Value.SignInScheme;
|
||||
}
|
||||
|
||||
if(options.StateDataFormat == null)
|
||||
{
|
||||
var dataProtector = dataProtectionProvider.CreateProtector(typeof(YavscAuthenticationMiddleware).FullName,
|
||||
options.AuthenticationScheme);
|
||||
|
||||
options.StateDataFormat = new PropertiesDataFormat(dataProtector);
|
||||
}
|
||||
}
|
||||
|
||||
// Called for each request, to create a handler for each request.
|
||||
protected override AuthenticationHandler<YavscAuthenticationOptions> CreateHandler()
|
||||
{
|
||||
return new YavscAuthenticationHandler(this.Backchannel,_logger);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,62 +0,0 @@
|
||||
//
|
||||
// YavscAuthenticationMiddlewareOptions.cs
|
||||
//
|
||||
// Author:
|
||||
// Paul Schneider <paul@pschneider.fr>
|
||||
//
|
||||
// Copyright (c) 2016 GNU GPL
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
using System;
|
||||
using Microsoft.AspNet.Authentication.OAuth;
|
||||
using Microsoft.AspNet.Http;
|
||||
|
||||
namespace Yavsc.Authentication
|
||||
{
|
||||
|
||||
public class YavscAuthenticationOptions: OAuthOptions
|
||||
{
|
||||
public YavscAuthenticationOptions()
|
||||
{}
|
||||
|
||||
public YavscAuthenticationOptions(string authType, string clientId, string clientSecret)
|
||||
{
|
||||
if (authType == null)
|
||||
throw new NotSupportedException();
|
||||
Description.AuthenticationScheme = authType;
|
||||
ClientId = clientId;
|
||||
ClientSecret = clientSecret;
|
||||
SignInAsAuthenticationType = authType;
|
||||
Scope.Clear();
|
||||
}
|
||||
public PathString TokenPath { get; set; }
|
||||
public PathString AuthorizePath { get; set; }
|
||||
|
||||
public PathString ReturnUrl { get; set; }
|
||||
public PathString LoginPath { get; set; }
|
||||
public PathString LogoutPath { get; set; }
|
||||
|
||||
internal string AuthenticationServerUri = "https://accounts.google.com/o/oauth2/auth";
|
||||
internal string TokenServerUri = "https://accounts.google.com/o/oauth2/token";
|
||||
|
||||
private string signInAsAuthenticationType = null;
|
||||
public string SignInAsAuthenticationType { get
|
||||
{ return signInAsAuthenticationType ; }
|
||||
set { signInAsAuthenticationType = value;
|
||||
ReturnUrl = new PathString("/signin-"+signInAsAuthenticationType.ToLower());
|
||||
} }
|
||||
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user