Specify login_hint using .NET Google.Apis.Oauth2.v2 - google-oauth

Since the Google.Apis.Oauth2.v2 in GoogleWebAuthorizationBroker.AuthorizeAsync() requests a uri to a static json file that contains the links and parameters to Google Oauth2 services, how can I specify the login_hint parameter if I happen to know that information ahead of time?
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secret.json"),
myScopes,
"user",
CancellationToken.None);
Extract from client_secret.json:
"auth_uri":"https://accounts.google.com/o/oauth2/auth?login_hint=user#domain.com"
How to specify the login_hint parameteron a per user basis?

I ended up subclassing the Google web authorization broker like this:
public class MyOAuth2WebAuthorizationBroker : GoogleWebAuthorizationBroker
{
public static async Task<UserCredential> AuthorizeAsync(ClientSecrets clientSecrets,
IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken)
{
var initializer = new MyOAuth2AuthorizationCodeFlow.Initializer
{
ClientSecrets = clientSecrets,
Scopes = scopes,
DataStore = new StorageDataStore(),
};
var installedApp = new AuthorizationCodeWindowsInstalledApp(new MyOAuth2AuthorizationCodeFlow(initializer, user));
return await installedApp.AuthorizeAsync(user, taskCancellationToken).ConfigureAwait(false);
}
public class MyOAuth2AuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
private string loginHint { get; set; }
public MyOAuth2AuthorizationCodeFlow(Initializer initializer, string loginHint) : base(initializer)
{
this.loginHint = loginHint;
}
public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)
{
return new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
{
ClientId = ClientSecrets.ClientId,
Scope = string.Join(" ", Scopes),
RedirectUri = redirectUri,
LoginHint = this.loginHint
};
}
}
}

Related

Azure Devops Oauth authentication: Cannot get access token (BadRequest Failed to deserialize the JsonWebToken object)

I'm trying to implement an OAUth 2.0 flow for custom webapplication for Azure Devops. I'm following this https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops documentation as well as this https://github.com/microsoft/azure-devops-auth-samples/tree/master/OAuthWebSample OauthWebSample but using ASP.NET Core (I also read one issue on SO that looked similar but is not: Access Azure DevOps REST API with oAuth)
Reproduction
I have registered an azdo app at https://app.vsaex.visualstudio.com/app/register and the authorize step seems to work fine, i.e. the user can authorize the app and the redirect to my app returns something that looks like a valid jwt token:
header: {
"typ": "JWT",
"alg": "RS256",
"x5t": "oOvcz5M_7p-HjIKlFXz93u_V0Zo"
}
payload: {
"aui": "b3426a71-1c05-497c-ab76-259161dbcb9e",
"nameid": "7e8ce1ba-1e70-4c21-9b51-35f91deb6d14",
"scp": "vso.identity vso.work_write vso.authorization_grant",
"iss": "app.vstoken.visualstudio.com",
"aud": "app.vstoken.visualstudio.com",
"nbf": 1587294992,
"exp": 1587295892
}
The next step is to get an access token which fails with a BadReqest: invalid_client, Failed to deserialize the JsonWebToken object.
Here is the full example:
public class Config
{
public string ClientId { get; set; } = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public string Secret { get; set; } = "....";
public string Scope { get; set; } = "vso.identity vso.work_write";
public string RedirectUri { get; set; } = "https://....ngrok.io/azdoaccount/callback";
}
/// <summary>
/// Create azdo application at https://app.vsaex.visualstudio.com/
/// Use configured values in above 'Config' (using ngrok to have a public url that proxies to localhost)
/// navigating to localhost:5001/azdoaccount/signin
/// => redirect to https://app.vssps.visualstudio.com/oauth2/authorize and let user authorize (seems to work)
/// => redirect back to localhost:5001/azdoaccount/callback with auth code
/// => post to https://app.vssps.visualstudio.com/oauth2/token => BadReqest: invalid_client, Failed to deserialize the JsonWebToken object
/// </summary>
[Route("[controller]/[action]")]
public class AzdoAccountController : Controller
{
private readonly Config config = new Config();
[HttpGet]
public ActionResult SignIn()
{
Guid state = Guid.NewGuid();
UriBuilder uriBuilder = new UriBuilder("https://app.vssps.visualstudio.com/oauth2/authorize");
NameValueCollection queryParams = HttpUtility.ParseQueryString(uriBuilder.Query ?? string.Empty);
queryParams["client_id"] = config.ClientId;
queryParams["response_type"] = "Assertion";
queryParams["state"] = state.ToString();
queryParams["scope"] = config.Scope;
queryParams["redirect_uri"] = config.RedirectUri;
uriBuilder.Query = queryParams.ToString();
return Redirect(uriBuilder.ToString());
}
[HttpGet]
public async Task<ActionResult> Callback(string code, Guid state)
{
string token = await GetAccessToken(code, state);
return Ok();
}
public async Task<string> GetAccessToken(string code, Guid state)
{
Dictionary<string, string> form = new Dictionary<string, string>()
{
{ "client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" },
{ "client_assertion", config.Secret },
{ "grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer" },
{ "assertion", code },
{ "redirect_uri", config.RedirectUri }
};
HttpClient httpClient = new HttpClient();
HttpResponseMessage responseMessage = await httpClient.PostAsync(
"https://app.vssps.visualstudio.com/oauth2/token",
new FormUrlEncodedContent(form)
);
if (responseMessage.IsSuccessStatusCode) // is always false for me
{
string body = await responseMessage.Content.ReadAsStringAsync();
// TODO parse body and return access token
return "";
}
else
{
// Bad Request ({"Error":"invalid_client","ErrorDescription":"Failed to deserialize the JsonWebToken object."})
string content = await responseMessage.Content.ReadAsStringAsync();
throw new Exception($"{responseMessage.ReasonPhrase} {(string.IsNullOrEmpty(content) ? "" : $"({content})")}");
}
}
}
When asking for access tokens the Client Secret and not the App Secret must be provided for the client_assertion parameter:

