Keycloak Custom Form Provider: Form has wrong action url - keycloak

I have a custom form added to RestCredentialFlow,
I can configure the new flow execution and I see the new Form. Looks all good.
The only problem is that the form action url points to registration and not reset-credentials,
<form id="kc-reset-password-form" class="sb-form-box" action="http://localhost:8080/auth/realms/soka/login-actions/registration?session_code=**&execution=478d7632-2821-42f1-9c34-aa013fea33eb&client_id=account&" method="post">
...
</form>
I can change it in the browser an everything works fine.
Can anybody help, why it points to registration and how to change it.
I don't see any interaction with the registration flow.
Thanks
Here the form is rendered, this already return the form with the wrong actionUrl.
public class ResetCredentialPage implements FormAuthenticator, FormAuthenticatorFactory {
private static final Logger log = Logger.getLogger(ResetCredentialPage.class);
public static final String PROVIDER_ID = "reset-credential-page-form";
#Override
public Response render(FormContext context, LoginFormsProvider form) {
return form.createPasswordReset();
}
...
}

Not sure if you've found the answer yet, I'm in the exact same position. Based on my reading of the documentation I strongly suspect the FormAction/FormAuthenticator classes are designed for the registration page only. So the action uri is not meant to be anything other than the registration uri - basically I suspect it's hard coded somewhere more or less.
If I'm wrong let me know.

Related

AEM - URL does not change with RequestDispatcher forward

