vaadin access session attribute that was put in filter - httprequest

I've got multiple filters.
In one of the filters I've got this code
HttpServletRequest request = (HttpServletRequest) req;
String url = request.getRequestURI();
HttpSession session = request.getSession();
if (request.getParameter("xxxx") != null)
session.setAttribute("xxxx", request.getParameter("xxxx"));
chain.doFilter(req, res);
For UI I use VAADIN 7.
And I decided to display the value of the parameter xxxx in the table.
So I wanted to do it like this
Table table = new Table("Data.");
table.setSizeFull();
table.addContainerProperty("Field", String.class, null);
table.addContainerProperty("Value", String.class, null);
table.setStyleName("wordwrap-table");
table.setStyleName("user-table");
Object attribute = VaadinSession.getCurrent().getAttribute("xxxx");
However attribute value is null.
Why? And how to resolve this problem?

You need another getSession() in there:
Object attribute = VaadinSession.getCurrent().getSession().getAttribute("xxxx");
The result of VaadinSession.getCurrent() is the current Vaadin Session. The next getSession() gets you the HTTP session, which is where your attributes live.

Related

Table.PutItemAsync of AWSSDK.DynamoDBv2 always returns null

In .net core 2.1 application I am adding a new record into DynamoDB table using Table.PutItemAsync of AWSSDK.DynamoDBv2 (v3.3.101.18) library:
var doc = await _table.PutItemAsync(document);
I can see that the record is successfully added in AWS Console, but it always returns null whereas the expected return value should be a Document:
public Task<Document> PutItemAsync(Document doc, CancellationToken cancellationToken = default);
I wonder if I am missing something obvious?
You need to specify the ReturnValues enum type in your PutItemOperationConfig and include this config in your request. The default is to return None. If you specify ReturnValues.AllOldAttributes (the only other option for this request), then you will get back a document with the old item's attributes if you overwrote an item or an empty item if you added a new item.
var putItemOperationConfig = new PutItemOperationConfig()
{
ReturnValues = ReturnValues.AllOldAttributes
};

How to get error or success result from Acumatica Web service api?

//LoginResult loginResult = context.Login("user","pass");
//if (loginResult.Code != ErrorCode.OK)
//Get Schema
//Insert
//Add fields values
//....
O301000.Actions.CopyOrder,
O301000.Actions.Save,
O301000.OrderSummary.OrderNbr
Submitresult = O301000.context.Submit(cmds);
How do I know if there was an error when inserting/saving the Order (or any other file)?
I just can find a value 'Submitresult.ErrorCode' like in the Login Result.
Mean while a have solve the issue, when inserting, by looking for the 'O301000.OrderSummary.OrderNbr' not null value.
But that does not works when updating a record.
You should always use a
try{Submitresult = O301000.context.Submit(cmds);}
catch(Exception ex){Console.WriteLine(ex.Message);}
when making these calls. If the SOAP calls returns an error, than the message is passed to the Exception object.

How to communicate WCF exceptions to WebClient

I have a WCF web service which throws exceptions when invalid data is submitted. The data is submitted via an HTTP Post using the WebClient object.
Here is the code for the web service:
[WebInvoke(UriTemplate = "update", Method = "POST")]
public JsonValue Update(HttpRequestMessage message)
{
var context = new Entities();
dynamic response = new JsonObject();
// in order to retrieve the submitted data easily, reference the data as a dynamic object
dynamic data = message.Content.ReadAs(typeof(JsonObject), new[] { new FormUrlEncodedMediaTypeFormatter() });
// retrieve the submitted data
int requestId = data.requestId;
int statusId = data.statusId;
string user = data.user;
string encryptedToken = data.token;
string notes = data.notes;
// retrieve the request with a matching Id
var request = context.Requests.Find(requestId);
// make sure the request exists
if (request == null)
throw new FaultException("The supplied requestId does not exist.");
// make sure the submitted encrypted token is valid
var token = DecryptToken(encryptedToken);
if (token == null)
throw new FaultException("Invalid security token.");
// TODO: Validate other token properties (e.g. email)?
if (!request.User.UserName.Equals(token.UserName))
throw new FaultException("Invalid security token.");
// additional logic removed ...
}
And here is the code that submits data to the web service:
// use the WebClient object to submit data to the WCF web service
using (var client = new WebClient())
{
client.Encoding = Encoding.UTF8;
// the data will be submitted in the format of a form submission
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = new NameValueCollection();
// prepare the data to be submitted
data.Add("requestId", requestId.ToString());
data.Add("statusId", this.StatusId);
data.Add("token", token.ToString());
data.Add("user", this.User);
data.Add("notes", this.Notes);
// submit the data to the web service
var response = client.UploadValues(this.Address, data);
}
I keep getting an exception with message: "The remote server returned an error: (500) Internal Server Error" at client.UploadValues(this.Address, data);.
Is there a way I can make sure that more detailed information is returned to the WebClient?
Also, how can I make sure that these exceptions (in the WCF service) are logged to the EventLog? (Basically I just need to know what happened).
Take a look at HttpResponseException (namespace Microsoft.ApplicationServer.Http.Dispatcher) - they're the way where you can control the response for error cases. You can specify the status code, and you have control over the HttpResponseMessage, in which you can control the message body.
On the client side, when you call WebClient.UploadValues, wrap that call and catch a WebException. If the service returns a response with a non-successful status code (e.g., 500, 400), the Response property of the WebException will have the body, in which you can read in your client.
Another option is to use HttpClient instead of the WebClient, in which case you can simply look at the HttpResponseMessage directly.