OpenIdConnect Redirect on Form POST

Why does a form POST with an expired access_token result in a GET when using the Microsoft.AspNetCore.Authentication.OpenIdConnect middleware? When this happens, any data entered into a form is lost, since it doesn't reach the HttpPost endpoint. Instead, the request is redirected to the same URI with a GET, following the signin-oidc redirect. Is this a limitation, or do I have something configured incorrectly?
I noticed this issue after shortening the AccessTokenLifetime with the intent of forcing the user's claims to be renewed more frequently (i.e. if the user were disabled or they had claims revoked). I have only reproduced this when the OpenIdConnect middleware's OpenIdConnectionOptions are set to true options.UseTokenLifetime = true; (setting this to false results in the authenticated user's claims not being updated as expected).
I was able to recreate and demonstrate this behavior using the IdentityServer4 sample quickstart 5_HybridFlowAuthenticationWithApiAccess with the following changes below. Basically, there is an authorized form that has an HttpGet and an HttpPost method. If you wait longer than the AccessTokenLifetime (configured to only 30 seconds in this example) to submit the form, the HttpGet method is called instead of the HttpPost method.
Modifications to MvcClient/Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options =>
{
// the following was added
options.SlidingExpiration = false;
})
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("openid");
options.Scope.Add("api1");
options.ClaimActions.MapJsonKey("website", "website");
// the following were changed
options.UseTokenLifetime = true;
options.Scope.Add("offline_access");
});
}
Modifications to the Client list in IdentityServer/Config.cs
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.Hybrid,
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1",
IdentityServerConstants.StandardScopes.OfflineAccess,
},
AllowOfflineAccess = true,
// the following properties were configured:
AbsoluteRefreshTokenLifetime = 14*60*60,
AccessTokenLifetime = 30,
IdentityTokenLifetime = 15,
AuthorizationCodeLifetime = 15,
SlidingRefreshTokenLifetime = 60,
RefreshTokenUsage = TokenUsage.OneTimeOnly,
UpdateAccessTokenClaimsOnRefresh = true,
RequireConsent = false,
}
Added to MvcClient/Controllers/HomeController
[Authorize]
[HttpGet]
[Route("home/test", Name = "TestRouteGet")]
public async Task<IActionResult> Test()
{
TestViewModel viewModel = new TestViewModel
{
Message = "GET at " + DateTime.Now,
TestData = DateTime.Now.ToString(),
AccessToken = await this.HttpContext.GetTokenAsync("access_token"),
RefreshToken = await this.HttpContext.GetTokenAsync("refresh_token"),
};
return View("Test", viewModel);
}
[Authorize]
[HttpPost]
[Route("home/test", Name = "TestRoutePost")]
public async Task<IActionResult> Test(TestViewModel viewModel)
{
viewModel.Message = "POST at " + DateTime.Now;
viewModel.AccessToken = await this.HttpContext.GetTokenAsync("access_token");
viewModel.RefreshToken = await this.HttpContext.GetTokenAsync("refresh_token");
return View("Test", viewModel);
}
After further research and investigation, I came to the conclusion that completing a form POST that is redirected to the OIDC provider is not supported out of the box (at least for Identity Server, but I suspect that is also true for other identity connect providers as well). Here is the only mention I can find of this: Sending Custom Parameters to Login Page
I was able to come up with a workaround for the issue, which I've outlined below and is hopefully useful to others. The key components are the following OpenIdConnect and Cookie middleware events:
OpenIdConnectEvents.OnRedirectToIdentityProvider - save Post requests for later retrieval
CookieAuthenticationEvents.OnValidatePrincipal - check for saved Post requests and update the current request with saved state
The OpenIdConnect middleware exposes the OnRedirectToIdentityProvider event which gives us the opportunity to:
determine if this is a form post for an expired access token
modify the RedirectContext to include a custom request id with the AuthenticationProperties Items dictionary
Map the current HttpRequest to an HttpRequestLite object that can be persisted to a cache store, I recommend using an expiring, distributed cache for load-balanced environments. I'm using a static dictionary here for simplicity
new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = async (context) =>
{
if (context.HttpContext.Request.Method == HttpMethods.Post && context.Properties.ExpiresUtc == null)
{
string requestId = Guid.NewGuid().ToString();
context.Properties.Items["OidcPostRedirectRequestId"] = requestId;
HttpRequest requestToSave = context.HttpContext.Request;
// EXAMPLE - saving this to memory which would work on a non-loadbalanced or stateful environment. Recommend persisting to external store such as Redis.
postedRequests[requestId] = await HttpRequestLite.BuildHttpRequestLite(requestToSave);
}
return;
},
};
The Cookie middleware exposes the OnValidatePrincipal event which gives us the opportunity to:
check the CookieValidatePrincipalContext for AuthenticationProperties Items for custom dictionary items. We check it for the ID of our saved/cached request
it's important that we remove the item after we read it so that subsequent requests do not replay the wrong form submission, setting ShouldRenew to true persists any changes on subsequent requests
check our external cache for items that match our key, I recommend using an expiring, distributed cache for load-balanced environments. I'm using a static dictionary here for simplicity
read our custom HttpRequestLite object and override the Request object in the CookieValidatePrincipalContext object
new CookieAuthenticationEvents
{
OnValidatePrincipal = (context) =>
{
if (context.Properties.Items.ContainsKey("OidcPostRedirectRequestId"))
{
string requestId = context.Properties.Items["OidcPostRedirectRequestId"];
context.Properties.Items.Remove("OidcPostRedirectRequestId");
context.ShouldRenew = true;
if (postedRequests.ContainsKey(requestId))
{
HttpRequestLite requestLite = postedRequests[requestId];
postedRequests.Remove(requestId);
if (requestLite.Body?.Any() == true)
{
context.Request.Body = new MemoryStream(requestLite.Body);
}
context.Request.ContentLength = requestLite.ContentLength;
context.Request.ContentLength = requestLite.ContentLength;
context.Request.ContentType = requestLite.ContentType;
context.Request.Method = requestLite.Method;
context.Request.Headers.Clear();
foreach (var header in requestLite.Headers)
{
context.Request.Headers.Add(header);
}
}
}
return Task.CompletedTask;
},
};
We need a class to map HttpRequest to/from for serialization purposes. This reads the HttpRequest and it's body without modifying the contents, it leaves the HttpRequest untouched for additional middleware that may try to read it after we do (this is important when trying to read the Body stream which can only be read once by default).
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Primitives;
public class HttpRequestLite
{
public static async Task<HttpRequestLite> BuildHttpRequestLite(HttpRequest request)
{
HttpRequestLite requestLite = new HttpRequestLite();
try
{
request.EnableRewind();
using (var reader = new StreamReader(request.Body))
{
string body = await reader.ReadToEndAsync();
request.Body.Seek(0, SeekOrigin.Begin);
requestLite.Body = Encoding.ASCII.GetBytes(body);
}
//requestLite.Form = request.Form;
}
catch
{
}
requestLite.Cookies = request.Cookies;
requestLite.ContentLength = request.ContentLength;
requestLite.ContentType = request.ContentType;
foreach (var header in request.Headers)
{
requestLite.Headers.Add(header);
}
requestLite.Host = request.Host;
requestLite.IsHttps = request.IsHttps;
requestLite.Method = request.Method;
requestLite.Path = request.Path;
requestLite.PathBase = request.PathBase;
requestLite.Query = request.Query;
requestLite.QueryString = request.QueryString;
requestLite.Scheme = request.Scheme;
return requestLite;
}
public QueryString QueryString { get; set; }
public byte[] Body { get; set; }
public string ContentType { get; set; }
public long? ContentLength { get; set; }
public IRequestCookieCollection Cookies { get; set; }
public IHeaderDictionary Headers { get; } = new HeaderDictionary();
public IQueryCollection Query { get; set; }
public IFormCollection Form { get; set; }
public PathString Path { get; set; }
public PathString PathBase { get; set; }
public HostString Host { get; set; }
public bool IsHttps { get; set; }
public string Scheme { get; set; }
public string Method { get; set; }
}

