How to maintain users sessions in DropWizard 1.0.x - session

The correct way to configure and (de)reference HttpSessions in DropWizard 1.0.x is not documented. How is it done?
Versions 0.7.x and 0.8.x are covered by this question, but it seems like things have changed as some of the classes referenced are not part of 1.0.x afaict.

You don't need the line with the class that isn't available, or Spring Boot.
environment.jersey().register(HttpSessionProvider.class);
environment.servlets().setSessionHandler(new SessionHandler());
Then, for instance:
#GET
#Path("/email")
#Produces(MediaType.TEXT_PLAIN)
public Response getSessionEmail(#Context HttpServletRequest request) {
return Response.ok(request.getSession().getAttribute("email")).build();
}

Forget it, use Spring Boot.
Spring has a heritage of front end technologies to preserve and is a better fit for anything that naturally requires a session.

Related

Is it possible to set Redis key expiration time when using Spring Integration RedisMessageStore

Dears, I'd like to auto-expire Redis keys when using org.springframework.integration.redis.store.RedisMessageStore class in Spring Integration. I see some methods related to "expiry callback" but I could not find any documentation or examples yet. Any advice will be much appreciated.
#Bean
public MessageStore redisMessageStore(LettuceConnectionFactory redisConnectionFactory) {
RedisMessageStore store = new RedisMessageStore(redisConnectionFactory, "TEST_");
return store;
}
Spring Boot: 2.6.3, spring integration and spring-boot-starter-data-redis.
The RedisMessageStore does not have any expiration features. And technically it must not. The point of this kind of store is too keep data until it is used. Look at it as persistent storage. The RedisMetadataStore is based on the RedisProperties object, so it also cannot use expiration feature for particular entry.
You probably talk about a MessageGroupStoreReaper, which really calls a MessageGroupStore.expireMessageGroups(long timeout), but that's already an artificial, cross-store implementation provided by the framework. The logic relies on the group.getTimestamp() and group.getLastModified(). So, still not that auto-expiration Redis feature.
The MessageGroupStoreReaper is a process needed to be run in your application: nothing Redis-specific.
See more info in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/message-routing.html#reaper

Axon 4 XStream configuration

When running my Spring Boot app which includes Axon 4 I see the following in my output console:
Security framework of XStream not initialized, XStream is probably vulnerable.
How do I go about securing the XStream included in Axon 4?
For clarification, I am speaking about how to configure the XStream that Axon 4 uses. I am not certain if this should be done in the YAML file or in one of the Configuration classes. Every where I have tried the information detailed in this answer does not affect the XStream configuration and I still get the same warning.
Update:
Based on the answers below, this question seems to be two fold. Thanks to the answers below I managed to get this working as follows (based on information posted at this answer):
//AxonConfig.java
#Bean
XStream xstream(){
XStream xstream = new XStream();
// clear out existing permissions and set own ones
xstream.addPermission(NoTypePermission.NONE);
// allow any type from the same package
xstream.allowTypesByWildcard(new String[] {
"com.ourpackages.**",
"org.axonframework.**",
"java.**",
"com.thoughtworks.xstream.**"
});
return xstream;
}
#Bean
#Primary
public Serializer serializer(XStream xStream) {
return XStreamSerializer.builder().xStream(xStream).build();
}
I didn't want to answer my own question as I think Jan got the correct answer combined with Steven pointing to the Spring Boot config.
I am certain I will need to whittle away at the package scopes and will do so in due course. Thanks Jan and Steven for your assistance.
This is not Axon specific, check this question for background and solution: Security framework of XStream not initialized, XStream is probably vulnerable
Jan Galinski is right in that this isn't an Axon specific issue per say. More so a shift within the XStream package. Regardless, the link Jan shares is very valuable.
From there, you can create your own XStream object, instead of using the one the XStreamSerializer creates for you when utilizing Axon. You can then feed that object to the builder() of the XStreamSerializer.
As you are using Spring Boot too, simply having a bean creation function like so would suffice:
// The XStream should be configured in such a way that a security solution is provided
#Bean
public Serializer serializer(XStream xStream) {
return XStreamSerializer.builder().xStream(xStream).build();
}
Hope this helps!

Spring Boot Actuator paths not enabled by default?

