Create a servlet-filter websphere liberty profile? - servlet-filters

I'm working with an websphere liberty profile webserver where i have deployed a couple of applications.
These applications are sending request message's, I want to create a servlet-filter without changing the applications
so i can see what the application is sending and receiving. Also i want to add new request headers.

You can use a ServletContainerInitializer to register new ServletFilters. An example implementation that adds a response header might look like this:
public class SCI implements ServletContainerInitializer {
#Override
public void onStartup(Set<Class<?>> arg0, ServletContext arg1)
throws ServletException {
arg1.addFilter("myFilter", MyFilter.class).addMappingForUrlPatterns(null, false, "/*");
}
}
The MyFilter class would look like this:
public static class MyFilter implements Filter {
#Override
public void destroy() { }
#Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
if (arg1 instanceof HttpServletResponse) {
((HttpServletResponse) arg1).addHeader("Test", "Test");
}
arg2.doFilter(arg0, arg1);
}
#Override
public void init(FilterConfig arg0) throws ServletException { }
}
You then need to register this using a file in called META-INF/services/ServletContainerInitializer which should contain the fully qualified class name of the Servlet Container Initializer, for example:
test.SCI
Normally you package these in a jar in the application, but since you don't want to update the application you instead configure the server like this:
<featureManager>
<feature>bells-1.0</feature>
</featureManager>
<library id="init">
<file name="path/to/jar"/>
</library>
<bell libraryRef="init"/>
The ServletContainerInitializer will be called for all started Web applications allowing you to add the filter. Note this will be called for all started Web applications including ones integrated into the Liberty runtime, such as the Admin Center and the REST connector.

I got the below response when I tried to install the same bells utility
CWWKF1295E: The bells-1.0 asset cannot be downloaded or installed to IBM WebSphere Application Server Liberty (ILAN) 19.0.0.4 because it applies only to the following product editions and versions:
IBM WebSphere Application Server Liberty 8.5.5.7
IBM WebSphere Application Server Liberty for Developers 8.5.5.7
IBM WebSphere Application Server Liberty - Express 8.5.5.7
IBM WebSphere Application Server Liberty Liberty Core 8.5.5.7
IBM WebSphere Application Server Liberty Network Deployment 8.5.5.7
IBM WebSphere Application Server Liberty z/OS 8.5.5.7
Use the installUtility find action to retrieve a list of assets that apply to your installation.

Related

url was not normalized error when using intellij but not when using STS

The developed website works fine on remote server and local machine (when using STS IDE) , recently I started use Intellij IDEA (I created a duplicate of the website code with no any changes ), I started getting the URL was not normalized error.
Does intellij handles Spring security somehow differently than STS ? or what could be the cause?
I don't want use custom httpfirewal .
#EnableGlobalMethodSecurity(prePostEnabled=true)
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider())
.jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// URLs matching for access rights
http.authorizeRequests()
.antMatchers( "/", "/contact","/register").permitAll()
.antMatchers("/accounts").hasAnyAuthority("SUPER_USER","ADMIN_USER")
.anyRequest().authenticated()
.and()
// form login
.csrf().disable().formLogin()
.loginPage("/index")
.failureUrl("/index?error=true")
.defaultSuccessUrl("/user")
.usernameParameter("email")
.passwordParameter("password")
.and()
// logout
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
and this is from the properties :
# Spring MVC view prefix.
spring.mvc.view.prefix=/templates/
# Spring MVC view suffix.
spring.mvc.view.suffix=.html
the error is :
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.
P.S: I'm using JDK8 ,Spring Boot 2,Spring Security ,thymeleaf,intellij U 2019.2
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.
Which IDE to use should not have any differences for running the same source codes on the embeddable server configured by springboot. This error happens when the HTTP requests that send to server is not normalised which the URL contains character sequences like ./, /../ , // or /. So I doubt that it is due to you are using different URL to browse the app. For example, you are accidentally adding a '/' in the URL such as http://127.0.0.1:8080/app//index.html
You can change to use a less secure HttpFirewall to avoid such checking by :
#Override
public void configure(WebSecurity web) throws Exception {
web.httpFirewall(new DefaultHttpFirewall());
//another configuration .....
}
P.S. Though it is called DefaultHttpFirewall , it is not the default HttpFirewall used by Spring Security since 4.2.4 which is less secured than the actual default StrictHttpFirewall

