I'm trying to invalidate a cookie created by my code. I want to do this creating a new endpoint to logout. I have to choose between two paths to redirect depending on whether an endpoint returns data or not. When I run the code locally it works like a charm. Deletes the cookie and redirects to the correct url but, if I test it deployed on a remote server, it doesn't work, meaning that it redirects correctly but doesn't expire the cookie nor modifies its value. My whole code must be a back end one so i cannot redirect to a javascript that would delete the cookie and redirect again.
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public void cookieKiller(
#CookieValue(name = "theCookie", required = false) Cookie myCookie,
HttpServletResponse response, HttpServletRequest request) {
if (myCookie != null) {
} else { // Just being cautious, if the cookie is not retrieved, would be overwritten anyway just in case
myCookie = new Cookie("theCookie","");
}
myCookie.setMaxAge(0);
myCookie.setValue("");
myCookie.setPath("/");
response.addCookie(myCookie);
boolean endpointHealthy = true;
if(haveITheEndpointUrls()) {
endpointHealthy = false;
} else {
try {
String eaiResponseJson = restTemplateAutowired.getForEntity(new URI(oneUrl),String.class).getBody();
if (eaiResponseJson != null && !eaiResponseJson.isBlank()) {
response.sendRedirect(eaiSamlUrl);
} else {
endpointHealthy = false;
}
} catch (IOException e) {
endpointHealthy = false;
} catch (ResourceAccessException e) {
endpointHealthy = false;
} catch (HttpClientErrorException e) {
endpointHealthy = false;
} catch (Exception e) {
endpointHealthy = false;
}
}
if (!endpointHealthy) {
try {
response.sendRedirect(request.getContextPath() + "/internal/Path");
} catch (IOException ex) {
// ...
}
}
}
If I add a new cookie, the domain that is generated is different than the original one, introduced in the front part of the application. Being the back one "domain.com" and the front one ".domain.com" so I guess it's a domain thing
I've been trying to change the path, to change the value, etc, but it won't work either, i've surfed stackoverflow a lot in search for an answer but without any result. Some suggestion or clue about domains or any hint that i could've been missing?
My code in local was generating a cookie like domain.com but SHibboleth needs cookie domains starting with a dot. I tried to create a cookie this way but that was not possible in Tomcat unless you use a LegacyCookieManager.
Related
I have the following method, which deletes a file from AWS S3 Bucket, however,
there is no exception thrown if the file doesn't exist
there is no success code or flag to see if the file has been deleted successfully
is there any workaround to deal with this situation.
#Override
public void deleteFile(String fileName) {
try {
this.client.deleteObject(builder ->
builder
.bucket(this.bucketName).key(fileName)
.build());
} catch (S3Exception ex) {
ex.printStackTrace();
}
}
If your request succeeded then your object is deleted. Note, that due to eventual consistency, the object is not guaranteed to disappear immediately. You need to check on the HTTP status code.
AmazonS3 as3 = new AmazonS3();
Status myStatus = as3.DeleteObject(<fill in paramters here>);
if (myStatus.Code >= 200 && myStatus.Code < 300)
{
// Success
}
else
{
// Delete Failed
// Handle specific Error Codes below
if (myStatus.Description == "AllAccessDisabled")
{
// Do something
}
if (myStatus.Description == "NoSuchKey")
{
// Do something
}
}
Also, there is an api available to check if the Object exists in S3
doesObjectExist
https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/AmazonS3.html#doesObjectExist-java.lang.String-java.lang.String-
I've implemented an Alfresco repository webscript (in Java) to programmatically create a new site.
I notice that there's a SiteService interface which I thought could be used to do this -
SiteInfo site = siteService.createSite("site-dashboard", "mySite",
"mySite", "", SiteVisibility.PUBLIC);
However, this results in the creation of a non-functional site, and although it's visible within the Alfresco Share dashboard, I'm not able to use it.
I then came across this code sample, which is doing exactly what I want. BUT the code includes a section to do authentication, involving sending the user's login and password details to a dologin web service. Don't really want to do this.
But as the user has already logged in via Alfresco Share, they should already be authenticated.
If I call the create-site webscript from my code, as shown in the example (without the initial call to dologin), I'm getting a 401 (unauthorised) return code.
So my question is, how do I tell the create-site webscript about my authentication?
I read about using an authentication ticket here. Is this ticket stored in the session, and if so, how do I access it within my Java code? If I could get the ticket, then this would be sufficient to invoke the create-site webscript.
Update: I've added the alf_ticket parameter as suggested by the comment, but I'm still getting a 401 response.
My current code is:
public NodeRef createServiceChange(String serviceChangeName) {
HttpClient client = new HttpClient();
String ticket = authService.getCurrentTicket();
PostMethod createSitePost = new PostMethod("http://localhost:8081/share/service/modules/create-site");
JSONObject siteObject = new JSONObject();
try {
siteObject.put("shortName", serviceChangeName);
siteObject.put("visiblity", "Public");
siteObject.put("sitePreset", "site-dashboard");
siteObject.put("title", serviceChangeName);
siteObject.put("description", serviceChangeName);
siteObject.put("alf_ticket", ticket);
createSitePost.setRequestHeader("Content-Type", "application/json");
createSitePost.setRequestHeader("Accept", "application/json");
createSitePost.setRequestEntity(new StringRequestEntity(siteObject.toString(), "application/json", "UTF-8"));
int status = client.executeMethod(createSitePost);
System.out.println("create a site script status :: " + status);
if (status == HttpStatus.SC_OK) {
System.out.println("Site created OK");
}
else{
System.out.println("There is error in site creation");
}
} catch (JSONException err) {
err.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So I've managed to successfully create a site, programmatically, and here's what I did:
First, forget about writing a repository (platform) webscript. Creation of sites in Alfresco is done by invoking a Share module, so you'll need to implement either a page, or custom menu item to create a site. I was also getting a lot of problems with authentication, but if you log in to the system via Alfresco Share, and in your Javascript, use the provided Alfresco Ajax request, then authentication shouldn't be a problem.
Here are the components I used:-
Create a Share page to create your site. In the Freemarker template (.ftl) add a form to collect the site details.
Attach a button on the form to the following Javascript function. Note that I cobbled this together from various code fragments on the web, so it could use some cleaning up. But it basically works for me -
function create_site()
{
var sc_form = document.forms.namedItem('sc_form');
var name = sc_form.elements.namedItem('name').value;
var url = Alfresco.constants.URL_CONTEXT + "service/modules/create-site";
Alfresco.util.Ajax.request({
method : Alfresco.util.Ajax.POST,
url : url,
dataObj: {
sitePreset: "site-dashboard",
visibility: "PUBLIC",
title: name,
shortName: name,
description: name
},
requestContentType: Alfresco.util.Ajax.JSON,
successCallback:
{
fn: function(res){
alert("success");
alert(res.responseText);
},
scope: this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayPrompt(
{
title: Alfresco.util.message("message.failure", this.name),
text: "search failed"
});
},
scope: this
}
});
}
I'm trying to redirect a new page with this syntax
try {
usuarios usu = new usuarios();
usu.setNombreusuario(request.getParameter("parCodigo"));
System.out.println(usu.getUsuario());
usu.setContrasena(request.getParameter("parContrasenha"));
System.out.println(usu.getContrasena());
usu = usuariosDAO.login(usu);
System.out.println("es valido? " + usu.isValid());
if (usu.isValid()) {
HttpSession session = request.getSession(true);
session.setAttribute("usuario", usu.getUsuario());
response.sendRedirect("/KolaEscocesaCRM/menumobile.jsp");
return;
} else {
response.sendRedirect("/KolaEscocesaCRM/loginmobile.jsp");
}
} catch (Exception ex) {
ex.printStackTrace();
}
My problem is that when I submit I get this:
http://localhost:8084/KolaEscocesaCRM/srvMenu2?parCodigo=admin&parContrasenha=kola
I don't know what to do please any help would be fine
If you get a dear 404
Most of the time, because the entry application is mapped into something like /myapp instead of /(root)
The server says to the browser go to /KolaEscocesaCRM/loginmobile.jsp where it should be /.myapp/KolaEscocesaCRM/loginmobile.jsp
The simplest way is changing the context-path to root (/ or empty string)
wish to know if the credential file generated by Java's kinit is the same as that created in "cache" or memory when the user logged in.
For example, using kinit the credential file is by default krb5_[username].
I also have a piece of code that gets the Kerberos ticket from the currently logged in user:
public static byte[] getTicket() {
// defined the realm, kdc etc here
.....
try {
LoginContext lc = new LoginContext("SomeLoginContext");
lc.login();
Subject signedOnUserSubject = lc.getSubject();
Set<Object> privatePrincipalsSet = signedOnUserSubject.getPrivateCredentials();
if (privatePrincipalsSet != null && privatePrincipalsSet.size() > 0) {
for (Object privatePrincipal : privatePrincipalsSet) {
//make sure it is the kerberos ticket
if (privatePrincipal instanceof KerberosTicket) {
KerberosTicket ticket = (KerberosTicket)privatePrincipal;
return ticket.getEncoded(); <------- is this correct?
}
}
}
}
catch (LoginException e) {
e.printStackTrace();
} finally {
}
return null;
}
May I know if the internal "format" of the credentials are the same.?
thanks
How can i implement theming support in Play Framework 2?
I want to create directory structure like:
views/default <- default template directory
views/site1 <- template for site 1
views/site2 <- template for site 2
If template doesn`t exist (ie. views/site1/home) it should render template from default directory.
I have tried cls = Class.forName("views.html.home); But I get class not found exception.
SOLUTION:
Maybe someone will find this useful:
protected static String renderTemplate(final String template, final String action,final ViewData templateParams) {
Class<?> cls = null;
String ret = "Template not found";
try {
cls = Class.forName(template);
} catch (ClassNotFoundException e) {
ret = e.toString();
}
if (cls == null) {
try {
cls = Class.forName("views.html.default."+action);
} catch (ClassNotFoundException e) {
ret = e.toString();
}
}
if (cls != null) {
Method htmlRender;
try {
htmlRender = cls.getMethod("render", ViewData.class);
ret = htmlRender.invoke("",templateParams).toString();
} catch (NoSuchMethodException e) {
ret = "Method not found"+e.toString();
} catch (IllegalAccessException e) {
ret = "illegal access exception";
} catch (InvocationTargetException e) {
ret = "InvocationTargetException";
}
}
return ret;
}
ViewData vd=new ViewData();
renderTemplate("views.html.custom."+viewname, actionname, vd)
You have to implement it yourself, as a reference, check the Play Authenticate usage sample, it allows to send ie. validation emails basing on Play's template and depending on the client's language, so for an instance, if your main language is Polish it will render the verify_email_pl.scala.html otherwise if your browser uses language not supported by PA, it will silently fallback to: verify_email_en.scala.html.
Check the usage and declaration of the method.
For your case it will be good solution, of course just criteria of the choice will be different.
This process is called "Branding". What you have to do is following.
Create a table in db by name "BRANDING" and add theme names in it against each instance of website.
Now you will make folders hierarchy as you mentioned and in jsp pages where load css files you will do that like this <link rel="stylesheet" type="text/css" href="/views/${themeName}.css">
where themeName would be a server side variable that you will program in your controller to be fetched from db or first time you will fetch it and then cache it.