While updating my Spring Boot application to the latest build snapshot and I am seeing that none of the actuator endpoints are enabled by default. If I specify them to be enabled in application.properties, they show up.
1) Is this behavior intended? I tried searching for an issue to explain it but couldn't find one. Could somebody link me to the issue / documentation?
2) Is there a way to enable all the actuator endpoints? I often find myself using them during development and would rather not maintain a list of them inside my properties file.
Two parts to this answer:
"Is there a way to enable all the actuator endpoints?"
Add this property endpoints.enabled=true rather than enabling them individually with endpoints.info.enabled=true, endpoints.beans.enabled=true etc
Update: for Spring Boot 2.x the relevant property is:
endpoints.default.web.enabled=true
"Is this behavior intended?"
Probably not. Sounds like you might have spotted an issue with the latest milestone. If you have a reproducible issue with a Spring Boot milestone then Spring's advice is ...
Reporting Issues
Spring Boot uses GitHub’s integrated issue tracking system to record bugs and feature requests. If you want to raise an issue, please follow the recommendations below:
Before you log a bug, please search the issue tracker to see if someone has already reported the problem.
If the issue doesn’t already exist, create a new issue.
Even if we enable all the actuator endpoints as below
management.endpoints.web.exposure.include=* (In case of YAML the star character should be surrounded by double quotes as "*" because star is one of the special characters in YAML syntax)
The httptrace actuator endpoint will still not be enabled in web by default. HttpTraceRepository interface need to be implemented to enable httptrace (See Actuator default endpoints, Actuator endpoints, Actuator httptrace).
#Component
public class CustomHttpTraceRepository implements HttpTraceRepository {
AtomicReference<HttpTrace> lastTrace = new AtomicReference<>();
#Override
public List<HttpTrace> findAll() {
return Collections.singletonList(lastTrace.get());
}
#Override
public void add(HttpTrace trace) {
if ("GET".equals(trace.getRequest().getMethod())) {
lastTrace.set(trace);
}
}
}
Now the endpoints can be accessed using the url,
http://localhost:port/actuator/respective-actuator-endpoint
(Example http://localhost:8081/actuator/httptrace)
If there is a management.servlet.context-path value present in properties file then the URL will be,
http://localhost:port/<servlet-context-path>/respective-actuator-endpoint
(Example http://localhost:8081/management-servlet-context-path-value/httptrace)
UPDATE: use this only in dev environment, not in production!
Is there a way to enable all the actuator endpoints?
Using Spring Boot 2.2.2 Release, this worked for me:
On the file src/main/resources/application.properties add this:
management.endpoints.web.exposure.include=*
To check enabled endpoints go to http://localhost:8080/actuator
Source: docs.spring.io

Shiro with SAML2 in Karaf with JAX-RS (Jersey)

I am creating an application that runs in Karaf as OSGi container, and uses the OSGi HTTP Service and Jersey for exposing REST APIs. I need to add SAML2 authentication and permissions-based authorization. I would like to use the annotation based approach in Shiro for this, as spring seems to be moving away from OSGi. My questions:
Is Shiro with SAML jars a good fit in OSGi environments?
I want to use WSO2 as the identity provider. Are there any caveats of Shiro and WSO2 working together?
For using annotations, the Shiro docs indicate I need to put AspectJ/Spring/Guice jars - Is this still valid in OSGi environments? I would prefer Guice for all my DI needs.
Would be great to have some insights from Shiro users.
UPDATE
I'm using this project: osgi-jax-rs-connector. So, I use Guice-Peaberry to register OSGi services with the interfaces annotated with #Path or #Provider, and the tool takes care of converting them into a REST resource. (Similar to pax-whiteboard?). I was planning to similarly expose my filters as OSGi services, and then dynamically add them along with the resources.
I have had headaches with AspectJ in OSGi in a previous project where I had to switch to vanilla Equinox from Karaf because the equinox weaving hook was not agreeing with Karaf (stack traces from Aries were seen, among other things). So, would doing something like shiro-jersey be better?
I'm sure it is doable, though I already see some restrictions/issues poping up.
for
1) haven't tried it, though you need to make sure that you tell the pax-web and jetty about it, it'll require adding this to the jetty.xml and it might even need to add a fragment bundle to pax-web-jetty so the desired class can be loaded. This will most likely be your first classnotfound issue.
2) don't know of WSO2 so no idea
3) if you want to use annotations, be careful. For Guice you'll mostlikely will need to use Peaberry since afaik Guice isn't "OSGi-fied" yet. Using AspectJ isn't really a good idea in a OSGi environment due to the classloader restrictions. If you have a compile-time weaving it should be fine, but run-time weaving will be a challange.
UPDATE:
Completely forgot about it, but there is a Pax Shiro Project available, maybe this can be a good starting point to get your setup in a correct lineup.
In the interest of readers, I'm sharing the solution I arrived at after some research of existing tools. First, the easy part: Using Shiro annotations in an OSGi environment. I ended up writing the below class since most Shiro-Jersey adapters shared by developers is based on Jersey 1.x.
#Provider
public class ShiroAnnotationResourceFilter implements ContainerRequestFilter {
private static final Map, AuthorizingAnnotationHandler> ANNOTATION_MAP = new HashMap, AuthorizingAnnotationHandler>();
#Context
private ResourceInfo resourceInfo;
public ShiroAnnotationResourceFilter() {
ANNOTATION_MAP.put(RequiresPermissions.class,
new PermissionAnnotationHandler());
ANNOTATION_MAP.put(RequiresRoles.class, new RoleAnnotationHandler());
ANNOTATION_MAP.put(RequiresUser.class, new UserAnnotationHandler());
ANNOTATION_MAP.put(RequiresGuest.class, new GuestAnnotationHandler());
ANNOTATION_MAP.put(RequiresAuthentication.class,
new AuthenticatedAnnotationHandler());
}
public void filter(ContainerRequestContext context) throws IOException {
Class resourceClass = resourceInfo.getResourceClass();
if (resourceClass != null) {
Annotation annotation = fetchAnnotation(resourceClass
.getAnnotations());
if (annotation != null) {
ANNOTATION_MAP.get(annotation.annotationType())
.assertAuthorized(annotation);
}
}
Method method = resourceInfo.getResourceMethod();
if (method != null) {
Annotation annotation = fetchAnnotation(method.getAnnotations());
if (annotation != null) {
ANNOTATION_MAP.get(annotation.annotationType())
.assertAuthorized(annotation);
}
}
}
private static Annotation fetchAnnotation(Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (ANNOTATION_MAP.keySet().contains(annotation.annotationType())) {
return annotation;
}
}
return null;
}
}
The complete project is here.
The above took care of Part 3 of my question.
For Shiro with SAML, I am using the Servicemix wrapped openSAML jar, and it seems to be working okay till now. I did however had to write a bit of code to make Shiro work with SAML2. It's almost on the same lines as shiro-cas, but is a bit more generic to be used with other IdPs. The code is kind of big so sharing a link to the project instead of copying classes to SO. It can be found here.
Now that I have some abstraction between my code and my IdP, WSO2 integration looks a bit simpler.
P.S. Thanks Achim for your comments and suggestions.