Why [Authorize] attribute return 401 status code JWT + Asp.net Web Api?

I'm having big trouble finding issue with the JWT token authentication with asp.net web api. This is first time I am dealing with JWT & Web Api authentication & Authorization.
I have implemented the following code.
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);
}
private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new OAuthTokenProvider(),
RefreshTokenProvider = new RefreshTokenProvider(),
AccessTokenFormat = new Provider.JwtFormat("http://localhost:49860")
};
// OAuth 2.0 Bearer Access Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
}
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = "http://localhost:49860";
string audienceId = Config.AudienceId;
byte[] audienceSecret = TextEncodings.Base64Url.Decode(Config.AudienceSecret);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
}
});
}
}
OAuthTokenProvider.cs
public class OAuthTokenProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// validate client credentials (demo)
// should be stored securely (salted, hashed, iterated)
context.Validated();
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
/***Note: Add User validation business logic here**/
if (context.UserName != context.Password)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{ "as:client_id", "Kaushik Thanki" }
});
ClaimsIdentity oAuthIdentity = new ClaimsIdentity("JWT");
var ticket = new AuthenticationTicket(oAuthIdentity, props);
context.Validated(ticket);
}
}
JwtFormat.cs
public class JwtFormat : ISecureDataFormat<AuthenticationTicket>
{
private readonly string _issuer = string.Empty;
public JwtFormat(string issuer)
{
_issuer = issuer;
}
public string Protect(AuthenticationTicket data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
string audienceId = Config.AudienceId;
string symmetricKeyAsBase64 = Config.AudienceSecret;
var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
var issued = data.Properties.IssuedUtc;
var expires = data.Properties.ExpiresUtc;
var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);
return jwt;
}
public AuthenticationTicket Unprotect(string protectedText)
{
throw new NotImplementedException();
}
}
RefreshTokenProvider.cs
public class RefreshTokenProvider : IAuthenticationTokenProvider
{
private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
public void Create(AuthenticationTokenCreateContext context)
{
throw new NotImplementedException();
}
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
var guid = Guid.NewGuid().ToString();
// maybe only create a handle the first time, then re-use for same client
// copy properties and set the desired lifetime of refresh token
var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
{
IssuedUtc = context.Ticket.Properties.IssuedUtc,
ExpiresUtc = DateTime.UtcNow.AddYears(1)
};
var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);
//_refreshTokens.TryAdd(guid, context.Ticket);
_refreshTokens.TryAdd(guid, refreshTokenTicket);
// consider storing only the hash of the handle
context.SetToken(guid);
}
public void Receive(AuthenticationTokenReceiveContext context)
{
throw new NotImplementedException();
}
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(context.Token, out ticket))
{
context.SetTicket(ticket);
}
}
}
Now Once I pass the authentication (Which I kept dummy for initial level matching same username & password) & got the token & refresh token.
When I request for method that is decorated with [Authorize] attribute, I always gets 401 status code.
I testing this method in postman following way
Any help or guidance will be really appreciated. I have invested my two days finding the solution for this but all in vain.