Varying WCF Security Roles/Claims by Method Parameter

I have a class that implements IAuthorizationPolicy. I set up a custom Principal object based on the logged in user which has all of my base level roles (I have also done this using claims). Now I would like to change the roles that a particular principal has depending on a key value passed in as a message parameter.
The problem I am having is that the request message cannot be read in the authorization policy class because I don't have access to write the message back to the request context. I can copy and read the message in a ServiceAuthorizationManager derived class using an override of the CheckAccess method. However, I have to ensure that the GetAuthorizationPolicies method has already been called prior to doing that.
I am looking for suggestions on how I can vary the roles on a principal, based on whether or not the message contains a particular parameter. Basically, when the Evaluate method id called on the policy I want to do something like this:
string myObjectId = null;
if (!messageCopy.IsEmpty)
{
System.Xml.XmlDictionaryReader xdr = messageCopy.GetReaderAtBodyContents();
xdr.ReadToDecendant("objectId");
if (xdr.Read())
{
myObjectId = xdr.ReadContentAsString();
}
xdr.Close();
}
messageCopy.Close();
ClaimSet claims = (myObjectId != null) ?
MapClaims(identity, myObjectId) : MapClaims(identity);
DefaultPrincipal principal = new DefaultPrincipal(identity, claims);
After an entire day of attempted failures, I gave up on trying to read the message body and used an easier method, adding a SOAP message header. When calling the service I now perform the following:
using (new OperationContextScope((IContextChannel)myService)) {
OperationContext.Current.OutgoingMessageHeaders.Add(
MessageHeader.CreateHeader("objectId", "http://tempuri.org/", "object value"));
myService.BeginMyOperation(parm, callback, state);
}
Then in my service authorization policy's Evaluate method I do this:
int index = OperationContext.Current.IncomingMessageHeaders.FindHeader(
"objectId", "http://tempuri.org/");
string myObjectId = (index < 0) ? null :
OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(index);
ClaimSet claims = (myObjectId != null) ?
MapClaims(identity, myObjectId) : MapClaims(identity);
DefaultPrincipal principal = new DefaultPrincipal(identity, claims);
I run into the same situation while developing WebAPI security and I choosen the next approach:
Method that recieves argument creates AuthorizationContext where it passes the argument as Resource claim
My custom ClaimsAuthorizationManager then can get argument from AuthorizationContext.Resource and use it from authorization.

how to get authenticated user id from wcf in nhibernate

I have implemented NHibernate custom context (ICurrentSessionContext).
In this context I inject the NHibernate session so I have Session per call pattern setup.
Ok, now I have made an interceptor that takes userId of the current logged user.
Now I do this:
public ISession CurrentSession()
{
// Get the WCF InstanceContext:
var contextManager = OperationContext.Current.InstanceContext.Extensions.Find<NHibernateContextManager>();
if (contextManager == null)
{
throw new InvalidOperationException(
#"There is no context manager available.
Check whether the NHibernateContextManager is added as InstanceContext extension.
Make sure the service is being created with the NhServiceHostFactory.
This Session Provider is intended only for WCF services.");
}
var session = contextManager.Session;
AuditLogInterceptor interceptor = new AuditLogInterceptor();
if (session == null)
{
session = this._factory.OpenSession(interceptor);
interceptor.Session = session;
contextManager.Session = session;
}
return contextManager.Session;
}
My AuditLogInterceptor takes UserId but I don't know how (from where) to get this userId.
If your user is authenticated you can use:
OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name
I assume that the current user is being set as the principal on the current thread?
If so, something like this is what you need:
var userName = Thread.CurrentPrincipal.Identity.Name;
There is some additional information in this article that may prove helpful.