Available paths listing for Spring actions

I have an application which exposes RESTful actions using spring annotations and Spring MVC.
It looks like
#RequestMapping(value = "/example/{someId}",
method = RequestMethod.GET, consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void isRegisteredToThread(#PathVariable long someId, HttpServletResponse response) {
[something]
}
What I want is an automatically generated listing of all URL's, methods and available parameters - possibly within a WSDL. Is there a plugin or is it somehwere available?
WSDL is not done for rest, it's used for SOAP.
You might use WADL, but I really do not suggest it.
In my project I always use swagger (there is a release for spring). You may find more info here https://github.com/martypitt/swagger-springmvc and here http://blog.zenika.com/index.php?post/2013/07/11/Documenting-a-REST-API-with-Swagger-and-Spring-MVC
Give it a try.
As an alternative, if you don't need something web-based, you may try rest-shell (https://github.com/spring-projects/rest-shell)
You could take a look at the source code of RequestMappingEndpoint provided by the Spring Boot and see how Spring Boot reports the mappings.
Looking through that code one can see that the mappings (both handler and method mappings) can easily be obtained from the applicationContext
(using
applicationContext.getBeansOfType(AbstractUrlHandlerMapping.class)
and
applicationContext.getBeansOfType(AbstractHandlerMethodMapping.class)
respectively). After you have obtained the mapping you can process them anyway you like.
You might want to create a library that could include in all your projects that processes the mapping your organizations desired form

Resources