Localized URLs in Spring - java

There is quite a lot of documentation and guides that describe how to set up message localization in Spring framework. All of these that I found consider only changing messages (texts) on the webpages, but not page URLs. I would like to have completely different URLs for each locale. For example, http://example.org/en/welcome would be used in the English version, but http://example.org/de/willkommen would be used in the German version.
I assume that I will not be able to use class annotations to route the pages. I prefer storing the path–controller mapping in a file and loading it at runtime.
Could you tell me at least how to not hav

Websites implement localization in one of two ways. The first approach involves automatically detecting the user locale by examining HTTP request headers (Accept-Language header in particular) and localizing site content for the user locale (if supported).
Spring MVC uses this approach by default. It uses the HttpServletRequest.getLocale method to determine the client locale and then loads localized messages from message sources. Note that the getLocale method returns a single Locale object whereas the Accept-Language header passed by the client could contain multiple languages (for example, Accept-Language: en-US, en-GB, en). In such cases, the getLocale method returns the Locale for the first matching language (en-US in the example above).
Therefore, if you wish your Spring MVC application to automatically detect the client locale and serve localized content, simply declare a ResourceBundleMessageSource bean in the application context. No other configuration is required.
The second approach used by websites is to always display content in a default language first and then allowing the user to change the locale (using a dropdown or links in the site header or footer). In such cases, the users may choose locales that are not consistent with the Accept-Language header sent by their browser. For example, the Accept-Language header may contain fr-CH while the user may select de-DE as the locale.
It is in such scenarios that LocaleChangeInterceptor and SessionLocaleResolver are required to use the user selection instead of the request headers. These components can intercept the user choice and save it temporarily for the duration of the session to localize the site content correctly.
and if you want more info refer this:
Spring Localization without passing language in query string

Related

Spring MVC Validating all parameters in POST/PUT methods in controllers

I have plenty of controllers and I want to validate all of parameters submitted in forms against XSS attacks. Instead securing each controller separately I would like to have one component that works as interceptor for all submitted forms and checks the parameters submitted.
I wrote a Filter that uses antisamy for correcting values of parameters but it works too good. I mean it escapes everything, even rich content that should not be escaped.
Sanitizing user inputs with Spring MVC framework
https://jeevanpatil.wordpress.com/2011/07/22/prevention_of_xss/
Therefre I need some solution to escape concrete parameters in controlers, do u know any solution ? I plan to create annotation next to parameters in every method in controller, for example #XSSEscaped, then only those parameters would be escaped.
HTML encoding at the time of input can corrupt the data. It may still not be secure because data inserted into an attribute, stylesheet, or script could still execute code even with HTML encoding. It may not cover all the data on the page as some values might not have come through the controller, or could have been modified since then.
There are many ways to bypass input filters (see XSS Filter evasion cheatsheet). The RequestWrapper in the linked answer for example filters out eval(), but pass in e<script></script>val() instead and you get eval() as output again. Fix that, then they'll be something else.
HTML encoding is the the responsibility of the view layer. This is where you can make sure all the data used on the page is encoded appropriately for the context where it's used. XSS is prevented by following the rules at the Cross Site Scripting Prevention Cheatsheet. Templating systems like Thymeleaf will do HTML encoding by default of its values.

What is difference b/w org.owasp.esapi.Encoder.encodeForHTML and org.owasp.esapi.Encoder.encodeForJavaScript methods