WebAPI : How to add the Account / Authentication logic to a self hosted WebAPI service

I just came across a great reference example of using authenticated WebAPI with AngularJS:
http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En?msg=4841205#xx4841205xx
An ideal solution for me would be to have such WebAPI service self hosted instead of running it as a Web application.
I just do not know where to place all of the authentication / authorization logic within a self hosted (OWIN / Topshelf) solution.
For example, in the Web app, we have these two files: Startup.Auth, and ApplicationOAuthProvider:
Startup.Auth:
public partial class Startup
{
static Startup()
{
PublicClientId = "self";
UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
}
ApplicationOAuthProvider:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
private readonly Func<UserManager<IdentityUser>> _userManagerFactory;
public ApplicationOAuthProvider(string publicClientId, Func<UserManager<IdentityUser>> userManagerFactory)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
if (userManagerFactory == null)
{
throw new ArgumentNullException("userManagerFactory");
}
_publicClientId = publicClientId;
_userManagerFactory = userManagerFactory;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// Add Access-Control-Allow-Origin header as Enabling the Web API CORS will not enable it for this provider request.
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (UserManager<IdentityUser> userManager = _userManagerFactory())
{
IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
}
return Task.FromResult<object>(null);
}
public static AuthenticationProperties CreateProperties(string userName)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "userName", userName }
};
return new AuthenticationProperties(data);
}
}
I'm looking for a way to integrate these into my OWIN self hosted app, and have these authentication features. start upon application startup, and function as they do in the Web app version.

