public async Task <IEnumerable <string> > ResolveAccessibleResources(string identityToken) { if (string.IsNullOrWhiteSpace(identityToken)) { throw new ArgumentNullException(nameof(identityToken)); } var getHierarchicalResource = await _hierarchicalResourceClientFactory.GetHierarchicalResourceClient() .Get(new Uri(_resourceManagerResolverOptions.ResourceManagerUrl), _resourceManagerResolverOptions.Url, true); var resources = getHierarchicalResource.Content.Where(r => !string.IsNullOrWhiteSpace(r.ResourceId)); var resourcePathLst = getHierarchicalResource.Content.Where(r => string.IsNullOrWhiteSpace(r.ResourceId)).Select(r => r.Path).ToList(); var grantedToken = await _identityServerClientFactory.CreateAuthSelector() .UseClientSecretPostAuth(_resourceManagerResolverOptions.Authorization.ClientId, _resourceManagerResolverOptions.Authorization.ClientSecret) .UseClientCredentials("uma_protection") .ResolveAsync(_resourceManagerResolverOptions.Authorization.AuthorizationWellKnownConfiguration); var tasks = new List <Task <string> >(); foreach (var resource in resources) { tasks.Add(ResolveUrl(resource, grantedToken.Content.AccessToken, identityToken)); } var grantedPathLst = (await Task.WhenAll(tasks)).Where(p => !string.IsNullOrWhiteSpace(p)); resourcePathLst.AddRange(grantedPathLst); return(resourcePathLst); }
public async Task <IActionResult> Get(string id) { if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentNullException(nameof(id)); } var information = _informations.FirstOrDefault(i => i.Id == id); if (information == null) { return(new NotFoundResult()); } string accessToken; var grantedToken = await GetAccessToken(); // 1. Get an access token. if (!TryGetAccessToken(out accessToken)) // 2 Try to get the RPT tokens { var ticket = await _identityServerUmaClientFactory.GetPermissionClient() // 2.1 Get permission ticket. .AddByResolution(new PostPermission { ResourceSetId = information.ResourceId, Scopes = new[] { "read" } }, "https://localhost:5445/.well-known/uma2-configuration", grantedToken.AccessToken); var ticketId = ticket.TicketId; var jObj = new JObject(); jObj.Add("ticket_id", ticketId); return(new OkObjectResult(jObj)); } var introspectionResult = await _identityServerClientFactory.CreateAuthSelector() .UseClientSecretPostAuth("resource_server", "resource_server") .Introspect(accessToken, TokenType.AccessToken) .ResolveAsync("https://localhost:5445/.well-known/uma2-configuration"); if (!introspectionResult.Active) { return(null); } var payload = _jwsParser.GetPayload(accessToken); if (!payload.ContainsKey("ticket")) { return(null); } var ticketObj = JArray.Parse(payload["ticket"].ToString()); // CHECK THE TICKET IS CORRECT. return(null); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticateRequest authenticateRequest) { Check(authenticateRequest); var grantedToken = await _identityServerClientFactory.CreateAuthSelector().UseClientSecretBasicAuth(Constants.ClientId, Constants.ClientSecret) .UsePassword(authenticateRequest.Login, authenticateRequest.Password, "openid", "profile", "role") .ResolveAsync(Constants.OpenIdWellKnownConfiguration) .ConfigureAwait(false); if (grantedToken.ContainsError) { return(new UnauthorizedResult()); } return(new OkObjectResult(grantedToken.Content)); }
public AuthenticationProvider( AuthOptions options, IIdentityServerClientFactory identityServerClientFactory) { _authOptions = options; _clientAuthSelector = identityServerClientFactory.CreateAuthSelector(); }
public async Task <IActionResult> Callback(string code, string state) { if (!Request.Cookies.ContainsKey(Constants.TMP_COOKIE_NAME)) { return(new UnauthorizedResult()); } var cookieContent = JsonConvert.DeserializeObject <CookieContent>(Request.Cookies[Constants.TMP_COOKIE_NAME]); if (cookieContent.State != state) { return(new UnauthorizedResult()); } var redirectUrl = $"{Request.GetAbsoluteUriWithVirtualPath()}/Authenticate/Callback"; var grantedToken = await _identityServerClientFactory.CreateAuthSelector().UseClientSecretPostAuth(_options.ClientId, _options.ClientSecret) .UseAuthorizationCode(code, redirectUrl) .ResolveAsync(_options.OpenidWellKnownConfigurationUrl).ConfigureAwait(false); if (grantedToken.ContainsError) { return(new UnauthorizedResult()); } if (!await AddCookie(grantedToken.Content.IdToken, cookieContent.Nonce).ConfigureAwait(false)) { return(new UnauthorizedResult()); } return(RedirectToAction("Index", "Home")); }
public async Task <IActionResult> Authenticate(AuthenticateViewModel viewModel) { if (viewModel == null) { throw new ArgumentNullException(nameof(viewModel)); } var result = await _identityServerClientFactory.CreateAuthSelector() .UseClientSecretBasicAuth("ProtectedWebsite", "ProtectedWebsite") .UsePassword(viewModel.Login, viewModel.Password, "openid", "profile") .ResolveAsync(Constants.OpenIdUrl); if (result.Content == null) { System.Console.WriteLine("error"); } else { System.Console.WriteLine("bingo"); } var userInfo = await _identityServerClientFactory.CreateUserInfoClient() .Resolve(Constants.OpenIdUrl, result.Content.AccessToken).ConfigureAwait(false); var claims = new List <Claim>(); claims.Add(new Claim("sub", userInfo.Content["sub"].ToString())); claims.Add(new Claim("id_token", result.Content.IdToken)); await SetLocalCookie(claims); var accessibleResources = await _resourceManagerResolver.ResolveAccessibleResources(result.Content.IdToken); this.PersistAccessibleResources(accessibleResources.ToList(), _dataProtector); return(RedirectToAction("Index", "Home")); }
public async Task <string> GetAccessToken() { var token = await _identityServerClientFactory.CreateAuthSelector() .UseClientSecretPostAuth("ResourceManagerApi", "ResourceManagerApi") .UseClientCredentials("display_configuration", "manage_configuration") .ResolveAsync("https://localhost:5443/.well-known/openid-configuration") .ConfigureAwait(false); return(null); }
public async Task <GrantedTokenResponse> GetToken(string url, string clientId, string clientSecret, IEnumerable <string> scopes) { if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentNullException(nameof(url)); } if (string.IsNullOrWhiteSpace(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (string.IsNullOrWhiteSpace(clientSecret)) { throw new ArgumentNullException(nameof(clientId)); } if (scopes == null) { throw new ArgumentNullException(nameof(scopes)); } var token = await GetToken(url, scopes).ConfigureAwait(false); if (token != null) { if (DateTime.UtcNow < token.ExpirationDateTime) { return(token.GrantedToken); } await RemoveToken(token).ConfigureAwait(false); } var grantedToken = await _identityServerClientFactory.CreateAuthSelector() .UseClientSecretPostAuth(clientId, clientSecret) .UseClientCredentials(scopes.ToArray()) .ResolveAsync(url) .ConfigureAwait(false); var storedToken = new StoredToken { GrantedToken = grantedToken.Content, ExpirationDateTime = DateTime.UtcNow.AddSeconds(grantedToken.Content.ExpiresIn), Scopes = scopes, Url = url }; await AddToken(storedToken).ConfigureAwait(false); return(grantedToken.Content); }
public async Task <IActionResult> Authenticate([FromBody] JObject json) { if (json == null) { return(StatusCode((int)HttpStatusCode.InternalServerError, new ErrorResponse(Constants.ErrorCodes.IncompleteRequest, "The login and password must be specified").GetJson())); } JToken jLogin; if (!json.TryGetValue(Constants.AuthenticateDtoNames.Login, out jLogin)) { return(StatusCode((int)HttpStatusCode.InternalServerError, new ErrorResponse(Constants.ErrorCodes.IncompleteRequest, "the login must be specified").GetJson())); } JToken jPassword; if (!json.TryGetValue(Constants.AuthenticateDtoNames.Password, out jPassword)) { return(StatusCode((int)HttpStatusCode.InternalServerError, new ErrorResponse(Constants.ErrorCodes.IncompleteRequest, "the password must be specified").GetJson())); } var wellKnownConfiguration = _configuration["OpenId:WellKnownConfiguration"]; if (string.IsNullOrWhiteSpace(wellKnownConfiguration)) { return(StatusCode((int)HttpStatusCode.InternalServerError, new ErrorResponse(Constants.ErrorCodes.InvalidConfiguration, "the well-known configuration is not specified").GetJson())); } var grantedToken = await _identityServerClientFactory.CreateAuthSelector() .UseClientSecretPostAuth(Constants.ClientId, Constants.ClientSecret) .UsePassword(jLogin.ToString(), jPassword.ToString(), "openid", "profile") .ResolveAsync(wellKnownConfiguration); var result = new JObject(); result.Add(Constants.GrantedTokenNames.AccessToken, grantedToken.AccessToken); result.Add(Constants.GrantedTokenNames.IdToken, grantedToken.IdToken); result.Add(Constants.GrantedTokenNames.ExpiresIn, grantedToken.ExpiresIn); result.Add(Constants.GrantedTokenNames.RefreshToken, grantedToken.RefreshToken); result.Add(Constants.GrantedTokenNames.Scope, new JArray(grantedToken.Scope)); result.Add(Constants.GrantedTokenNames.TokenType, grantedToken.TokenType); return(new OkObjectResult(result)); }