I Know, we can use encodeForHTML for HTMl and encodeForJavascript for javaScript.
There is a Cross-Site Scripting: "Reflected fortify scan problem" in my code
String errorDesc = HttpServletRequest.getParameter("error_description");
I have to validate this using Encoder but I am confused to use which one should i use between them. As we do not know the return type of HttpServletRequest.getParameter.
1. org.owasp.esapi.Encoder.encodeForHTML
2. org.owasp.esapi.Encoder.encodeForJavaScript
What we have here dear asker is a rather common misunderstanding about the differences between output encoding--which is what you're working with when you look at the Encoder calls, and input validation, which is a completely separate operation that has little to do with the Encoder class.
The Encoder methods you're dealing with here are to be used only when you're presenting data to a user, and only for the correct context. For example, if the application is a "Single Page Application" (SPA) then very likely you're just going to want to ensure that the output is encoded for JavaScript as the client-facing framework will almost certainly be JavaScript.
If you were using an older style of application, then you would encode for HTML anytime you were going to place data between <some_tag> data </some_tag>.
XSS requires you to understand one thing for every variable in your application: Its data flow, from when the value is generated (Server, User, DB, etc.) and understand all of the transformations it might undergo as it traverses to the user and back to the system. If the value starts in the browser, it will enter into some kind of Controller on the backend, and before you process the value you'll whitelist validate it--ESAPI has a validator class--and then if it passes validation you'll ensure that the database will only treat it as data (PreparedStatement, or through use of an ORM framework's utilities.) Best practice is to
Canonicalize the data
Validate against the canonicalized value
If valid, discard the canonicalized value and store the original data
If used properly, the Validator class is defaulted to help you do this.
The methods you're asking about in this question are for instances where user input is being sent back to the browser, either from the database or from a previous request in your session that hasn't yet been persisted.
The main difference is how the output encoding is done. Encoder.encodeForHTML() does HTML entity encoding via the org.owasp.esapi.codecs.HTMLEntityCodec class, whereas Encoder.encodeForJavaScript() uses JavaScript's backslash encoding via org.owasp.esapi.codecs.JavaScriptCodec.
Which one you choose depends on the context of how your "error_description" parameter will be rendered in your application. If it is rendered between HTML tags, use encodeForHTML(), if you are rendering it in purely a JavaScript context, use encodeForJavaScript(). Refer to https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html for a more thorough explanation of all this.

how to know website supported languages?

I am facing a problem while doing localization testing using selenium web driver and java,how to know the languages supported by a web page?
what i want to achieve is following
1. enter the URL for localization testing.
2. i want to show web site supported languages to the User Automatically.
3. Then depend upon user choosen language L10N/I18N process goes on
There's no 100% guaranteed way to do this, unfortunately, but the rel="alternate" hreflang="foo" standard is probably your best bet to automated detection. If you want to be very fancy and thorough, though, you could attempt to fetch the page from different locations; you could also fetch the page using different values of the Accept-Language header; you could also try to modify the URL using common patterns that are known to be widely used for internationalizing domains (e.g. using "en.", "fr.", etc. prefixes in place of "www.", adding "/en/", "/fr/", etc. in the path, replacing the ".com" with ".co.uk", ".fr", ".de", etc.) in an attempt to find hidden international variants.
Since this is for automated testing, it may be easier if the user simply supplies the set of languages you want to test. Then, if the language is in hreflang, you use that URL; if it's not in hreflang, you use the original URL and simply specify that language in your Accept-Language header.

why does the page name is not added in the url after launching jsf application [duplicate]

I am currently learning JSF and was rather amazed and puzzled when I realized that whenever we use <h:form>, the standard behavior of JSF is to always show me the URL of the previous page in the browser, as opposed to the URL of the current page.
I understand that this has to do with the way JSF always posts a form to the same page and then just renders whatever page the controller gives it back to the browser which doesn't know the page location has changed.
It seems like JSF has been around for long enough that there must be a clean, solid way to deal with this. If so, would you mind sharing?
I have found various workarounds, but sadly nothing that seems like a real solid solution.
Simply accept that the URL is misleading.
Append "?faces-redirect=true" to the return value of every bean's action and then
figure out how to replace #RequestScoped with something else (Flash Scopes, CDI conversation, #SessionScoped, ...).
accept to have two HTTP round trips for every user action.
Use some method (e.g. 3rd party library or custom code) to hide the page name in the URL, always using the same generic URL for every page.
If "?faces-redirect=true" is as good as it gets, is there a way do configure an entire application to treat all requests this way?
Indeed, JSF as being a form based application targeted MVC framework submits the POST form to the very same URL as where the page with the <h:form> is been requested form. You can confirm it by looking at the <form action> URL of the generated HTML output. This is in web development terms characterized as postback. A navigation on a postback does by default not cause a new request to the new URL, but instead loads the target page as content of the response. This is indeed confusing when you merely want page-to-page navigation.
Generally, the right approach as to navigation/redirection depends on the business requirements and the idempotence (read: "bookmarkability") of the request (note: for concrete code examples, see the "See also" links below).
If the request is idempotent, just use a GET form/link instead of POST form (i.e. use <a>, <form>, <h:link> or <h:button> instead of <h:form> and <h:commandXxx>).
For example, page-to-page navigation, Google-like search form, etc.
If the request is non-idempotent, just show results conditionally in the same view (i.e. return null or void from action method and make use of e.g. <h:message(s)> and/or rendered).
For example, in-page data entry/edit, multi-step wizard, modal dialog, confirmation form, etc.
If the request is non-idempotent, but the target page is idempotent, just send a redirect after POST (i.e. return outcome with ?faces-redirect=true from action method, or manually invoke ExternalContext#redirect(), or put <redirect/> in legacy XML navigation case).
For example, showing list of all data after successful editing, redirect after login, etc.
Note that pure page-to-page navigation is usually idempotent and this is where many JSF starters fail by abusing command links/buttons for that and then complain afterwards that URLs don't change. Also note that navigation cases are very rarely used in real world applications which are developed with respect to SEO/UX and this is where many JSF tutorials fail by letting the readers believe otherwise.
Also note that using POST is absolutely not "more secure" than GET because the request parameters aren't immediately visible in URL. They are still visible in HTTP request body and still manipulatable. So there's absolutely no reason to prefer POST for idempotent requests for the sake of "security". The real security is in using HTTPS instead of HTTP and checking in business service methods if currently logged-in user is allowed to query entity X, or to manipulate entity X, etc. A decent security framework offers annotations for this.
See also:
What is the difference between redirect and navigation/forward and when to use what?
JSF implicit vs. explicit navigation
What URL to use to link / navigate to other JSF pages
Bookmarkability via View Parameters feature
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
When should I use h:outputLink instead of h:commandLink?
Creating master-detail pages for entities, how to link them and which bean scope to choose
Retaining GET request query string parameters on JSF form submit
Pass an object between #ViewScoped beans without using GET params

Bean Validation: How to localize messages programmatically?

In my current rest-service scenario I need to be able to provide localized error messages to individual clients.
Think of a method like void validate(Locale locale) which is called on the parameter object when receiving some request.
The locale information can be squeezed out of the http headers.
How can I instruct/configure a validator to use a certain language when violation messages are getting interpolated?
As far as I know a validator chooses the used Locale by calling Locale.getDefault().
So far I couldn't find anything other than this article which does not exactly fit to my needs (a story too long to tell).
Thanks in advance!
According to the spec you have two possibilities:
Use interpolate(String, Context, Locale) or
implement a custom message interpolator.
A custom message interpolator may be provided (e.g., to interpolate contextual data, or to adjust the default Locale used).
See also:
Example 5.10. Use MessageInterpolator to use a specific Locale value
Example 5.11. Contextual container possible MessageInterpolator implementation

Categories