ServiceStack Authenticate attribute does not checking if user is authenticated

Im trying to make a service can only be accessed if the client is authenticated and I put the Authenticate attribute but it did not work because when I can access the service without being authenticated. I placed the Authenticate attribute before the Request DTO , top of a service and before the Action. Here is some code of the service I want to secure
[Authenticate]
public class HelloService : Service
{
public const string HelloServiceCounterKey = "HelloServiceCounter";
public object Any(HelloRequest request)
{
var userSession = SessionAs<AppHost.CustomUserSession>();
Session.Set(HelloServiceCounterKey, Session.Get<int>(HelloServiceCounterKey) + 1);
var roles = string.Join(", ", userSession.Roles.ToArray());
return new HelloResponse { Result = "Hello, " + request.Name + ", your role(s): " + roles };
}
}
I have this in my AppHost Configure(Funq.Container container)
Plugins.Add(new AuthFeature(
() => new CustomUserSession(),
new[] { new CustomCredentialsAuthProvider() }
));
public class CustomUserSession : AuthUserSession
{
public string CompanyName { get; set; }
}
public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
if (!Membership.ValidateUser(userName, password)) return false;
var session = (CustomUserSession)authService.GetSession(false);
session.CompanyName = "Company from DB";
session.UserAuthId = userName;
session.IsAuthenticated = true;
// add roles
session.Roles = new List<string>();
if (session.UserAuthId == "admin") session.Roles.Add(RoleNames.Admin);
session.Roles.Add("User");
return true;
}
}
When access the service in the line of
var roles = string.Join(", ", userSession.Roles.ToArray());
obviosly return NULL because have not been autheticated.
What should do Authenticate attribute on this case?
you need to configure your authentication provider in you app host configuration as follows:
public override void Configure(Container container)
{
Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[]
{
your providers here...
}));
}
Edit:
Assuming that CustomUserSession inherits from IAuthSession you can change
var session = (CustomUserSession)authService.GetSession(false);
To
var session = authService.GetSession<CustomUserSession>();
and as far as I see you aren't saving the session after the authentication
try something like this:
public override object Authenticate(IServiceBase authService, IAuthSession session, ServiceStack.ServiceInterface.Auth.Auth request)
{
string userName = request.UserName;
string password = request.Password;
if (!LoginMatchesSession(session, userName))
{
authService.RemoveSession();
session = authService.GetSession();
}
if (TryAuthenticate(authService, userName, password))
{
authService.SaveSession(session, SessionExpiry);
if (session.UserAuthName == null)
session.UserAuthName = userName;
OnAuthenticated(authService, session, null, null);
return new AuthResponse
{
UserName = userName,
SessionId = session.Id,
ReferrerUrl = RedirectUrl
};
}
throw new HttpError(HttpStatusCode.BadRequest, "400", "wrong credentials");
}
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
var session = authService.GetSession<CustomUserSession>();
if (!Membership.ValidateUser(userName, password)) return false;
session.IsAuthenticated = true;
session.Id = authService.GetSessionId();
return true;
}
EDIT:
there's other missing part you need to configure a cacheclient since all the session are managed in cache
try something like that:
container.Register<ICacheClient>(new MemoryCacheClient(){FlushOnDispose = false});
can you update your code with your host configuration?