Spring #Scope("token") in component #Component - java

I have application with Angular 5 frontend and Spring 5 REST-backend. I need spring component, witch created one time for one token. If I been using non REST API I could use #Scope("session"). But now Session ID is different for each request.
I need that, because java.security.Principal in provides only username. But I need filtering my entities by customer ID.
I do not want to get customer from database while each request.

Create your own scope . Read spring doc to use a custom scope ,or go to Using custom scope . You will find plenty of examples,
Create a class TokenScope implementing Scope interface and use it as you use any other scope for a bean.
For a typical spring boot app
#Qualifier
#Scope("token")
#Target({ ElementType.TYPE, ElementType.METHOD })
#Retention(RetentionPolicy.RUNTIME)
public #interface TokenScoped {
}
and use it.
#Component
#TokenScoped
class SomeBean

Related

Can I use #PreAuthorize in a simple class ( not a #Component)

I am trying to add control authorization in some methods using
#PreAuthorize("hasRole('ADMIN')").
Methods belong to a simple class DaoImpl implementing an interface DAO,
I add this
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
to my security config class.
for me it doesn't work, is it logic or I miss something?
The answer is no.
Spring can only enforce annotations on classes it is aware of. To make spring aware of instantiated classes it needs to either instantiate them itself, which means the class needs to be annotated with one of springs lifecycle annotations ex. #Component, #Service #RestController, or you need to instantiate them yourself and hand them over to the spring context. This can for instance be done by using the new keyword in a #Bean annotated function in a #Configuration annotated class and then return the newly created class from the #Bean annotated function.
If you create the class yourself by using the new keyword just randomly in your application, spring will have no awareness of the class and hence has no ability to intercept function calls using spring AOP and in turn enforce annotations on them like for instance #PreAuthorize

When to use #ServerEndpoint vs #Controller in Java spring boot framework?

Can someone point out the differences between the 2 and when it is appropriate to use which one?
When a class annotated by #ServerEndpoint is registered to a server-side WebSocket endpoint and every time the corresponding endpoint's WebSocket is connected to the server, its instance is created and managed by JWA implementation.
Classic controllers can be annotated with the #Controller annotation. This is simply a specialization of the #Component class and allows implementation classes to be autodetected through the classpath scanning.
Hope this helps
#ServerEndPoint is an annotation for the web socket, and #Controller is an annotation for the web. (Similarly there is #RestController.)
Maybe this article can help:
https://spring.io/blog/2013/05/23/spring-framework-4-0-m1-websocket-support
#ServerEndpoint: If decorated with #ServerEndpoint, the container ensures availability of the class as a WebSocket server listening to a specific URI space
#ServerEndpoint(value="/chat/{username}")
public class ChatEndpoint {
----
}
#Controller: If decorated with #Controller annotation is an annotation used in Spring MVC framework (the component of Spring Framework used to implement Web Application). The #Controller annotation indicates that a particular class serves the role of a controller. The #Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects #RequestMapping annotations.

Deltaspike and #Stateless Bean

I want to secure my "Stateless" EJb with the DeltaSpike-API.
#Stateless
#Remote(UserServiceRemote.class)
public class UserService implements UserServiceRemote
At method level i have a custom annotation "Support"
#Support
public void doSomething() {}
Therefore i wrote a custom annotation "#Support":
#Retention(value = RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE, ElementType.METHOD })
#Documented
#SecurityBindingType
public #interface Support {
My custom Authorizer looks like:
#Secures
#Support
public boolean doAdminCheck(Identity identity, IdentityManager identityManager, RelationshipManager relationshipManager)
throws Exception {
return hasRole(relationshipManager, identity.getAccount(), getRole(identityManager, "Support"));
}
In my "beans.xml" file i included:
<interceptors>
<class>org.apache.deltaspike.security.impl.extension.SecurityInterceptor</class>
</interceptors>
But after i log in my application and call the "doSomething" method per remote call the "Support" annotation is ignored, no matter if I have the role or not.
What I'm doing wrong? Thanx for all suggestions!!!
Ejb and CDI are two different concepts. A stateless session bean and a managed CDI bean are managed by different containers. So you cannot use Deltaspike on a stateless session bean.
If you want to use deltaspike security, use a named bean instead and use a different remoting strategy.
In my case I had to make sure that module (jar) containing service I wanted to secure with the annotation had beans.xml file with deltaspike interceptor in it (previously I was adding the file only to module with the security code itself, which was a problem).
Also I found out that I had to separate business logic service, from the SOAP endpoint declaration itself.
This custom EJB #Stateles (or any other) service can be #Inject-ed into the SOAP and security annotations (here #Support) will work on it.
In my opinion separation of endpoint declaration from business code is good design anyway, as we may have multiple interfaces invoking same business logic. (and it's easier to unit test etc.)

Bean Validation with groups using Spring in Service Layer

I am developing a service(not a web application) using Spring-3.1.0.GA. I want to use hibernate-validator along with Spring to validate my service inputs.
I have enabled the bean validation support with:
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>
I have annotated my service interface with #Validated and method parameters with #NotNull, #Size, #Valid etc and it is working fine.
But I have to validate my parameter, say Customer, based on validation group(s).
If I annotate method parameter with #Validated or #Validated(Group1.class) Spring is not performing any validation.
If I annotate with #Valid then validations are happening but with Default validation group(as expected).
I can't annotate #Validate(Group1.class) at interface level because various methods operate on various groups.
How can I perform service layer validations using Spring and hibernate-validator with groups support?
I have gone through Spring Source code and why the validation groups on method params are not being picked...As per the code it is picking the validation groups configuration only from #Validated on interface level, not on method level.
But I haven't gone through how it is working in SpringMVC context, I haven't checked yet.
Also in this process I came to know If you configure MethodValidationPostProcessor in child application context it is not picked up by Spring. I mean if you are using SpringMVC, MethodValidationPostProcessor will be registered only if you configure it in [servlet-name]-servlet.xml. If you configure in any child context configuration files that are picked by ContextLoaderListener Spring won't register MethodValidationPostProcessor. Also I am not sure it is only for MethodValidationPostProcessor or for any BeanPostProcessors also.
I get the following code working, I need to attach the #Validated at the method header and #Valid in the method parameters.
#Validated(Default.class)
public UserDto updateUser(#Valid UserDto userDto) {
In Spring 3.1.0+ you can use groups directly in #Valid annotation. E.g.:
#Valid(groups={Default.class, Group1.class})

Spring #Controller and custom MethodNameResolver

I have several controllers in a spring mvc application. They are regular beans that inherit from MultiActionController. They also have a custom MethodNameResolver that inspects a certain request parameter.
Now I am trying to use a new controller - a pojo with #Controller annotation. I am using #RequestMapping to resolve methods.
I am not sure if I understand this correctly, but as explained here in the spring reference, it is possible to use #RequestMapping with various filters (e.g. GET vs POST) without specifying a path, and then if a url applies to several methods then Spring falls back to InternalPathMethodNameResolver to decide which method to invoke.
How can I tell Spring to fall back to my custom MethodNameResolver? Is it enough to inject the resolver to my pojo controller?
(my controller doesn't inherit from any Spring specific class)
I guess you need to declare AnnotationMethodHandlerAdapter bean and set its methodNameResolver property.

Categories

Resources