SEAM - get url of base65 authentication - java

I have this config in my components.xml:
<web:authentication-filter url-pattern="/resource/rest/*" auth-type="basic"/>
<security:identity authenticate-method="#{basicAuthenticator.login}"/>
Well, my basicAuthenticator is a Stateless seam component where i have that login method which returns true/false depending on credentials.
I do really want to find the host (url adress) of the request.
Of course i can use ExternalContext like:
#In(value = "#{facesContext.externalContext}", required = false)
private ExternalContext externalContext;
but it gives me null because i have no jsf here...
Do you know any other way?
Thanks.

Cristian,
Because ServletFilter will always be called before FacesServlet, you will always get null.
So do not use
private #In FacesContext facesContext;
anymore when using Servlet Filter.
Solution: well, it can not be The best solution but it solves what you want to do
Create a CustomAuthenticationFilter as follows
#Scope(APPLICATION)
#Name("org.jboss.seam.web.authenticationFilter")
#Install(value = false, precedence = BUILT_IN)
#BypassInterceptors
#Filter(within = "org.jboss.seam.web.exceptionFilter")
public class CustomAuthenticationFilter extends org.jboss.seam.web.AbstractFilter {
/**
* Because of some private methods defined in AuthenticationFilter
* do Ctrl + C / Ctrl + V All of source code of AuthenticationFilter
*
* Except authenticate method which is shown bellow
*/
private void authenticate(HttpServletRequest request, final String username) throws ServletException, IOException {
new ContextualHttpServletRequest(request) {
#Override
public void process() throws ServletException, IOException, LoginException {
Identity identity = Identity.instance();
identity.getCredentials().setUsername(username);
try {
identity.preAuthenticate();
/**
* Yes, THE SAME LOGIC performed by authenticate-method must goes here
*/
/**
* Do not use #In-jection here
*
* Use context lookup instead
* For instance, UserService userService = (UserService) Contexts.lookupInStatefulContexts("userService");
*/
identity.postAuthenticate();
} finally {
// Set password to null whether authentication is successful or not
identity.getCredentials.setPassword(null);
}
}
}.run();
}
}
Now overrides default AuthenticationFilter in /WEB-INF/componets.xml
<web:rewrite-filter view-mapping="/resource/rest/*"/>
<component name="org.jboss.seam.web.authenticationFilter" class="br.com.ar.seam.CustomAuthenticationFilter">
<property name="urlPattern">/resource/rest/*</property>
<property name="authType">basic</property>
</component>
And To enable restURL do as follows
web.xml
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!--HERE GOES NON-REST INTERCEPTED URL-->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.seam</url-pattern>
</servlet-mapping>
<!--HERE GOES REST INTERCEPTED URL-->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Now, let's suppose you want to call /resource/rest/user which matchs restURL servlet-mapping. In /WEB-INF/pages.xml declare
<page view-id="<VIEW_ID_GOES_HERE>">
<rewrite pattern="/resource/rest/user"/>
<rewrite pattern="/resource/rest/{userId}"/>
<!--userId comes from pattern shown above-->
<param name="userId" value="#{userService.userId}"/>
</page>
To avoid FacesServlet intercept any client-side resource such as css, javaScript and images files, you can define
<servlet>
<servlet-name>Seam Resource Servlet</servlet-name>
<servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Seam Resource Servlet</servlet-name>
<url-pattern>/resource/*</url-pattern>
</servlet-mapping>
Which does not apply JSF lifecycle. Make sure put Seam Resource Servlet above FacesServlet declaration.

Related

Disable Swagger in Jersey 2.X

I am following the swagger tutorial to swaggerize my web application.
. I am using package scanning and Swagger's BeanConfig for swagger initialization. Is there a way to disable swagger in specific environment (e.g. production)? There are some discussion talking about disabling swagger with SpringMVC
Here is my web.xml
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
io.swagger.jaxrs.listing,
com.expedia.ord.ops.rest
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Hooking up Swagger-Core in your application -->
<servlet>
<servlet-name>SwaggerServlet</servlet-name>
<servlet-class>com.expedia.ord.ops.util.SwaggerServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SwaggerUI</servlet-name>
<jsp-file>/SwaggerUI/index.html</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>SwaggerUI</servlet-name>
<url-pattern>/api/docs/*</url-pattern>
</servlet-mapping>
Here is my Swagger servlet:
public class SwaggerServlet extends HttpServlet
{
static private final String[] SCHEMES = {"http"};
#Value("${swagger.enable}")
private boolean enableSwagger;
#Value("${swagger.resource.package}")
private String resourcePackage;
#Value("${swagger.host}")
private String host;
#Value("${swagger.basePath}")
private String basePath;
#Value("${swagger.api.version}")
private String version;
#Override
public void init(final ServletConfig config) throws ServletException
{
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
final BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion(version);
beanConfig.setSchemes(SCHEMES);
beanConfig.setHost(host);
beanConfig.setBasePath(basePath);
beanConfig.setResourcePackage(resourcePackage);
beanConfig.setScan(enableSwagger);
}
}

How to make a RESTEasy Response Filter?

I'm having trouble trying to make RESTEasy Filters work. I'm sure that I'm missing something, but I don't know what.
I'm testing with the following method:
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<User> listAll(#QueryParam("start") Integer startPosition, #QueryParam("max") Integer maxResult) {
String hql = "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.tasks ORDER BY u.id";
TypedQuery<User> findAllQuery = em.createQuery(hql, User.class);
if (startPosition != null) {
findAllQuery.setFirstResult(startPosition);
}
if (maxResult != null) {
findAllQuery.setMaxResults(maxResult);
}
final List<User> results = findAllQuery.getResultList();
return results;
}
And here's my web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="3.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>tasks-webapp</display-name>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<mime-mapping>
<extension>ico</extension>
<mime-type>image/x-icon</mime-type>
</mime-mapping>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>br.com.tasks.rest.CORSFilter</param-value>
</context-param>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
And finally, my Filter:
#Provider
public class CORSFilter implements ContainerResponseFilter {
#Override
public void filter(final ContainerRequestContext requestContext,
final ContainerResponseContext cres) throws IOException {
cres.getHeaders().add("Access-Control-Allow-Origin", "*");
cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
cres.getHeaders().add("Access-Control-Max-Age", "1209600");
}
}
With this combined It's not working. I left an breakpoint in the filter and it's never called. And I'm testing with Postman and my headers are missing. I saw other questions here and I followed it's instructions without success. I tried with the Application class and nothing too.
Someone help me? I'm grateful in advance. :)
Have you tried adding:
<context-param>
<param-name>resteasy.scan.providers</param-name>
<param-value>true</param-value>
</context-param>
To register your providers as explained here ? Because it seems that default value is false

All Request redirect specific url

I serve my app in localhost:8084/ues/. I want to redirect all request from localhost:8084/ues/* to localhost:8084/ues/index.jsp. How can I to do this?
In your web.xml have the below code,
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/ues/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.myPackage.redirectServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
public class redirectServletextends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
RequestDispatcher dispatcher = request.getRequestDispatcher("/pages/index.jsp");
dispatcher.forward(request, response);
}
catch(Exception e)
{
//catch your exceptions
}
}
}
Define a filter in Deployment Descriptor like
<filter>
<filter-name>Filter-Name</filter-name>
<filter-class>Fully-Qualified-Class-Name</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter-Name</filter-name>
<url-pattern>ues/*</url-pattern>
</filter-mapping>
and redirect to your desired Jsp from the Filter

Google App Engine (Java) - Redirection to jsp from web.xml

I have problems whit redirections and Servlets in Google App Engine.
I have an index.jsp and a list.jsp, but I can't get the results expected.
I have this in web.xml:
<filter-name>URIParserFilter</filter-name>
<filter-class>com.bbva.icaro2.web.filters.URIParserFilter</filter-class>
</filter>
<servlet>
<servlet-name>EntitiesAdminServlet</servlet-name>
<servlet-class>com.myproject.web.EntitiesAdminServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ListServlet</servlet-name>
<servlet-class>com.myproject.web.ListServlet</servlet-class>
<jsp-files>/lists/lists.jsp</jsp-files>
</servlet>
<servlet-mapping>
<servlet-name>EntitiesAdminServlet</servlet-name>
<url-pattern>/admin/entities/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ListServlet</servlet-name>
<url-pattern>/lists/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
When I access to http://myproject/lists/mylist
The thread goes to URIParserFilter:
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
String entityKind = null;
String id = null;
String pathInfo = ((HttpServletRequest)req).getPathInfo();
String pathString = (pathInfo == null || pathInfo.equals("/")) ? "" : pathInfo.substring(1);
String[] parts = pathString.split("/");
entityKind = parts[0].trim();
id = (parts.length > 1) ? parts[1].trim() : null;
req.setAttribute(Constants.REQ_ATTR_REQ_ENTITYKIND, entityKind); // entityKind = "mylist"
req.setAttribute(Constants.REQ_ATTR_REQ_ENTITYID, id);
chain.doFilter(req, resp);
}
And then it goes to list.jsp whitout pass through ListServlet :-(
In case of http://myproject/admin/entities/hello it works!
The classes are exactly the same...
What I'm doing wrong?
Thanks, and sorry for my bad english...
write the only <jsp-files> with url pattern.it will redirect to jsp file.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.uks.MyServlet</servlet-class>
<jsp-files>/jsp/my.jsp</jsp-files>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
Do a forward from your servlet to your jsp page. Don't map the jsp in web.xml.
So do whatever you need to in your servlet and then:
String destination = "/jsp/my.jsp";
RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
rd.forward(request, response);

How to use #RequestMapping headers?

I am studying springmvc. When I use #RequestMapping(value="/helloWorld", headers = "content-type=text/*") and connect to http://localhost:8080/SpringMVC_10100/helloWorld, the following is output in the console:
WARN
org.springframework.web.servlet.PageNotFound
- No matching handler method found for servlet request: path '/helloWorld',
method 'GET', parameters
map[[empty]]
My code is:
#Controller
public class HelloWordController {
private Logger logger = LoggerFactory.getLogger(HelloWordController.class);
#RequestMapping(value="/helloWorld", headers = "content-type=text/*")
public ModelAndView helloWorld() {
logger.debug("jin ru le");
logger.info("The helloWorld() method is use");
ModelAndView view = new ModelAndView();
view.setViewName("/helloworld");
return view;
}
}
web.xml is
<servlet>
<description>This is Spring MVC DispatcherServlet</description>
<servlet-name>SpringMVC DispatchServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>SpringContext</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC DispatchServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Why?
Its most likely the case that /helloworld is not inside the path configured for your dispatcher servlet
e.g. If i have a servlet configured like so:
<servlet>
<servlet-name>BMA</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>BMA</servlet-name>
<url-pattern>/bma/*</url-pattern>
</servlet-mapping>
And i have a controller configured like so:
#RequestMapping(value = "/planner/plan/{planId}/delete", method = RequestMethod.GET)
public ModelAndView deletePlanConfirm(HttpServletRequest request,
#PathVariable("planId") Long planId) {}
Then the request in browsder would be:
http://localhost:8080/bma/planner/plan/1223/delete
Edit:
Also if you have content-type header narrowing on your handler, make sure that content-type haeder is sent in your request.
In the below annotation remove the headers:
#RequestMapping(value="/helloWorld", headers = "content-type=text/*")
to:
#RequestMapping(value="/helloWorld", method = RequestMethod.GET)
or to:
#RequestMapping(value="/helloWorld")
should make it work.

Categories