Authorization not working in swagger jersey, authorization checkbox is not showing - authorization

Screenshot
List<AuthorizationScope> scopes = new ArrayList<AuthorizationScope>();
scopes.add(new AuthorizationScope("pets", "Access all"));
List<GrantType> grantTypes = new ArrayList<GrantType>();
ImplicitGrant implicitGrant = new ImplicitGrant(new LoginEndpoint("url"), "access_code");
grantTypes.add(implicitGrant);
AuthorizationType oauth = new OAuthBuilder().scopes(scopes).grantTypes(grantTypes).build();
config.addAuthorization(oauth);
// i am using com.wordnik swagger-jaxrs_2.10 1.3.12

Related

PKCE flow Error code: 500 code challenge required

I'm trying to get the PKCE example to work, but I keep hitting
Error code: 500
Error: invalid_request : code challenge required
Here's a sample url, it does include a code_challenge param generated with the example code.
https://login.xero.com/identity/connect/authorize
?client_id=XXX
&response_type=code
&scope=openid%20profile%20email%20offline_access%20files%20accounting.transactions%20accounting.contacts&redirect_uri=https%3A%2F%2Flocalhost%3A5001%2F
&code_challenge=tj6n3SLd6FZ8g6jjSJYvfC--4r2PHGnpbSGTwIreNqQ
&code_challenge_method=S256
The registered app is a PKCE flow, kind of out of options what it could be.
Here's the code I use, the only changes are the last 2 lines where I launch the browser a I'm connecting from a desktop app. Tried pasting the generated url into the browser directly but that also didn't work.
XeroConfiguration xconfig = new XeroConfiguration();
xconfig.ClientId = "XXX";
xconfig.CallbackUri = new Uri("https://localhost:5001"); //default for standard webapi template
xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";
//xconfig.State = "YOUR_STATE"
var client = new XeroClient(xconfig);
// generate a random codeVerifier
var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";
Random random = new Random();
int charsLength = random.Next(43, 128);
char[] randomChars = new char[charsLength];
for (int i = 0; i < charsLength; i++) {
randomChars[i] = validChars[random.Next(0, validChars.Length)];
}
string codeVerifier = new String(randomChars);
var uri = client.BuildLoginUriPkce(codeVerifier);
Clipboard.SetText(uri);
System.Diagnostics.Process.Start("explorer.exe", $"\"{uri}\"");

Error when changing password in AD LDS

I have problem when implemented password updating of user in AD LDS: it throws below error when calling connection.Modify().
Does anybody have experience with ADLDS and its errors?
Operations Error:00002077: SvcErr: DSID-03380736, problem 5012 (DIR_ERROR), data 8237
Code as below:
var entry = GetUserEntry(userName, AttributeList(AttributeTypes.Basic));
//create the ldap modifications
var modifications = new LdapModification[2];
var deletePassword = new LdapAttribute(application.UserPasswordAttribute, oldPassword);
modifications[0] = new LdapModification(LdapModification.DELETE, deletePassword);
var addPassword = new LdapAttribute(application.UserPasswordAttribute, newPassword);
modifications[1] = new LdapModification(LdapModification.ADD, addPassword);
//perform the modification
connection.Modify(entry.DN, modifications);
The entry.DN includes: "CN=user1,CN=Users,CN=sampleInstance,DC=local,DC=com".
By the way, I'm using SSL connection.

Azure Pack REST API Authentication

After hours of search in Microsoft messed up API documentation for its products, i am still no where on how to authenticate a rest API request in windows azure pack distribution.
Primarily i want to create an API which automate the process of deploying virtual machine, but I cant find any documentation on how to acquire the authentication token to access the resources.
Some documentation states the use of ADFS, but don't provide any reference on the ADFS REST API for authentication.
And I don't want to use ADFS in the first place. I want to authenticate using AZURE tenant and admin interface.
In conclusion, if anyone can provide any help on the REST API authentication, it will make my day.
Thanks in advance.
You can use the following PowerShell to acquire an access token.
Add-Type -Path 'C:\Program Files\Microsoft Azure Active Directory Connect\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
$tenantID = "<the tenant id of you subscription>"
$authString = "https://login.windows.net/$tenantID"
# It must be an MFA-disabled admin.
$username = "<the username>"
$password = "<the password>"
# The resource can be https://graph.windows.net/ if you are using graph api.
# Or, https://management.azure.com/ if you are using ARM.
$resource = "https://management.core.windows.net/"
# This is the common client id.
$client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" `
-ArgumentList $username,$password
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" `
-ArgumentList $authString
$authenticationResult = $authContext.AcquireToken($resource,$client_id,$creds)
# An Authorization header can be formed like this.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
I am doing some similar job like you did.
static string GetAspAuthToken(string authSiteEndPoint, string userName, string password)
{
var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + "/wstrust/issue/usernamemixed"));
var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
identityProviderBinding.Security.Message.EstablishSecurityContext = false;
identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
{
TrustVersion = TrustVersion.WSTrust13,
};
//This line is only if we're using self-signed certs in the installation
trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };
trustChannelFactory.Credentials.SupportInteractive = false;
trustChannelFactory.Credentials.UserName.UserName = userName;
trustChannelFactory.Credentials.UserName.Password = password;
var channel = trustChannelFactory.CreateChannel();
var rst = new RequestSecurityToken(RequestTypes.Issue)
{
AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
TokenType = "urn:ietf:params:oauth:token-type:jwt",
KeyType = KeyTypes.Bearer,
};
RequestSecurityTokenResponse rstr = null;
SecurityToken token = null;
token = channel.Issue(rst, out rstr);
var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));
return jwtString;
}
Parameter "authSiteEndPoint" is your Tenant Authentication site url.
default port is 30071.
You can find some resource here:
https://msdn.microsoft.com/en-us/library/dn479258.aspx
The sample program "SampleAuthApplication" can solve your question.

