JSF 2 redirect to HTTPS - jsf

I've seen these posts: Issues with JSF navigation rules using redirect on HTTPS, and JSF 2 and Post/Redirect/Get?, but haven't been able to get what I want to do to work. I'm trying to redirect to an https page in my app using ConfigurableNavigationHandler. Here's my handleNavigation:
public void handleNavigation(FacesContext context, String from, String outcome) {
System.out.println("outcome: " + outcome);
if (outcome.startsWith("manageEmail")) {
outcome = "https://localhost:8081/appmonitor/faces/manageEmail.xhtml";
}
System.out.println("outcome: " + outcome);
parent.handleNavigation(context, from, newOutcome);
}
When I click on the link which redirects to "manageEmail", I see that outcome starts as "manageEmail", and changes to my https address, but it doesn't actually redirect there. I suspect it's trying to navigate to http://localhost:8080/appmonitor/faces/https://localhost:8081/appmonitor/faces/manageEmail.xhtml. If this is what is in fact happening, is there any way to override this behavior?

Have you tried accessing the external response and give back a redirect command?
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.sendRedirect(outcome);

Related

How do I limit a user from accesing sertain pages in JSF? [duplicate]

This question already has answers here:
How implement a login filter in JSF?
(2 answers)
Closed 2 years ago.
Like the title says, how do I limit users from accessing certain pages in JSF? I have two different kinds of pages that I want to limit access to. The first one is pages that need parameters to load, would it be possible to redirect if a user tries to redirect access that page without any parameters? The second one is pages that only certain users should have access to. In my app you have the ability to create and edit competitions, however, I only want the host of the event to be able to access the edit page for that event - which at the moment anyone can access if they know the right parameters. Is there something in JSF that lets me do this?
General page access
Have a look at #WebFilter and its doFilter method. Inside you can check if your user is logged in retrieving your session scoped bean from the HttpSession.
#WebFilter(filterName = "UserAuthenticationFilter", urlPatterns =
{
"/sites/user/account.xhtml"
} , dispatcherTypes =
{
DispatcherType.FORWARD, DispatcherType.REQUEST, DispatcherType.ERROR
})
public class UserAuthenticationFilter extends HttpFilter
{
#Override
public void doProductionFilter(final HttpServletRequest request, final HttpServletResponse response, final HttpSession session, final FilterChain chain) throws IOException, ServletException
{
final UserBean userBean = session.getAttribute("userBean");
// check if logged in and redirect to login page if not
if (userBean.isLoggedIn()
chain.doFilter(request, response);
else
response.sendRedirect(request.getContextPath() + "/login.xhtml");
}
}
Specific page access
Check your request param either in your #PostConstruct or better in your viewAction or initPreRenderView methods since in the later two you have access to your injected view parameters.
If user does not has sufficient rights to access the data redirect or/and show faces message or do something else.

Proper way to redirect to a different page in Hybris

what is the proper way to redirect to a different page in Hybris?I have been the following approach quite a lot:
link
But some people emphasized that it is better to redirect using a separate method and using redirect:
What is the correct way?
Let me first tell you basic difference between request Redirect Vs Forward.
Redirect: Server sends a header (in response) back to the browser/client, which contain redirect URL, then browser initiates a new request to redirect URL.
When can we use Redirect?
Usually, when data is posted to the server, we should redirect to get method(URL) to prevent data resubmission on browser refreshed(F5).
return "redirect:/redirectToGeturl";
Forward: Within the server, control can be forwarded to target resource(URL). Which is done by container internally so browser/client is not aware of it.
When can we use forward?
Sometimes, we want to show different page/resource in response without changing original URL, then we forward request to other controller internally.
return "forward:/404";
What is the proper way to redirect to a different page in Hybris?
public static final String REDIRECT_PREFIX = "redirect:";
public static final String FORWARD_PREFIX = "forward:";
This class level constants are defined in AbstractController. You can use that by extending your controller to AbstractPageController or AbstractController.
return REDIRECT_PREFIX + "/redirecturl";
return FORWARD_PREFIX + "/404";
< a href="< c:url value="/path" />">link< /a >
This is the correct way to declare a link on client/browser side, which sends GET request to /path once the user clicks it.
Find detail post here

WebClient with credentials still not downloading file

I am trying to download files from a website with username/password. You need to pay for a registered account in order to download files - which we have done. I am attempting to pass in the username/password and download a file as follows:
if (docUrl != null)
{
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
this.WebClientInstance.Credentials = new NetworkCredential(username, password);
fileData = this.WebClientInstance.DownloadData(docUrl);
this.WebClientInstance.Dispose();
isDataDownloaded = true;
}
WebClientInstance is a System.Net.WebClient. I debugged and verified that it is hitting the line to set credentials. Instead of downloading the PDF, I end up with an HTML page that prompts me to log in to get access to the file. I have verified that the username/password is correct. I use the same credentials to scrape the website with WatiN.
Is there something else that I'm supposed to be doing here?
UPDATE
Okay, I've done some sniffing around and found some useful info on this issue. I still haven't gotten it to work, but I think I'm closer. First, you need to create a cookie aware WebClient that extends the WebClient class, as follows:
public class CookiesAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; private set; }
public CookiesAwareWebClient()
{
this.CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var webRequest = base.GetWebRequest(address);
if (webRequest is HttpWebRequest)
(webRequest as HttpWebRequest).CookieContainer = this.CookieContainer;
return webRequest;
}
}
Next is to use the WebClient.UploadValues() method to upload the login info to the target website. The full process of authenticating and downloading the target resource is as follows:
using (var webClient = new CookiesAwareWebClient())
{
var postData = new NameValueCollection()
{
{ "userId", username },
{ "password", password }
};
webClient.UploadValues(docUrl, postData);
fileData = webClient.DownloadData(docUrl);
}
I was wrong about the site using forms auth. It is a JSP website and uses a JSESSIONID. I have verified that I am getting a cookie back with what appears to be a valid 32-byte JSESSIONID value.
However, when I call WebClient.DownloadData() it is still only returning the redirected login page. I've tried to fix this by setting the AllowAutoRedirect property on the HttpWebRequest to false, but then it returns 0 bytes.
Is there something else that I need to do so it won't redirect and will take me to the resource once I have authenticated?
(Answered in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Solved. So the problem was between my ears. I was passing in the URL for the secure resource to the .UploadValues() method, knowing that it would redirect to the login page. However, I really needed to pass in the URL from the login form (where it goes upon submitting) - not the login page itself. Once I did that, it worked correctly. I think I'm going to go find a career in food service now.
LINKS
There were already a few questions posted on SO that addressed this issue. I just didn't know what I was looking for at first so I didn't see those... Anywhere here are a couple good resources that I came across when working on this issue:
how to maintaine cookies in between two Url's in asp.net
Trying to get authentication cookie(s) using HttpWebRequest

How to signout programmatically from Liferay custom portlet

I am creating a custom portlet.
And I need to log-out the User from the portal after he performs some operation in my custom portlet. I am extending liferay's MVCPortlet.
In one of MyPortlet's action methods I need to write the code to logout the user and then redirect it to the home page.
Update:
I tried the following which I think logs out the user but does not redirect to the home page after logging out:
actionResponse.sendRedirect(PortalUtil.getPortalURL(actionRequest) + "/c/portal/logout");
Thanks All
Well this may be a very late reply, but it may help somebody
Firstly, you have to validate the session and the re-direct to the logout URL. Otherwise, the session remains and the user is moved to the landing page, even though we redirect to the logout url. So, this is what one should do
HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
request.getSession().invalidate();
actionResponse.sendRedirect(themeDisplay.getURLSignOut());
Hope this helps.
I also did not find a way to send a specific redirect by using liferay's default logout (/c/portal/logout). So I logged out the user programmatically with the util class AuthenticatedSessionManagerUtil and
afterwards sending a specific redirect location within the response object, e.g. response.sendRedirect(yourLocation)
Note:
With Liferay 7.2 I used AuthenticatedSessionManagerUtil.signOutSimultaneousLogins(userId) instead of AuthenticatedSessionManagerUtil.logout(userId) which did not work for me.
hth
You can redirect to c/portal/logout
more precisely :
actionResponse.sendRedirect("/c/portal/logout/");
Just leaving this here after facing this problem (LR7):
try {
AuthenticatedSessionManagerUtil.logout(request, response);
request.setAttribute(WebKeys.LOGOUT, true);
}
All you have to do is
perform operation: at the end of operation use this:
HttpSession session = PortalUtil.getHttpServletRequest(request).getSession();
session.invalidate();
try {
System.out.println(" redirecting to the required page");
response.sendRedirect(themeDisplay.getPortalURL() + "/page-on-which-to-be-redirected");
} catch (IOException e1) {
e1.printStackTrace();
}

JSF PhaseListener viewId always one behind

Im trying to prevent users to access special pages with a phaselistener. for that reason im trying to figure out on which page they try to access.
but my problem is, i only get the page they where before. not the actual page.
public void afterPhase(PhaseEvent event)
{
FacesContext fc = event.getFacesContext();
System.out.println("test1" + fc.getViewRoot().getViewId());
}
and same here
public void afterPhase(PhaseEvent event)
{
FacesContext fc = event.getFacesContext();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
String uri = request.getRequestURI();
System.out.println("uri: " + uri);
}
why is that, and how do i get the pagename the user is trying to access? Not that one that they required one step before, or better the page they are coming from.
It is one step behind because that is the way sequence of HTTP POST request behaves. When you are navigating in JSF application via command buttons each request goes as a post request.
Since you are protecting some resources make sure they are accessed via HTTP GET than you will get exact view id, this can be achieved as
User directly hits the url from address bar of browser.
After a post of jsf app redirect it to the resource instead of simple JSF navigation. POST-REDIRECT-GET pattern falls into this have a look here.
If you are showing some messages after each POST, you might need Flash map for that, which is new feature in JSF2, if you are on JSF1.x hard luck, you can implement flash if you want to.
To conclude catch the view ids on HTTP GET request.
Hope this helps...

Resources