TomEE Embedded: Resource defined in resources.xml not available within webapp

I'm currently trying to run a simple webapp on TomEE Embedded (TomEE Version 7.0.5).
According to the docs, I can start the TomEE and deploy the classpath as a webapp like this. I've set the document base to src/main/webapp.
try (final Container container = new Container(new Configuration())
.deployClasspathAsWebApp("", new File("src/main/webapp"))) {
container.await();
}
I have defined a datasource in WEB-INF/resources.xml which looks like this:
<Resource id="myDataSource" type="javax.sql.DataSource">
JdbcDriver org.hsqldb.jdbcDriver
JdbcUrl jdbc:hsqldb:file:hsqldb
UserName sa
Password
</Resource>
And I've setup a reference in the web.xml:
<resource-ref>
<res-ref-name>myDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
</resource-ref>
Then I try to lookup this datasource in my Servlet via JNDI.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
Context initCtx = new InitialContext();
DataSource ds = (DataSource) initCtx.lookup("java:comp/env/myDataSource");
Connection connection = ds.getConnection();
...
}
When the TomEE starts, it seems like my DataSource is created (at least there is some output about that in the logs). However when I try to lookup the DataSource in my servlet, I get an unconfigured dbcp2 connection pool as a DataSource which throws the following exception when ds.getConnection() is called:
java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2186)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2066)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1525)
at TestServlet.doGet(TestServlet.java:32)
...
The same configuration works fine on a standalone TomEE (I tried TomEE Webprofile) or when using the TomEE Maven Plugin. Is there anything I'm missing to get it running also for Embedded TomEE?
Thanks in advance
Tomee embedded does not bind a custom webapp classloader by default so does not have comp/ always bound. You can pass properties to the context to force it to be openejb one or use openejb:Resource/myDataSource or java:openejb/Resource/myDataSource naming.

How to get past the Authentication Required Spring-boot Security

I have put in the password which is "root" and it keeps popping back up. How can I suppress this or get rid of it. I am using spring boot and spring security.
application.properties
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootpractice
spring.datasource.username=root
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: update
entitymanager.packagesToScan: /
I am using intellij 14 if that matters.
----Update 1-----
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/index")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/index")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
This class has to be in a parent package of all other packages:
WebSecurityConfig.
Also in application.properties set:
security.basic.enabled=false
ACV's answer is probably the easiest way to turn off the authentication completely by adding security.basic.enabled=false to the application.properties file which is usually located under src/main/resources folder.
or you just type in the password :)
1. use default password
When you run your spring application, there is usually a whole bunch of logging printed, which people usually don't read. The password is actually generated and printed to the screen at the startup. and the username is simply user. If you are testing using a browser and it probably only need you enter it once and caches it, so once for all, you should be securely logged in without authenticating every time.
(however, every time you restart your app, it will generate a new password)
2. customize your password
Add the following properties to your application.properties if you want to customize your username and password:
security.user.name=myuser
security.user.password=mypassword
And here is how it looks like with your own username and password
Reference:
Spring Boot Features - Security
Monitoring and Management over HTTP
You can bypass this spring boot security mechanism. See an example below for this:
#SpringBootApplication
#EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
public class SampleSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SampleSpringBootApplication.class, args);
}
}
When Spring Security is in the classpath, Spring Boot by default secures all your pages with Basic authentication. That's why you are being asked for userid and password.
You will need to configure the security. To do so, commonly people would extend a WebSecurityConfigurerAdapter, like this:
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
...
Refer this Spring Security guide for more details.
Here was the issues
(1) .loginPage("/index") was saying my login page was at index, however I just wanted to use spring's default login page.
(2) had to to move the security package inside the demo package (the main package). Thanks to #Sanjay for suggesting that. I tried to use #ComponantScan but it could not get it to work.

Apache cxf java client + ntlm authentication and multi user support