InsertAll using C# not working

I´d like to know why this code is not working. It runs without errors but rows are not inserted. I´m using C# client library.
Any ideas? Thanks!!
string SERVICE_ACCOUNT_EMAIL = "(myserviceaccountemail)";
string SERVICE_ACCOUNT_PKCS12_FILE_PATH = #"C:\(myprivatekeyfile)";
System.Security.Cryptography.X509Certificates.X509Certificate2 certificate =
new System.Security.Cryptography.X509Certificates.X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret",
System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
{
Scopes = new[] { BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.Bigquery }
}.FromCertificate(certificate));
// Create the service.
var service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "test"
});
Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest tabreq = new Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest();
List<Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData> tabrows = new List<Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData>();
Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData rd = new Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData();
IDictionary<string,object> r = new Dictionary<string,object>();
r.Add("campo1", "test4");
r.Add("campo2", "test5");
rd.Json = r;
tabrows.Add(rd);
tabreq.Rows = tabrows;
service.Tabledata.InsertAll(tabreq, "(myprojectid)", "spots", "spots");
I think you should add the Kind field [1]. It should be something like this:
tabreq.Kind = "bigquery#tableDataInsertAllRequest";
Also remeber that every request of the API has a response [2] with additional info to help you find the issue's root cause.
var requestResponse = service.Tabledata.InsertAll(tabreq, "(myprojectid)", "spots", "spots");
[1] https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/csharp/latest/classGoogle_1_1Apis_1_1Bigquery_1_1v2_1_1Data_1_1TableDataInsertAllRequest.html#aa2e9b0da5e15b158ae0d107378376b26
[2] https://cloud.google.com/bigquery/docs/reference/v2/tabledata/insertAll

How to insert rule in Google Calendar ACL from Google Apps Script

How can I add a new user to the ACL for a Google Calendar? I'm trying to send a POST HTTP request. Perhaps there is something wrong with the XML? The code below generates a server error (400). (Edit: Shows the oAuth).
//---------------------------------------------------------------
// Add a rule to the Access Control List for 'Fake Calendar 1.0'
//---------------------------------------------------------------
function addRule() {
// Get Calendar ID, script user's email, and the API Key for access to Calendar API
var calId = '12345calendar.google.com';
var userEmail = Session.getActiveUser().getEmail();
var API_KEY = 'ABC123';
var newUserEmail = 'person#example.net';
// Get authorization to access the Google Calendar API
var apiName = 'calendar';
var scope = 'https://www.googleapis.com/auth/calendar';
var fetchArgs = googleOAuth_(apiName, scope);
fetchArgs.method = 'POST';
var rawXML = "<entry xmlns='http://www.w3.org/2005/Atom' " +
"xmlns:gAcl='http://schemas.google.com/acl/2007'>" +
"<category scheme='http://schemas.google.com/g/2005#kind' " +
"term='http://schemas.google.com/acl/2007#accessRule'/>" +
"<gAcl:role value='owner'/>" +
"<gAcl:scope type='user' value='"+userEmail+"'/>" +
"</entry>";
fetchArgs.payload = rawXML;
fetchArgs.contentType = 'application/atom+xml';
// Get the requested content (the ACL for the calendar)
var base = 'https://www.googleapis.com/calendar/v3/calendars/';
var url = base + calId + '/acl?key=' + API_KEY;
var content = UrlFetchApp.fetch(url, fetchArgs).getContentText();
Logger.log(content);
}
//--------------------------------------------------------------
// Google OAuth
//--------------------------------------------------------------
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
Have you gone through the oAuth authorization process before executing this piece of code. Your app has to be explicitly authorized before it can do anything significant with the Calendar API
Srik is right. You need to use oAuth Arguments in your UrlFetchApp.
Given Reference URL shows few examples for using oAuth in Apps script to work with Google's REST APIs
https://sites.google.com/site/appsscripttutorial/urlfetch-and-oauth