I downloaded the katana project and wanted to try the client/server in the sandbox project.
I rand into a problem at for OAuthValidateClientAuthenticationContext :
public bool TryGetFormCredentials(out string clientId, out string clientSecret)
{
clientId = Parameters.Get(Constants.Parameters.ClientId);
if (!String.IsNullOrEmpty(clientId))
{
clientSecret = Parameters.Get(Constants.Parameters.ClientSecret);
ClientId = clientId;
return true;
}
clientId = null;
clientSecret = null;
return false;
}
clientSecret is null and hence the following do not validated the client.
private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret))
{
if (clientId == "123456" && clientSecret == "abcdef")
{
context.Validated();
}
else if (context.ClientId == "7890ab" && clientSecret == "7890ab")
{
context.Validated();
}
}
return Task.FromResult(0);
}
Ensure the client_secret param doesn't contain a space in your post
client_secret[space] will fail.
Related
I would like to share some bit of experience and troubles that I met while doing a folder creation and moving by using RESTful API.
**Create a Folder: **
You will need sharePoint Token
public async Task<JObject> getSharePointToken()
{
var sharPointTokenRequestUrl = "https://accounts.accesscontrol.windows.net/" + _configuration["MicrosoftGraph: TenantId"] + "/tokens/OAuth/2";
var parameters = new Dictionary<string, string>();
parameters["grant_type"] = "client_credentials";
parameters["client_id"] = "your client id";
parameters["client_secret"] = "your client secret";
parameters["resource"] = "resource id";
var par = new FormUrlEncodedContent(parameters);
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), sharPointTokenRequestUrl))
{
var response = await httpClient.PostAsync(sharPointTokenRequestUrl, par);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
return result;
}
}
}
Also You will need XRequest Digest
public async Task<JObject> getXRequestDigest()
{
var sharPointXRequestDigesttUrl = "https://your site /_api/contextinfo";
var sharePointTokenString = getSharePointToken().Result.ToString();
var sharePointToken = JsonConvert.DeserializeObject<SharePointTokenDto>(sharePointTokenString);
var parameters = new Dictionary<string, string>();
var par = new FormUrlEncodedContent(parameters);
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + sharePointToken.access_token);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
using (var request = new HttpRequestMessage(new HttpMethod("POST"), sharPointXRequestDigesttUrl))
{
var response = await httpClient.PostAsync(sharPointXRequestDigesttUrl, par);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
return result;
}
}
}
Then you could Crate Folder In SharePoint
namespace Sharepoint.Dtos
{
public class SharePointTokenDto
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string not_before { get; set; }
public string expires_on { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
}
}
public async Task<Boolean> CrateFolderInSharePoint(string folderPath)
{
var sharePointTokenString = getSharePointToken().Result.ToString();
var sharePointToken = JsonConvert.DeserializeObject<SharePointTokenDto>(sharePointTokenString);
var xRequestDigest = await getXRequestDigest();
var FormDigestValue = xRequestDigest["d"]["GetContextWebInformation"]["FormDigestValue"];
var siteUrl = "https://yoursites-url/sites/SiteName/_api/web/folders";
var folderUrl = "/sites/SiteName/Shared Documents" + folderPath;
var body = new Dictionary<string, string>
{
{ "ServerRelativeUrl", folderUrl }
};
string bodyString = JsonConvert.SerializeObject(body);
bodyString.Insert(0, " \"__metadata\": { \"type\": \"SP.Folder\" } ");
var content = new StringContent(bodyString, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + sharePointToken.access_token);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
httpClient.DefaultRequestHeaders.Add("X-RequestDigest", FormDigestValue.ToString());
using (var request = new HttpRequestMessage(new HttpMethod("POST"), siteUrl))
{
var response = await httpClient.PostAsync(siteUrl, content);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
}
}
}
I am new to Nodejs .
I am trying to pass JWT token from Nodejs to java service class.
I am getting JWT token in a variable in Nodejs code that I need to pass to spring mvc application service class.
can anyone please help me on this?
And having confusion with how to integrate Nodejs with java if i pass variable from Nodejs to java?
Node code is,
module.exports = {
verifyReq: function (req, res, next) {
if (req.headers.authorization) {
res.setHeader('Content-Type', 'text/html');
res.write('<div id="_mscontent"><script src="URL"></script>');
var notAuthorized = false;
var authorization = req.headers.authorization;
console.log("authorization: " + authorization);
if (authorization) {
req.isAuthorized = true;
}
try {
var decodedJWT = JWT.decode(authorization.split(' ')[1], "", true);
} catch (e) {
notAuthorized = true;
}
else {
req.isAuthorized = false;
res.status(401);
res.end('Not Authorized!');
return;
}
return req.isAuthorized === true;
}
};
Java Code,
public class GetCarAssetValuesService {
private static String output;
private static String token;
private static Asset[] myObjects;
public void getAssets(String tokenToPass)
throws JsonParseException, JsonMappingException, IOException, JSONException {
System.out.println("In service");
HttpsURLConnection myURLConnection = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuilder strBuilder = new StringBuilder();
JSONObject jsonObj = new JSONObject(tokenToPass);
System.out.println("success_token= " + jsonObj);
token = jsonObj.getString("access_token");
System.out.println("Print token= " + token);
try {
URL url = new URL(
"Third Party URL");
myURLConnection = (HttpsURLConnection) url.openConnection();
String bearerAuth = "Bearer " + token;
myURLConnection.setRequestProperty("Authorization", bearerAuth);
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setDoOutput(true);
inputStream = myURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
if (myURLConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + myURLConnection.getResponseCode());
}
System.out.println("Here the control cars...");
System.out.println("Output from Server .... \n");
while ((output = bufferedReader.readLine()) != null) {
strBuilder.append(output);
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String mindsphereResponse = strBuilder.toString();
System.out.println("Responsesssssss" + mindsphereResponse);
ObjectMapper mapper = new ObjectMapper();
myObjects = mapper.readValue(mindsphereResponse, Asset[].class);
}
Here instead of passing "tokenToPass" i want to get this token from node js i.e.decodeJWT. This "tokenToPass" i am getting from other java service now i want it from Nodejs.
Thanks in Advance..!!!
You can set the JWT token in the HTTP Request header ( nodejs ) and API endpoint ( java ) can be get it from there.
HelloController.java
#Controller
public class HomeController {
#Autowire
private HomeService homeService;
#GetMapping("/hello")
public String home(HttpServletRequest request, Model model) {
helloService.invoke(request.getHeader('JWT_TOKEN_KEY'));
}
}
HelloService.java
#Service
public class HelloService {
public void invoke(jwtToken) {
// Use this jwttoken
}
}
NodeJS.js
var options = {
host: 'your_java_api_endpoint',
port: 80,
path: '/hello',
headers:{
'JWT_TOKEN_KEY':'json web token here'
}
};
http.get(options, function(res) {
res.on("data", function(responseData) {
console.log("data: " + responseData);
});
}).on('error', function(e) {
console.log("http error : " + e);
});
I am trying to call Azure Graph API to update the user details, I have verified the access to graph api from my Application in Azure. Below is my code
public async Task<HttpResponseMessage> UpdateUserDetails(string userId, string requestString)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentException("You must spectify a valid user Id", nameof(userId));
}
if(string.IsNullOrWhiteSpace(requestString))
{
return null;
}
var authContext = new AuthenticationContext(AzureAdConfig.Authority);
var getAccessToken = await authContext.AcquireTokenAsync(AzureAdConfig.GraphResourceId, new ClientCredential(AzureAdConfig.AppId, AzureAdConfig.AppKey));
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", getAccessToken.AccessToken);
string url = AzureAdConfig.GraphResourceId + AzureAdConfig.Tenant + "/users/" + userId + "?" + AzureAdConfig.GraphVersion;
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), url);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", getAccessToken.AccessToken);
request.Content = new StringContent(requestString, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(request);
return response;
}
Thanks in Advance
According to my test, you can not get HttpResponseMessage with await client.SendAsync(request) in console application. You should use client.SendAsync(request).Result to get HttpResponseMessage. This my code.
static void Main(string[] args)
{
Console.WriteLine( CallWebApiProtected("2778d832-402f-4bc2-aa28-0720c92947d5"));
Console.Read();
}
static HttpResponseMessage CallWebApiProtected(string userId)
{
string authority = "https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/oauth2/token"; //token endpoint https://login.microsoftonline.com/b29343ba-***/oauth2/token
string resourceUri = "https://graph.windows.net/";
string clientId = "6187f317-5f3c-447e-b0c4-1fd7c31ec14e";//your application id
string clientkey = "q6e2d7xPwfa5rWHDCV5Tv/75wVkAnsinAcgF5FFkf7Y=";//your app key
AuthenticationContext authContext = new AuthenticationContext(authority);
ClientCredential clientCredential = new ClientCredential(clientId, clientkey);
AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(resourceUri, clientCredential).Result;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Specify values for the following required parameters
queryString["api-version"] = "1.6";
// Specify values for path parameters (shown as {...})
var uri = "https://graph.windows.net/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/users/" +userId + "?" + queryString;
Console.WriteLine(uri);
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(uri);
//request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
request.Headers.Add("Authorization", "Bearer " + authenticationResult.AccessToken);
HttpResponseMessage response = client.SendAsync(request).Result;
return response;
}
Its result as below.
Besides,you can get HttpResponseMessage with await client.SendAsync(request) in web application. This my code.
public async System.Threading.Tasks.Task<ActionResult> About()
{
HttpResponseMessage response = await CallWebApiProtected("2778d832-402f-4bc2-aa28-0720c92947d5");
ViewBag.Message = response;
return View();
}
static async System.Threading.Tasks.Task<HttpResponseMessage> CallWebApiProtected(string userId)
{
string authority = "https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/oauth2/token"; //token endpoint https://login.microsoftonline.com/b29343ba-***/oauth2/token
string resourceUri = "https://graph.windows.net/";
string clientId = "6187f317-5f3c-447e-b0c4-1fd7c31ec14e";//your application id
string clientkey = "q6e2d7xPwfa5rWHDCV5Tv/75wVkAnsinAcgF5FFkf7Y=";//your app key
AuthenticationContext authContext = new AuthenticationContext(authority);
ClientCredential clientCredential = new ClientCredential(clientId, clientkey);
AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(resourceUri, clientCredential).Result;
Console.WriteLine("--------------------------------");
Console.WriteLine(authenticationResult.AccessToken);
Console.WriteLine("----------------------------");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Specify values for the following required parameters
queryString["api-version"] = "1.6";
// Specify values for path parameters (shown as {...})
var uri = "https://graph.windows.net/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/users/" + userId + "?" + queryString;
Console.WriteLine(uri);
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(uri);
//request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
request.Headers.Add("Authorization", "Bearer " + authenticationResult.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
return response;
}
}
Its result as below.
private static async Task CreateApplication(string tenantId, string
clientId, string redirectUri)
{
var graphUri = new Uri("https://graph.windows.net");
var serviceRoot = new Uri(graphUri, tenantId);
var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => AcquireTokenAsyncForUser("https://login.microsoftonline.com/"
+
tenantId, clientId, redirectUri));
var app = new Application
{
Homepage = "https://localhost",
DisplayName = "My Application",
LogoutUrl = "https://localhost",
IdentifierUris = new List<string> {
"https://tenant.onmicrosoft.com/MyApp" },
ReplyUrls = new List<string> { "https://localhost" }
};
await activeDirectoryClient.Applications.AddApplicationAsync(app);
Console.WriteLine(app.ObjectId);
}
I already create a OAuth Server and i would like to make a login to this site.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LocalLogin(LoginViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var member = memberService.VaildateMmember(model.UserName, model.Password);
if (member == null)
{
ModelState.AddModelError("", "Account or Password Error!");
return View(model);
}
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, member.AccountName),
new Claim(ClaimTypes.Name, member.AccountName),
new Claim(ClaimTypes.Email, member.Email),
new Claim(ClaimTypes.NameIdentifier, member.Id.ToString())
};
var claimsIdentity = new ClaimsIdentity(
claims,
DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(
new AuthenticationProperties
{
IsPersistent = true,
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromMinutes(30))
},
claimsIdentity);
return RedirectToAction("Index", "Home");
}
And i create my own AuthorizeAttribute.
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
return false;
var user = httpContext.User.Identity;
if (!user.IsAuthenticated) //here Always false
return false;
//CheckUser
if (Users.Length > 0 && !Users.Split(',').Contains(user.Name, StringComparer.OrdinalIgnoreCase))
return false;
//CheckRole
if (!IsHasRoles(user))
return false;
//CheckScope
if (!IsHasScope(user))
return false;
return true;
}
I don't know what's wrong here.
Why httpContext.User.Identity.IsAuthenticated always return false.