When i do a Forward using RequestDispatcher.. the result page loads but the URL does not change.
The URL where we start and Submit data to the PostServlet: http://localhost:4502/content/en/postformtest.html
Final result URL should be: http://localhost:4502/content/en/postformtestresult.html
But is: http://localhost:4502/services/processFormData
What am i missing? Appreciate any thoughts.
Code snippets..
The HTML Form:
<form name="userRegistrationForm" method="post" action="/services/processFormData">
<input type="submit" title="Submit" class="btn submit btn-success" value="Submit" tabindex="25" name="bttnAction">
</form>
The POST Servlet
#SlingServlet(
label = "Common POST Servlet",
metatype = true,
methods = { "POST" },
name="com.commons.service.servlets.TPostServlet",
paths = { "/services/processFormData" }
)
public class TPostServlet extends SlingAllMethodsServlet{
#Override
protected void doPost(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException {
final SlingHttpServletRequest syntheticRequest = new SyntheticSlingHttpServletGetRequest(request);
final RequestDispatcherOptions options = new RequestDispatcherOptions();
options.setReplaceSelectors("");
options.setForceResourceType("cq/Page");
request.getRequestDispatcher("/content/en/postformtestresult.html", options).forward(syntheticRequest, response);
}
}
The Wrapper Servlet:
public class SyntheticSlingHttpServletGetRequest extends
SlingHttpServletRequestWrapper {
private static final String METHOD_GET = "GET";
public SyntheticSlingHttpServletGetRequest(final SlingHttpServletRequest request) {
super(request);
}
#Override
public String getMethod() {
return METHOD_GET;
}
}
As the javadocs for RequestDispatcher indicate, the RequestDispatcher and by association the forward method act as wrappers around the resource essentially allowing the delegation of further processing to the resource. This is done behind the scenes so to speak and as such the requested URL will not change - it is not a redirect.
Based on the content of your question I presume what you are trying to accomplish is a traditional form POST to a page. This is actually a rather cumbersome pattern to achieve in AEM and you would most likely be better served by submitting the form asynchronously and then redirecting based on the response.
If all you need is a simple redirect after form processing this can be achieved by calling the sendRedirect method of the response.
If, however, you do need to POST to a page which is then going to handle both the form processing and the page rendering, you could employ a method similar to the OOB form components. The OOB com.day.cq.wcm.foundation.forms.impl.FormsHandlingServlet is implemented as both a Servlet and a request level Filter. As a filter it catches to POST request to the page prior to processing, forwards it using the RequestDispatcher to its Servlet nature, and the Servlet in turn is able to process the request and then forward it, again using the RequestDispatcher, to the page after wrapping the request as a GET request similar to what you are doing above. A bit circuitous but, as noted, this is a cumbersome pattern to realize.
Have you looked at ACS Commons Forms? They do support PRG as a standard form handling process. Check it out at http://adobe-consulting-services.github.io/acs-aem-commons/features/forms.html
You may end up using the feature as is or will get some hint for implementation.
The git link for the same is https://github.com/Adobe-Consulting-Services/acs-aem-commons

Silverstripe Login params

Im trying to style my login page. My login url is website/Security/login. Im trying to locate the 'login' piece of the url. What have i done wrong below?
public function DisplayPageType() {
$param = $this->request->param('Action');
if ($param === 'login')
{
return 'Login';
}
Thanks
I think that won't work since the controller during render is the Page_Controller and not the Security controller. So the $Action param is not equal to login. It could be index, I'm not sure.
If you just want to check if you're in the login page, you can add this to your Page_Controller:
public function getIsLoginPage()
{
return $_REQUEST['url'] == '/Security/login';
}
Then in your template:
<body class="<%if $IsLoginPage %>login-page<% end_if %>">
A bit dirty but it's the quickest way I know.
Another way is to leverage SilverStripe's legacy support. You can add a css file called tabs.css at mysite/css/tabs.css. If this file exists, SilverStripe will include this in the page.
You can also create templates that SilverStripe will automatically use if they exist:
themes/<theme_name>/Security.ss - If you want your login page to use an entirely different layout.
themes/<theme_name>/Layout/Security_login.ss - If you want to change just the content part (the $Layout section)
I hope this helps.
#gpbnz is right, the $Action param is not equal to login, it actually returns null as accessing $this->request from the Page_Controller when accessing the Security/login returns a NullHTTPRequest.
To get the action, you will want to get the current controller using Controller::curr(). It is then as simple as calling getAction on this controller.
To confirm that the action isn't from a random controller that happens to have an action called login, you can check the instanceof the controller like so: Controller::curr() instanceof Security
This check will still allow it to work for any controller that extends Security though which may/may not happen depending on the project.
I would stick away from actually reading the URL for the information manually though as that can create issues with maintainability in the future.
To bring this to a nice little function:
public function isLoginPage()
{
$controller = Controller::curr();
return $controller instanceof Security && $controller->getAction() == 'login';
}
Otherwise #gpbnz had a good suggestion of using the template system to your advantage for overriding not only the styles but the HTML around it.

How to produce rendered output from a Sling POST in AEM?

It seems like Sling expects every form POST to modify the JCR. So the expected/standard behavior would be a POST-redirect-GET, which is fine for most things. However, I need to be able to POST to AEM and then use the data in that POST to create a rendered result. Our use of AEM is stateless and so I don't want to carry the POST'd data in Session in order to utilize it in a subsequent GET.
Some have recommended putting the POST'd data in Browser sessionStorage, but that doesn't have broad enough support to be sufficient.
As far as I can tell there is no way for Sling in AEM to take a POST and produce a rendered result.
Here is a screenshot of what a POST produces in the page/resourceType component and in any Sling included jsp's that happen to be involved in the rendering.
I have tried things like using the "nop" operation.
<input type="hidden" name=":operation" value="nop" />
But either way all servlets think a POST is happening and don't render properly.
There is the option of creating a custom servlet, to handle the POST, but then how do you render the templated output and change the request so that all the components think they are serving a GET?
UPDATED:
Here is a screenshot of the "nop" POST.jsp result.
What you can do is create a POST.jsp file in the appropiate resourceType.
If your POST request go to /content/yourapp/something, which has a resourceType: your/app/example. Then you can create a file /apps/your/app/example/POST.jsp with whatever render you wish. You can even include your default rendering script in the POST.jsp file if you need it to be rendered the same as the GET requests.
The other option is to use a servlet registered for POST requests and internally use the SlingRequestProcessor service. That service allow you to programmatically process a request through Sling. You can use a SlingRequestWrapper to wrap your request and override getMethod() to return "GET". That should process the request as if it was a GET request.
This sounds like a somewhat funky use case, IIUC you are using a large request parameter P to drive the rendering?
Using a custom POST servlet should work, if you use something like
slingRequest.getRequestDispatcher(resource).forward(request, response) where request is a wrapper around the actual request, where request.getMethod() returns GET. You can then store your P data in request attributes.
The SlingHttpServletRequestWrapper class can be used to create such wrappers.
Creating a custom servlet to handle a post could be an idea. After successfull write you could redirect to the modified resource - simple 302.
The other solution that comes to my mind is a custom Filter that would do the same. However, since AEM expects to get 200 instead of 302, it would be good to tell by atrribute or parameter that this POST needs to be redirected. Otherwise some of the AEM UI functionalities could brake. This is a quick example of an idea. You would probably need to write something more sophisticated.
#Component(immediate = true)
#Service
#Properties({
#Property(name = Constants.SERVICE_DESCRIPTION, value = "Desc"),
#Property(name = Constants.SERVICE_VENDOR, value = "Company name"),
#Property(name = Constants.SERVICE_RANKING, intValue = RedirectFilter.RANKING),
#Property(name = "filter.scope", value = "request") })
public class RedirectFilter implements Filter {
public static final int RANKING = -1000; // low ranking
#Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
if (request.getParameter("redirect").equals("true")) {
((SlingHttpServletResponse) response).sendRedirect(((SlingHttpServletRequest)request).getRequestURI());
}
}
}

GWT detect browser refresh in CloseHandler

I have a GWT application and I want to run some code when the user leaves the application to force a logout and remove any data etc.
To do this I am using a CloseHandler and registering it using Window.addCloseHandler.
I have noticed that when the refresh button is clicked the onClose method is run but I have been unable to differentiate this event from a close where the user has closed the browser. If it is a refresh I do not want to do the logout etc, I only want to do this when the user closes the browser/tab or navigates away from the site.
Does anybody know how I can do this?
There is no way to differentiate the 'close' from 'refresh'. But, you can set a cookie that holds the last CloseHandler call time and check, when loading the module, if this time is old enough to clean the information before showing the page.
You can do that with the folowing utility class (BrowserCloseDetector). Here is an example using it on the onModuleLoad.
The test lines:
#Override
public void onModuleLoad() {
if (BrowserCloseDetector.get().wasClosed()) {
GWT.log("Browser was closed.");
}
else {
GWT.log("Refreshing or returning from another page.");
}
}
The utility class:
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
public class BrowserCloseDetector {
private static final String COOKIE = "detector";
private static BrowserCloseDetector instance;
private BrowserCloseDetector() {
Window.addWindowClosingHandler(new Window.ClosingHandler() {
public void onWindowClosing(Window.ClosingEvent closingEvent) {
Cookies.setCookie(COOKIE, "");
}
});
}
public static BrowserCloseDetector get() {
return (instance == null) ? instance = new BrowserCloseDetector() : instance;
}
public boolean wasClosed() {
return Cookies.getCookie(COOKIE) == null;
}
}
Have you tried
<BODY onUnload = "scriptname">
in your gwt hosting/launching html file?
I am thinking that if you defined a map "hash" (i.e. a javascript pseudo hash) in the hosting file and then accessed the "hash" in GWT through Dictionary class, you could update values in that hash as the user progresses through the gwt app. Which means, your programming style would require you to log milestones on the user's progress onto this map.
When the user closes the browser page, the onunload script of the launching html page would be triggered. That script would access the map to figure out what needs to be updated to the server, or what other url to launch.
I am intereted too if someone got a solution (GWT/java side only).
Maybe we can do it with HistoryListerner ?
1-set a flag for your current viewing page.
2-when ClosingHandler event, launch a "timeout" on server-side (for example 10s)
3-if during this time your got a massage from HistoryListerner with the same last flag so it was just a refresh.
of disconnect if timer is over...
Is not a good solution but I think it is easy to do... If someone have a better one...

Persisting querystring parameter throughout site in ASP.Net MVC 2

http:www.site1.com/?sid=555
I want to be able to have the sid parameter and value persist whether a form is posted or a link is clicked.
If the user navigates to a view that implements paging, then the other parameters in the querystring should be added after the sid.
http:www.site1.com/?sid=555&page=3
How can I accomplish this in Asp.Net Mvc 2?
[Edit]
The url I mentioned on top would be the entry point of the application, so the sid will be included in the link.
Within the application links like:
<%= Html.ActionLink("Detail", "Detail", new { controller = "User",
id = item.UserId })%>
should go to:
http:www.site1.com/user/detail/3?sid=555
This question is different than what Dave mentions, as the querystring parameter is persisting throughout the site.
Firstly, I'd say if the value needs to be persisted throughout the session then you should store it in Session and check that its still valid on each action call. This can be done through a custom action attribute you add to the controller / actions required. If the value is required then when the value is checked you can re-drect to a login page or similar if not present or its expired.
Anyway, that said I thought I would have a crack at getting it working. My first thought would be to create a custom action filter attribute which took the value of the querstring and stored it in session in OnActionExecuting and then OnResultExecuted would add the key back to the querystring. But as QueryString in Request is a read-only collection you can't do it directly.
So, whats now available to you?
Option #1 - Add it to all calls to Html.ActionLink() manually
or ...
Option #2 - Override a version of ActionLink which automatically adds the value for you. This can be achived like so. I wouldn't recommend doing this though.
Start off with the custom attribute.
public class PersistQueryStringAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var sid = filterContext.RequestContext.HttpContext.Request.QueryString["sid"];
if (!string.IsNullOrEmpty(sid))
{
filterContext.RequestContext.HttpContext.Session["sid"] = sid;
}
base.OnActionExecuting(filterContext);
}
}
All this does is check the request querystring for the required key and if its available add it into the session.
Then you override ActionLink extention method to one of your own which adds the value in.
public static class HtmlHelperExtensions
{
public static MvcHtmlString ActionLink<TModel>(this HtmlHelper<TModel> helper, string text, string action, string controller, object routeValues)
{
var routeValueDictionary = new RouteValueDictionary(routeValues);
if (helper.ViewContext.RequestContext.HttpContext.Session["sid"] != null)
{
routeValueDictionary.Add("sid", helper.ViewContext.RequestContext.HttpContext.Session["sid"]);
}
return helper.ActionLink(text, action, controller, routeValueDictionary, null);
}
}
On each of the action which is going to be called apply the attribute (or apply it to the controller), eg:
[PersistQueryString]
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
Note
As the query value gets put into session it will be applied for the life of the session. If you want to check that the value is there and the same each request you will need to do some checking in the attribute overridden method.
Finally
I've purely done this as a "can it be done" exercise. I would highly recommend against it.
Possible Duplicate:
How do you persist querystring values in asp.net mvc?
I agree with the accepted answer to the question linked above. Querystring parameters are not designed for data persistence. If a setting (i.e. sid=555) is intended to persist through a session, use Session state or your Model to save that data for use across requests.