I am trying to follow this to incorporate spring security in the framework
http://java.dzone.com/tips/pathway-acegi-spring-security-
i hope to make a basic form based authentication, so i think this would be a great pointer.
if i am using the spring security 3 libraries, would there be any different?
which file is the authentication-manager xml would suppose to be in?
Some time ago I've done a migration from Acegi Security to Spring Security, and I should say that it went pretty smooth, without any significant issues. So I assume that this libraries (in fact Spring Security is a latter version of Acegi) have not too much differences.
You could include you AuthenticationProvider implementation or any configuration related to a security any context configuration file. However, it's generally preferable to keep in separate Spring XML config file, which name is passed as a parameter along with name of main config file when you are creating ApplicationContext instance.
Suppose you have class MyAuthenticationProvider :
...
import org.springframework.security.providers.AuthenticationProvider;
...
public final class MyAuthenticationProvider implements AuthenticationProvider {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
...
}
}
This class is a regular Spring bean and therefore you can inject there any other bean you need, particularly DAO object which works with 'Users' table. Inside authenticate method you recieve partially initialized Authentication object. It's supposed to contain username and password. Here you could compare user credentials against database records.
also trying this one and succeed. this one is more complete with the included file
http://static.springsource.org/spring-security/site/petclinic-tutorial.html
Related
I am trying to build a token based authentication and authorization system using Apache CXF and Spring. I am completely following this fantastic post for doing this.
But I am stuck in a problem with my AuthorizationFilter at the very beginnig. I have seen many posts, apache JIRA, github comments about it, but could not yet found the workaround about this seemingly CXF issue.
#PreMatching
#Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
private ResourceInfo resourceInfo;
#Context
public void setResourceInfo(ResourceInfo resourceInfo) {
this.resourceInfo = resourceInfo;
}
#Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
Method method = resourceInfo.getResourceMethod();
In the above code, the injected resourceInfo is a proxy object, and it has none of the associated properties present. So, anything from that resourceInfo object is returning null, more specifically resourceInfo.getResourceMethod() is null, leading to NPE.
This is the JIRA post pertaining to this very issue, saying that:
In some circumstances (like using #ApplicationScoped annotation for example) the CDI runtime will create a proxy class for a particular bean. As the result, the CXF side is going to bind the particular provider metadata to this proxy instance. It looks logical and unambiguous.
However, the interesting things are happening when CXF will try to inject contextual proxies (#Context annotations) into the provider instance. The injections are successful but the target object for them will be the proxy instance (not the real instance behind it). Consequently, at runtime, when the proxy delegates the call to a backing instance, all contextual proxies are null in there (simply put, not set).
Referring to the recent discussions with Sergey Beryozkin, the best solution would be to delegate the #Context annotation to CDI framework (as such, relieving the CXF from doing the injection work). This proposal may need a support from the JAX-RS specification side.
Simpler (interim?) possible solution would be to complement the CDI injection with #Context injection (delegating this work to the CXF as it works right now for non-proxy beans and non-CDI deployments). This could be done by observing ProcessInjectionTarget events and supplying our own InjectionTarget (have working PoC for this approach).
Regarding constructor injection, it seems like CXF does not support passing the arguments to provider constructor (in case of CDI, w/o #Context annotation) so I it would be another (separate) issue to look at.
Can someone help me point out what is this simpler approach is all about:
Simpler (interim?) possible solution would be to complement the CDI injection with #Context injection (delegating this work to the CXF as it works right now for non-proxy beans and non-CDI deployments). This could be done by observing ProcessInjectionTarget events and supplying our own InjectionTarget (have working PoC for this approach)
Or is there any other way, where Spring Framework can inject the ResourceInfo object in a correct way?
I have registered the filters like this in my applicationContext.xml :
<jaxrs:server id="endpoints">
<jaxrs:providers>
<ref bean="authenticationFilter" />
<ref bean="authorizationFilter" />
</jaxrs:providers>
</jaxrs:server>
The problem is the #PreMatching annotation.
Global binding annotation that can be applied to a container request filter to indicate that such filter should be applied globally on all resources in the application before the actual resource matching occurs.
The key is highlighted part "before the actual resource matching occurs". So even before the resource is matched to the request, the filter is called. And if there is no resource matched yet, then it is impossible to get any information from the ResourceInfo. If you just remove the #PreMatching annotation, then the filter will be called after a matching resource is found, and you will be able to access all the info from the ResourceInfo.
We have properties defined in application.properties, is it appropriate to have the property pulled in a spring-boot #Configuration annotated class to be used for initializing the bean being created. Refer code snippet below
#Configuration
public class MyConfig {
#Value("${a.property.in.application.properties}")
public String aProperty;
#Bean
MyClass myClassInstance() {
return new MyClass(aProperty);
}
}
Simplest example would be creating a datasource instance with url, driver, username, password configured in the application.properties
Is it appropriate?
What could be the possible consequences of continuing to use in this manner?
I'm using this approach for different things like cors configurations. There are probably also disadvantages, but so far it has only had advantages for me. I think it's most times better to have config values outside of the code. That allows you, for example, to use different profiles (local/dev/int/prod). But I would recommend to encrypt things like passwords. I'm using Jasypt.
I want to use SpringSecurity4 in a CDI/EJB environment.
Is this possible? Can SpringSecurity can be used without using Spring?
What I want to do, is to use SpringSecurity with my EJB and CDI components.
Spring Security is basically a filter machine, filtering all the incoming requests. However, plenty of it's functionality is Spring-core dependent. It is possible to utilize Spring in a CDI application, but Spring's core is heavyweight and it's functionality is funny compared to CDI. That would be a downgrade and there would be no point in using CDI.
What you can do is to have a look at some Security projects for JEE world.
Apache DeltaSpike and it's Security module.
Keycloak - The absolute solution. Keycloak goes far, far beyond Spring security's functionality. It is an evolution of old PicketLink libraries developed by JBoss, but those are discontinued and merged into Keycloak instead. An example how simple usage of Keycloak is can be found here.
It is also not that hard to write own security interceptor using #WebFilter and #Inject :), there are several projects on GitHub:
https://github.com/rmpestano/security-interceptor
https://github.com/clairton/security
https://github.com/Rudin-Informatik/cdi-security
https://github.com/rafaelodon/my-security-context
I have no experience with these projects. However, I am always amazed how easily can Spring Security be replaced :)
I am using Spring Security with CDI but I can say it is not very healthy since Spring Security is based on spring and spring is messing with the CDI beans.
Here is what happened to me. I customized the AuthenticationProvider of spring security in order to authenticate users through my authentication server. When implementing this mechanism I used my predefined CDI beans by injecting them using (#Inject) annotation. At this point spring somehow intercepts the injection and creates its own bean, which means you cannot use any of the values you set to the CDI bean previously.
In order to solve this, I did some trick like this:
#Inject
private LoginController loginController;
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
//Here, the injected bean is empty, I am requesting my old bean from CDI and assign it back.
LoginController bm = (LoginController) CDI.current().select(LoginController.class).get();
loginController = bm;
I don't know if this is the answer you are looking for but i hope this helps...
Assume I have Spring MVC powered application with Spring security. I have:
UserBean class which provides CRUD operations on table User
UserController : controller which expose operation on User to http clients
UserLogin: Authentication provider from Spring security, which authenticates users.
How should I configure my application if:
I want simple XML configuration, with auto-discovering beans by annotations (<context:component-scan base-package="org.example"/>)
UserLogin and UserController needs UserBean to work
UserLogin and UserController use transaction annotations and aspect annotations
I see the following oportunities:
Create one common Spring XML configuration file, used both by DispatcherServlet and ContextLoaderListener
Disadvantage: nobody shows that solution in tutorial. All beans are duplicated (one instance in ContextLoaderListener context, second in DispatcherServlet). Duplication may cause some hard to track bugs. Duplication is not elegant
Create two Spring XML configuration files, one for ContextLoaderListener (main) and one for DispatcherServlet (controllers). UserBean is declared in first config and visible in second one
Disadvantage: to avoid duplication I have to add complex component scanning rules to both files (context:component-scan). <tx:annotation-driven and <aop:aspectj-autoproxy/> must be defined in both files. I will have still doubts which config file is appropiate when declaring new stuff.
Create two Spring XML configuration files and include third for common settings like <tx:annotation-driven
Disadvantage: I wanted simple solution...
Summary: I'm looking for good practice to configure application with Spring MVC + Spring Security AND security part is highly connected with business part. I was searching for good example but I always find case when security code is isolated from business code. But I need example when security and business share the code
Similar question: ContextLoaderListener or not?
I have two xml files for my configuration, no particular reason, that's just how it worked out.
These sample spring security projects provide good examples of lots of different types of configurations maybe you can find something that works for you:
https://github.com/spring-projects/spring-security/tree/master/samples
Hidden message in my question was: having two contexts is stupid.
Did someone already notice that?
Is there a way to have single application configuration?
Answers:
Yes. https://jira.springsource.org/browse/SPR-6903
Yes. https://github.com/michaldo/spring-single-context-demo
The best practice which applies to my case is described here: https://stackoverflow.com/a/14032213/2365727
Here are the questions resulted from reading the Spring Reference, please help.
(1) Do I ever need manual creation of ApplicationContext? Do I ever need second instance of AplicationContext?
(2) We have the following config instructions:
<context:annotation-config/>
<context:component-scan base-package=".."/>
<mvc:annotation-driven/>
Do these instructions duplicate theirselfs? In which cases yes, in which no?
(3) I am a bit stuck with all that ways Spring introduces to convert from string to object: PropertyEditor, Conversions, Formatting..
Here is a simple use case:
I have a Spring MVC controller that processes some POST request. That request is a result of filling some form. The form is a web representation of some entity.
So, given a the user submits a new Project form. In that form exist a date field and a manager's name field to be selected from the list of existing managers. The entered date should be converted to Date property of Project object, and manager's name - to Manager property, created or located by this name (i.e. I want to inject Manager into his Project). What should I use in this case? Property editors, formatters, something else?
(4) Generally, may I say that all the #interface classes that are found on classpath can be used by Spring as annotations?
In other words, how can I know which annotations can be used in my project? All that can be found in my classpath, or I need to register them somehow?
(5) I tried to use spring aop without aspectj.jar: just created an Aspect and addred XML definition for this aspect (without any annotations). As a result it throws "class not found Exception: org/aspectj/weaver/BCException".
So looks like I cannot use Spring AOP without aspectJ library?
(1) Do I ever need manual creation of ApplicationContext? Do I ever need second instance of AplicationContext?
Spring is typically usd in two environments - in web development and in desktop applications/standalone servers. In the former case the ApplicationContext is created automatically via ContextLoaderListener defined in web.xml or WebContextInitializer in Servlet 3.0 container.
In the latter case (standalone application) you are responsible for creating and destroying the application context.
(2) We have the following config instructions:
<context:component-scan base-package=".."/> provides all the functionality of <context:annotation-config/> plus (surprise!) component scanning. <mvc:annotation-driven/> is completely independent and it recognizes spring-mvc annotations like #Controller.
[...]The entered date should be converted to Date property of Project object[...]
Register custom editor within #Controller:
#Controller
public class FooController {
#InitBinder
public void binder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
public void setAsText(String value) {
try {
setValue(new SimpleDateFormat("yy-MM-dd HH:mm:ss").parse(value));
} catch (ParseException e) {
setValue(null);
}
}
});
}
}
[...]how can I know which annotations can be used in my project?[...]
I found this awesome annotations support sheet some time ago (I am not an author). It will tell you which annotations are enabled when.
All that can be found in my classpath
#Inject is enabled if it is found on the CLASSPATH, other annotations need to be enabled manually, see above.
So looks like I cannot use Spring AOP without aspectJ library?
You can use Spring without CGLIB if you only use interface proxies (i.e. you only apply aspects on classes implementing at least one interface). Otherwise you need CGLIB to dynamically create subclasses.