I am using apache cxf java client to connect my WS. I am also using NTLM for authentication.
Now problem I am facing due to credential caching. First time i tried user which does not have privileges to access WS method. when I changed the user , it is still using same user to access WS method.
I am running in tomcat, so cannot kill my JVM .. tried all possible combination on httpClientPolicy.
Any help will be appreciated.
This is NTLM specific problem. sun.net.www.protocol.https.HttpsURLConnectionImpl is getting serverAuthorization via java.net.Authenticator. requestPasswordAuthentication(). This authorization info is maintained in sun.net.www.protocol.http.AuthCacheValue.cache.
So if we override sun.net.www.protocol.http.AuthCacheValue means we can fix this issue.
AuthCacheValue.setAuthCache(new AuthCache()
{
#Override
public void remove(String arg0, AuthCacheValue arg1) { }
#Override
public void put(String arg0, AuthCacheValue arg1) { }
#Override
public AuthCacheValue get(String arg0, String arg1)
{
return null;
}
});
Reference :
http://web.archiveorange.com/archive/v/ACbGtycfTs2dqbRNpy6d
http://tigrou.nl/2011/06/11/cached-credentials-in-http-basic-authentication/
I googled and tried a lot of solutions to this problem.. apparently the simplest code that worked is as below using the JCIFS library
//Set the jcifs properties
jcifs.Config.setProperty("jcifs.smb.client.domain", "domainname");
jcifs.Config.setProperty("jcifs.netbios.wins", "xxx.xxx.xxx.xxx");
jcifs.Config.setProperty("jcifs.smb.client.soTimeout", "300000"); // 5 minutes
jcifs.Config.setProperty("jcifs.netbios.cachePolicy", "1200"); // 20 minutes
jcifs.Config.setProperty("jcifs.smb.client.username", "username");
jcifs.Config.setProperty("jcifs.smb.client.password", "password");
//Register the jcifs URL handler to enable NTLM
jcifs.Config.registerSmbURLHandler();
Apparently CXF 3.0 doesnt have a valid way of configuring the HTTP Client (4.3.x) with NTCredentials instance. Please refer to bug https://issues.apache.org/jira/browse/CXF-5671
By the way, if you have a simple message which needs to be transmitted, just use HTTP Client (I worked using 4.3.4.. not sure of the earlier versions) with NTCredentials Instance. That too did the magic for me.. The sample is as below:
final NTCredentials ntCredentials = new NTCredentials("username", "Passworrd","destination", "domain");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, ntCredentials);
CloseableHttpClient httpclient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(credsProvider)
.build();

Exception error in google doc api

I am new to google api. I am trying to create a simple web application (Java EE) to read DocumentListFeed from google doc. My code in the servlet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
DocsService service = new DocsService("Document List Demo");
service.setUserCredentials(NAME, PASSWORD);
response.getWriter().println("helloooooo");
//URL documentListFeedUrl = new URL("http://docs.google.com/feeds/documents/private/full");
URL documentListFeedUrl = new URL("https://docs.google.com/feeds/default/private/full?v=3");
DocumentListFeed feed = service.getFeed(documentListFeedUrl, DocumentListFeed.class);
for(DocumentListEntry entry : feed.getEntries())
{
response.getWriter().println(entry.getTitle().getPlainText());
}
}
catch (Exception e)
{
response.getWriter().println(e);
}
}
But it is showing me the error: java.lang.NoClassDefFoundError: com/google/gdata/client/docs/DocsService
I am using Glassfish server and Ecllipse. And added external jar file: activation.jar, guava-r07.jar, mail.jar, servlet.jar, gdata-client-1.0.jar, gdata-client-meta-1.0.jar, gdata-core-1.0.jar, gdata-media-1.0.jar, gdata-docs-3.0.jar, gdata-docs-meta-3.0.jar.
I have copied this same code to java standard edition and it is working fine. Could please tell me why this thing is not working in Java EE? Is it a problem in GlassFish server?
It just means that the jars are not present in your Glassfish server classpath.
Add all the jars you listed to yuor glassfish server classpath. Since am not an Glassfish expert i cannot help you in adding the jars to your server.
In case of weblogic, you just need to package all the jars in your project APP-INF directory.
Hope it helps.