Quantcast
Channel: Spring Community Forums - Security
Viewing all 284 articles
Browse latest View live

LoginUrlAuthenticationEntryPoint 'commence' not called for the first time via AJAX

$
0
0
To handle session time out in case of AJAX requests, I have extended LoginUrlAuthenticationEntryPoint to handle it by returning HTTP status 401. But to my surprise the commence method is called when the first AJAX request is received on server. For the first time server still returns HTTP status 302 and then browser fetches login page but dies not redirect with status 200 OK.

Below is my AjaxAwareAuthenticationEntryPoint

Code:

public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    public AjaxAwareAuthenticationEntryPoint(String loginUrl) {
        super(loginUrl);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (isAjax(request)) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Please re-authenticate yourself");
        } else {
            super.commence(request, response, authException);
        }
    }

    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
}


And below is spring security configuration

Code:

    <http auto-config="true" use-expressions="true" entry-point-ref="authenticationEntryPoint">
        <intercept-url pattern="/index.jsp" access="permitAll" />
        <intercept-url pattern="/qualifiers/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/userpreference/**" access="hasRole('ROLE_USER')" />
        <form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-success-handler-ref="authSuccessBean" authentication-failure-handler-ref="authFailureBean"
            authentication-failure-url="/login.jsp?error=true" always-use-default-target="false" />
        <logout logout-success-url="/login.jsp" delete-cookies="JSESSIONID" />
        <remember-me />
        <session-management invalid-session-url="/login.jsp">
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>
    </http>
    <beans:bean id="authenticationEntryPoint" class="com.pcc.myapp.controller.auth.AjaxAwareAuthenticationEntryPoint">
        <beans:constructor-arg name="loginUrl" value="/login.jsp" />
    </beans:bean>
    <authentication-manager>
        <authentication-provider user-service-ref="userLoginService">
            <!-- <password-encoder hash="sha" /> -->
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="authFailureBean" class="com.pcc.myapp.controller.auth.AuthFailureHandler">
        <beans:property name="defaultFailureUrl" value="/login.jsp?error=true" />
    </beans:bean>

    <beans:bean id="authSuccessBean" class="com.pcc.myapp.controller.auth.AuthSuccessHandler">
        <beans:property name="defaultTargetUrl" value="/qualifiers/attributes.do" />
        <beans:property name="alwaysUseDefaultTargetUrl" value="true" />
    </beans:bean>


Below is my firebug AJAX calls log
screeshot.jpg
Attached Images

Custom expression method not found on my WebSecurityExpressionRoot subclass

$
0
0
Hi all,

I'm having a problem getting custom SpEL expressions to work in my @PreAuthorise annotations. I have written a custom method (code below) which I am trying to use as follows:

@PreAuthorise("isLocal()")
and
@PreAuthorise("local") // this should also work as the method honours bean naming semantics

However when Spring tries to find this method I get the following error:

Code:

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'local' cannot be found on object of type 'org.springframework.security.access.expression.method.MethodSecurityExpressionRoot'
Here's my code and configuration:

web.xml
Code:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      /WEB-INF/spring/spring-mvc.xml
      /WEB-INF/spring/security.xml
    </param-value>
  </context-param>

  <description>Spring Context Loader Listener</description>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
     
  <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        /WEB-INF/spring/spring-mvc.xml
      </param-value>
    </init-param> -->
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <!-- map all requests for /app/* to the dispatcher servlet -->
  <servlet-mapping>
      <servlet-name>springDispatcherServlet</servlet-name>
      <url-pattern>/app/*</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
      org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

security.xml

Code:

<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns:bean="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns="http://www.springframework.org/schema/security"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                      http://www.springframework.org/schema/security
                      http://www.springframework.org/schema/security/spring-security-3.1.xsd">
  <global-method-security pre-post-annotations="enabled" proxy-target-class="true"/>
  <http auto-config="true" use-expressions="true">
    <expression-handler ref="archiveWebSecurityExpressionHandler"/> <!-- Rename to annotation? -->
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
  </http>
</bean:beans>

AnnotationWebSecurityExpressionRoot.groovy
Code:

class AnnotationWebSecurityExpressionRoot extends WebSecurityExpressionRoot {

  AnnotationWebSecurityExpressionRoot(Authentication a, FilterInvocation fi) {
    super(a, fi)
  }
                                           
  boolean isLocal() {
    return true //trivial implementation so I can see whether this is working initially
  }
}

ArchiveWebSecurityExpressionHandler.groovy
Code:

@Component
class ArchiveWebSecurityExpressionHandler extends DefaultWebSecurityExpressionHandler {
 
  private final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl()
 
  @Override
  protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) {
    WebSecurityExpressionRoot root = new AnnotationWebSecurityExpressionRoot(authentication, fi)
    root.setPermissionEvaluator(permissionEvaluator)
    root.setTrustResolver(trustResolver)
    root.setRoleHierarchy(roleHierarchy)
    return root
  }
}

My project dependencies are as follows:
Code:

  groovy "org.codehaus.groovy:groovy-all:3.1.4.RELEASE"
  compile "org.springframework:spring-context:3.1.4.RELEASE"
  compile "org.springframework:spring-webmvc:3.1.4.RELEASE"
  compile "org.springframework:spring-web:3.1.4.RELEASE"
  compile "org.springframework.security:spring-security-config:3.1.4.RELEASE"
  compile "org.springframework.security:spring-security-core:3.1.4.RELEASE"
  compile "org.springframework.security:spring-security-web:3.1.4.RELEASE"
  compile "cglib:cglib-nodep:${depVersions.cglib}"

I have copied this example almost entirely verbatim from the Spring Security 3.1 book so I am suprised that I am seeing this error, the only real difference is that my classes are Groovy rather than Java (would that make a difference?). I have seen lots of posts in this forum around similar issues however many don't seem to have solutions so I'm hoping someone can help me find one here.

Many thanks,

Edd

clazz WebAuthenticationDetailsSource spring security 3.1.4

$
0
0
Hello everybody,
i'm a new user of spring framework and i tried to update some libraries in an existing project.
When i update spring sec from 3.0.5 to 3.1.4 i've a problem with :
1) PreAuthenticatedGrantedAuthoritiesWebAuthenticatio nDetails
Into the project i extend this class to set grantedAuthorities from setter and not from constructor, how can i do something like old version?
2) WebAuthenticationDetailsSource
There is not presence "clazz" method, so how can i specified a class ?

my spring-seurity is something like that :

<bean id="filter" class="org.springframework.security.web.authentica tion.preauth.RequestHeaderAuthenticationFilter">
<property name="principalRequestHeader" value="SM_USER" />
<property name="authenticationManager" ref="authenticationManager" />
<property name="authenticationDetailsSource" ref="webAuthenticationDetailsSource" />
</bean>

<bean id="webAuthenticationDetailsSource" class="org.springframework.security.web.authentica tion.WebAuthenticationDetailsSource">
<property name="clazz">
<value> com.auth.preauth.GrantedWebAuthenticationDetails
</value>
</property>
</bean>

Thanks a lot,

Regards.

No authentication providers

$
0
0
I need to protect Jersey REST Service
but i always getting message:

org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name '_authenticationManager': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException:
No authentication providers were found in the application context

i've read docs, tried do some variants, but it didn't help

Code:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
        xmlns:sec="http://www.springframework.org/schema/security"
        xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <http>
                <intercept-url pattern="/rest/**" access="ROLE_USER" />
                  <http-basic/>
    </http>

    <authentication-manager alias="_authentication-manager">
        <authentication-provider>
            <user-service id="userDetailsService">
                <user password="password" name="username" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

Spring authentication using multiple datasources

$
0
0
I would like to know how can i use multiple datasources to do authentication and authorization with Spring security.

Currently, I am using only one database to provide user authentication. I am on Spring version 3.1



<authentication-manager>
<authentication-provider>
<password-encoder hash="sha-256">
<salt-source user-property="username"/>
</password-encoder>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="
select username,password, enabled
from users where USERNAME=?"

authorities-by-username-query="
select username, authority from users where username =? "
/>
</authentication-provider>
</authentication-manager>


I would like to extend this functionality by providing a drop down of multiple datasources to the user at login page and authenticate user based on datasource selected.

Thanks.

RunAs Authentication Replacement for ACL?

$
0
0
I have been trying to determine how to grant object access to users via an invitation but Spring Security doesn't appear to have any sort of capability to handle this design.

What I want to do is to have one user issue an invitation to a second user. A second user may or may not be in the service at the time the invitation is created. In both cases (when a user already exists and when a user does not yet exist), an invitation object is created with the privileges selected by the inviter, the object the invitee has been invited to have access, the inviter SecUser id, and the invitee email address.

At this point no access privileges have been granted.

When an invitee logs into the service, the invitation is detected and the user is prompted to accept or reject the invitation. If the user chooses to accept the invitation and gain access to the object then the object ACL's should be extended to add ACE entries for the new user.

Now, here is the issue. I do not seem to be able to force Spring Security to allow a user to set ACL privileges for an object that the user has no admin privileges for regardless of any SpEL annotation I try on the service or controller (Grails environment). I have tried using @PreAuthorize("permitAll") and @PreAuthorize("#missionInvite.emailAddress==princi pal.email") to see if the annotation could force the ACL subsystem to stop checking for permission but I still get a "No such property: accessDenied for class:" error when my implementation of AclUtilService tries to call acl.insertAce().

I am thinking that I could use RunAs Authentication but I cannot find any examples implementing this temporary switch without resorting to annotations. The documentation seems to indicate that the RunAsUserTokens are statically created and not dynamic. Can someone point me to example code where RunAsTokens are created on the fly so that the service can change the current authentication object so that ACE's can be created for a user without the user have the needed privileges?

[OAuth 1.0] OAuthProviderTokenServices custom implementation

$
0
0
Hi, I'm triying to implement a custom OAuthProviderTokenServices in order to store tokens in a database.
All I got from the docs is:

Quote:

When creating your OAuthProviderTokenServices implementation, you may want to consider extending the RandomValueProviderTokenServices which creates tokens via random value and handles everything except for the persistence of the tokens. There is also an in-memory implementation of the OAuthProviderTokenServices that may be suitable [...]
which is fine, so I created a new custom class:

Code:

package experiments;

import java.util.concurrent.ConcurrentHashMap;
import org.springframework.security.oauth.provider.token.OAuthProviderTokenImpl;
import org.springframework.security.oauth.provider.token.RandomValueProviderTokenServices;

/**
 * Implementation of TokenServices that stores tokens in a database.
 *
 * @author Seether
 */
public class DatabaseProviderTokenServices extends RandomValueProviderTokenServices {

  protected final ConcurrentHashMap<String, OAuthProviderTokenImpl> tokenStore = new ConcurrentHashMap<String, OAuthProviderTokenImpl>();

  protected OAuthProviderTokenImpl readToken(String token) {
    return tokenStore.get(token);
  }

  protected void storeToken(String tokenValue, OAuthProviderTokenImpl token) {
    tokenStore.put(tokenValue, token);
  }

  protected OAuthProviderTokenImpl removeToken(String tokenValue) {
    return tokenStore.remove(tokenValue);
  }

}

which for now, as you can see, is identical to the InMemoryProviderTokenServices class.

My application uses the AccessConfirmationController from sparkl example, which is this:

Code:

package experiments;

import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.oauth.provider.ConsumerDetails;
import org.springframework.security.oauth.provider.ConsumerDetailsService;
import org.springframework.security.oauth.provider.token.OAuthProviderToken;
import org.springframework.security.oauth.provider.token.OAuthProviderTokenServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * Controller for retrieving the model for and displaying the confirmation page for access to a protected resource.
 *
 * @author Ryan Heaton
 */
@Controller
public class AccessConfirmationController {

        private OAuthProviderTokenServices tokenServices;
        private ConsumerDetailsService consumerDetailsService;

        @RequestMapping("/oauth/confirm_access")
        public ModelAndView getAccessConfirmation(HttpServletRequest request, HttpServletResponse response)
                        throws Exception {
                String token = request.getParameter("oauth_token");
                if (token == null) {
                        throw new IllegalArgumentException("A request token to authorize must be provided.");
                }

                OAuthProviderToken providerToken = tokenServices.getToken(token);
                ConsumerDetails consumer = consumerDetailsService
                                .loadConsumerByConsumerKey(providerToken.getConsumerKey());

                String callback = request.getParameter("oauth_callback");
                TreeMap<String, Object> model = new TreeMap<String, Object>();
                model.put("oauth_token", token);
                if (callback != null) {
                        model.put("oauth_callback", callback);
                }
                model.put("consumer", consumer);
                return new ModelAndView("access_confirmation", model);
        }

        public void setTokenServices(OAuthProviderTokenServices tokenServices) {
                this.tokenServices = tokenServices;
        }

        public void setConsumerDetailsService(ConsumerDetailsService consumerDetailsService) {
                this.consumerDetailsService = consumerDetailsService;
        }
}

Now the question is: how do I tell my application to use my tokenServices implementation rather than the default one (which right now I belive is InMemoryProviderTokenServices)?

I tried messing around with the controller, but the fews attempt all led me to java.lang.IllegalStateExceptions.

EDIT: just noticed I posted in the wrong forum... sorry. Can any mod please move it to /OAuth?

Spring Security RC1 Java Config not working for Hessian Remoting ?

$
0
0
Hi,

I'm trying to secure a server that uses Hessian Remoting with Spring Security and Java Configuration.

I've created a small isolated integration test to play with it:

https://bitbucket.org/walczak_it/pro...test?at=master

my configuration looks like this:

Code:

@Configuration
@ComponentScan("test.context")
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
public class HessianServerConfig extends WebSecurityConfigurerAdapter {
   
    @Autowired
    private SecurePingService securePingService;
       
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
            .withUser("someusr").password("somepass").roles("USER");
    }
   
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }
   
    @Bean
    public SecurePingService securePingService() {
        return new SecurePingServiceImpl();
    }
   
    @Bean(name="/SecurePingService")
    public HessianServiceExporter securePingServiceExporter() {
        HessianServiceExporter he = new HessianServiceExporter();
        he.setService(securePingService);
        he.setServiceInterface(SecurePingService.class);
        return he;
    }
}

my service looks like this:

Code:

public interface SecurePingService {

    @PreAuthorize("hasRole('ROLE_USER')")
    public String ping(String returnValue);
}

Code:

@Service
public class SecurePingServiceImpl implements SecurePingService {
   
    private static final Log LOG = LogFactory
            .getLog(SecurePingServiceImpl.class);

    @Override
    public String ping(String returnValue) {
        // this will throw AuthenticationCredentialsNotFoundException:
        // An Authentication object was not found in the SecurityContext
        //------
        String name = SecurityContextHolder.getContext()
            .getAuthentication().getName();
        //------
        LOG.info("name=" + name);
        return returnValue;
    }

}

I connect to the service like this

Code:

            HessianProxyFactoryBean proxyFactory = new HessianProxyFactoryBean();
            proxyFactory.setServiceInterface(SecurePingService.class);
            proxyFactory.setServiceUrl("http://localhost:8080/api/SecurePingService");
            proxyFactory.setUsername("somename");
            proxyFactory.setPassword("wrongpass");
            proxyFactory.setConnectTimeout(2000);
            proxyFactory.afterPropertiesSet();
            SecurePingService pingService
                    = (SecurePingService) proxyFactory.getObject();
            String ret = pingService.ping("pong");

As to my understanding the AuthenticationCredentialsNotFoundException I'm getting from inside my services implementation indicates that Spring Security did not authenticate using HTTP Basic nor did it execute method security mechanizes.



Please help: Em I doing something wrong or is it a bug ?



I'm using the latest milestones:

springVersion = 4.0.0.M2
springSecurityVersion = 3.2.0.RC1

and Java 8 b100

Session expiry directs to invalid-session-url even with RememberMe cookie

REST API Authentication with OpenID/OAuth

$
0
0
Has anyone got any advice on how to secure a stateless REST API with OpenID and Spring Security ? Not expecting a complete solution here, but even a few pointers would be appreciated.

Problem
=====

I have a secured a REST API using HTTP Basic using Spring Security and can then use the rest-shell to set the header before interacting with my API, but extending security to OpenID doesn't appear to be documented anywhere so I am wondering whether it is even supported.

The intention is to allow new user of a REST API to use their OpenID/OAuth credentials instead of adding site-specific user ids.

Research
======

There are a few tutorials on adding OpenID/OAuth to session based web sites, including the "Pro Spring Security" book, but for stateless REST APIs this obviously doesn't work as you need to send credentials on each API request.

Tutorial I found on adding OpenID support using Spring Security based websites (ie. not REST APIs)

a. http://krams915.blogspot.co.uk/2011/...n-with_13.html
b. http://harmonicdevelopment.tumblr.co...ng-social-part

Furthermore, the "REST in practice" book suggests that the process should be as follows, but I am unclear if this is possible to do with Spring Security:

1. Client requests a login with an Open ID to REST API, eg. /login/1234
2. REST App discovers openid provider, and shares secrets with OpenID provider to form association
3. Original client request is redirected to OpenID provider form
4. Client authenticates with OpenID provider
5. OpenID provider sends back credentials
6. Client presents credentials to REST API which then validates.

Thanks,

Ben

Does sample OpenID code need CSRF protection?

$
0
0
Reading about the new CSRF protection in 3.2.0.RC1 [1], does CSRF protection need to be added to the sample OpenID login code? Our new site is based off the sample XML site, so to make sure we're well protected, I'm curious if there's any code I should add.

Thanks,
Blair

[1] http://blog.springsource.org/2013/08...rf-protection/

Spring security, integrating Facebook authentication into restful basic auth

$
0
0
I am developing the server side for a mobile application as per below: - I'm using Spring MVC framework and I have already implemented BASIC AUTHENTICATION for restful requests (using JSON) as per code below.

Code:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
      http://www.springframework.org/schema/security
      http://www.springframework.org/schema/security/spring-security-3.1.xsd">



      <security:http  create-session="stateless" entry-point-    ref="restAuthenticationEntryPoint" use-expressions="true">

  <security:intercept-url pattern="/restful" access="hasRole('ROLE_USER')"/>
  <security:intercept-url pattern="/restful/*" access="hasRole('ROLE_USER')"/>
      <security:intercept-url pattern="/login" access="permitAll"/>
  <security:custom-filter ref="myFilter" after="BASIC_AUTH_FILTER"/>

    <!-- <security:logout />  -->
  </security:http>


<security:authentication-manager alias="authenticationManager">
    <security:authentication-provider
        user-service-ref="daoUserService">
        <security:password-encoder ref="passwordEncoder" />
    </security:authentication-provider>
</security:authentication-manager>




<bean id="restAuthenticationEntryPoint"  class="com.bp_gae.utils.RestAuthenticationEntryPoint">
 </bean>

<bean id="myFilter"
    class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationEntryPoint" ref="restAuthenticationEntryPoint" />
    </bean>


    <bean
    id="passwordEncoder"
    class="com.bp_gae.utils.AppPasswordEncoder" />

 <bean
    id="daoUserService"
    class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
    <property
        name="dataSource"
        ref="dataSource" />
    <property
        name="enableGroups"
        value="false" />
    <property
        name="enableAuthorities"
        value="true" />
    <property name="usersByUsernameQuery">
        <value>
            select username,password, 1
            from users
            where username = ?
        </value>
    </property>
    <property name="authoritiesByUsernameQuery">
        <value>
            select username,authority
            from users c,
            user_roles cp
            where c.user_id = cp.user_id
            and  c.username = ?
        </value>
    </property>
</bean>



</beans>

So the mobile client sends username, password in every request and a check in DB is done to determine whether he can have access to protected resources.There are no sessions created. The new requirement is to intagrate Facebook authentication. 1) The mobile user signs in and authenticates on client side and sends the authentication token to server. 2) The server should get user facebook details using that token (check whether this token is valid against facebook) using facebook app-id and app-secret from FB app I've created. I am using Spring Social for that purpose. 3) All protected resources are accessible after either basic or Facebook successful auth. 4) I already have a Users table in DB (username,email,password) and I'm thinking of creating another one with SocialUsers (email, token) and do some matching between them to link same users.

I am not sure on how to get both authentication methods working in my security.xml file. -Do I have to set up another filter for Social Auth? -In that case how can I use both filters? Any suggestions / sample code welcome!

How I Create dynamically ACL spring Security

$
0
0
hello

I want to add security for my webApp with this properties:
1.Secure url ,xhtmls and java Objects(domain and methods)
2.And possible to add users and role in Database
3.And secure object dynamically means :
The System admin can set and change Permissions of objects and url and ... for each user o each roles
In this mind ,The System admin can see objects and user and role in application ,can set permission access of abjects for each role or user and save in database and where user request for object ,App check object permission and return response.
For example :
This @PreAuthorize("hasRole('ROLE_USER')")has a permission for access to method
I want to set "hasRole('ROLE_USER')" to set dynamically and set from database


I try to use ACL spring security for this and I can do 1,2 but for 3 I don’t have any idea
I don’t have need to record security and I have need this permission (view(for url),read,update,delete,add(create) ) for any abject of this class
Plz help me

sessionRegistry.getAllPrincipals() return empty

$
0
0
hi everybody, the problem when I integrate spring mvc3.1 with spring security3.1 is I can not get all login users by

sessionRegistry.getAllPrincipals() ,because this method aways return empty.

anybody can give some help ? Thank you so much if you can give me your solutions .

the following are xml configurations

web.xml

Code:

        <listener>
                <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>
                    classpath:applicationContext.xml
                    classpath:applicationContext-security.xml
                </param-value>
        </context-param>

        <servlet>
                <servlet-name>springMVC</servlet-name>
                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                <init-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value>
                          classpath:springMVC-servlet.xml
                        </param-value>
                </init-param>
                <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
                <servlet-name>springMVC</servlet-name>
                <url-pattern>*.htm</url-pattern>
        </servlet-mapping>
       
      <filter>
          <filter-name>springSecurityFilterChain</filter-name>
          <filter-class>
            org.springframework.web.filter.DelegatingFilterProxy
          </filter-class>
      </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

spring-security.xml

Code:

<http pattern="/js/**" security="none"/>
    <http pattern="/images/**" security="none"/>
    <http pattern="/login.jsp*" security="none"/>
    <http pattern="/plugin/**" security="none"/>
    <http pattern="/css/**" security="none"/>
    <http use-expressions="true"  entry-point-ref="authenticationProcessingFilterEntryPoint">
        <logout delete-cookies="JSESSIONID"  invalidate-session="true" />

      <custom-filter  ref="concurrencyFilter" position="CONCURRENT_SESSION_FILTER"/>
              <custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER"  />
                <custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
            <session-management session-authentication-strategy-ref="sas" invalid-session-url="/login.jsp" />
    </http>
   
<beans:bean id="concurrencyFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter">
  <beans:property name="sessionRegistry" ref="sessionRegistry"  />
  <beans:property name="expiredUrl" value="/login.jsp" />
</beans:bean>
  <beans:bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
  <beans:constructor-arg name="sessionRegistry" ref="sessionRegistry" />
  <beans:property name="maximumSessions" value="1" />
  <beans:property name="exceptionIfMaximumExceeded" value="true" />
 </beans:bean>
   
   
    <beans:bean id="loginFilter"
                class="com.verysoft.baseframework.security.MyUsernamePasswordAuthenticationFilter">
       
                <beans:property name="filterProcessesUrl" value="/j_spring_security_check"></beans:property>
                <beans:property name="authenticationSuccessHandler" ref="loginLogAuthenticationSuccessHandler"></beans:property>
                <beans:property name="authenticationFailureHandler" ref="simpleUrlAuthenticationFailureHandler"></beans:property>
                <beans:property name="authenticationManager" ref="myAuthenticationManager"></beans:property>
                <beans:property name="userDao" ref="userDao"></beans:property>
        </beans:bean>
        <beans:bean id="loginLogAuthenticationSuccessHandler"
                class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
                <beans:property name="defaultTargetUrl" value="/admin/index.htm"></beans:property>
        </beans:bean>
        <beans:bean id="simpleUrlAuthenticationFailureHandler"
                class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
                <beans:property name="defaultFailureUrl" value="/login.jsp"></beans:property>
        </beans:bean>

    <beans:bean id="securityFilter" class="com.verysoft.baseframework.security.MySecurityFilter">
           
            <beans:property name="authenticationManager" ref="myAuthenticationManager" />
           
            <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
   
            <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
    </beans:bean>
 
    <authentication-manager alias="myAuthenticationManager">
        <authentication-provider user-service-ref="myUserDetailServiceImpl" >
        <password-encoder hash="sha"/>
        </authentication-provider>
    </authentication-manager>
   
    <beans:bean id="myAccessDecisionManager" class="com.verysoft.baseframework.security.MyAccessDecisionManager"></beans:bean>
        <beans:bean id="mySecurityMetadataSource" class="com.verysoft.baseframework.security.MySecurityMetadataSource">
                <beans:constructor-arg name="resourcesDao" ref="resourcesDao"></beans:constructor-arg>
        </beans:bean>
        <beans:bean id="myUserDetailServiceImpl" class="com.verysoft.baseframework.security.MyUserDetailServiceImpl">
                <beans:property name="userDao" ref="userDao"></beans:property>
        </beans:bean>
       
       
        <beans:bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
                <beans:property name="loginFormUrl" value="/login.jsp"></beans:property>
        </beans:bean>
 <beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />

UsernamePasswordAuthenticationFilter sending snippet as a response

$
0
0
Hi Friends,

I have implemented spring ldapSecuirty by using UsernamePasswordAuthenticationFilter with Extjs. I am able to authenticate successfully, but i am facing very strange problem i am not able write proper response back to Ajax request, i am writing response as response.getWriter().write("test"), but in ajax response i am seeing html code snippet. I googled a lot but i didn't find any solution . Please see my configurations

Response Message

//////////
<html>
<head>



<link rel="stylesheet" type="text/css" href="http://cdn.sencha.com/ext/gpl/4.2.0/resources/css/ext-all.css">
<link rel="stylesheet" type="text/css" href="app/resource/cams.css">
<script type="text/javascript" src="http://cdn.sencha.io/ext-4.2.0-gpl/ext-all.js"></script>
<script type="text/javascript" src="app/app.js"></script>
</head>
<body></body>
</html>

spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schem...-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">

<bean id="camsSecurityContextPlaceholderConfig"
class="org.springframework.beans.factory.config.Pr opertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:ldap.properties</value>
</list>
</property>
</bean>

<security:global-method-security />




<!-- This is where we configure Spring-Security -->

<security:http pattern="/index.jsp" security="none" />
<security:http pattern="/app/**" security="none" />


<security:http auto-config="false" use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint">
<security:intercept-url pattern="/**" access="permitAll" />
<security:custom-filter position="FORM_LOGIN_FILTER" ref="authenticationProcessingFilter"/>
</security:http>




<bean id="authenticationProcessingFilter" class=" com.moodys.cams.security.MyAuthenticationProcessin gFilter">
<property name="authenticationManager" ref="authenticationManager" />
</bean>


<!-- LDAP server details -->
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider
ref="ldapActiveDirectoryAuthProvider" />
</security:authentication-manager>



<bean id="authenticationProcessingFilterEntryPoint"
class="org.springframework.security.web.authentica tion.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="/index.jsp" />
<property name="forceHttps" value="false" />
</bean>

<bean id="camsUserDetailsContextMapper" class="com.moodys.cams.security.UserDetailsContext MapperImpl">
<property name="ldapGroupName" value="${ldap.group.name}"></property>
</bean>

<bean id="grantedAuthoritiesMapper" class="com.moodys.cams.security.ActiveDirectoryGra ntedAuthoritiesMapper"/>

<!-- This custom class is added because of the bug in Spring Security 3.1 -->
<bean id="ldapActiveDirectoryAuthProvider" class="com.moodys.cams.security.MoodysAdLdapAuthen ticationProvider">
<constructor-arg value="${ldap.domain.name}" />
<constructor-arg value="${ldap.server.url}" />
<property name="authoritiesMapper" ref="grantedAuthoritiesMapper" />
<property name="userDetailsContextMapper" ref="camsUserDetailsContextMapper" />
<property name="useAuthenticationRequestCredentials" value="true" />
<property name="convertSubErrorCodesToExceptions" value="true" />
</bean>
</beans>

UsernamePasswordAuthenticationFilter

public class MyAuthenticationProcessingFilter extends UsernamePasswordAuthenticationFilter {

private static Log logger = LogFactory.getLog(MyAuthenticationProcessingFilter .class);


@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
logger.info("Authenctication Success.....");
super.successfulAuthentication(request, response, chain, authResult);
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
Writer out = responseWrapper.getWriter();
out.write("{success:true }");
out.close();


}


@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException, ServletException {
logger.info("Authenctication Success.....");
super.unsuccessfulAuthentication(request, response, failed);
response.setContentType("application/json");
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);

Writer out = responseWrapper.getWriter();

out.write("{ success: false, errors: { reason: 'Login failed. Try again.' }}");
out.close();
}


}


Thanks in Advance.
Siva Kumar.

ACL denying user on collection objects

$
0
0
I want to integrate ACL to my Spring MVC application. It is based on this tutorial, it uses a database. I use service/dao layer model and my services/dao's are based on generic service/dao class. I successfully implemented a form authentication with 2 roles (ROLE_USER, ROLE_ADMIN). Also ACL on controller's method level works correctly (e.g. with @PreAuthorize annotation). But when I call service method getByPage() with anotation @PostFilter("hasPermission(filterObject, 'READ')"), it doesn't return any object.

Records related to objects are stored in ACL database tables.

Here is log from console.

Code:

DEBUG ExpressionBasedPostInvocationAdvice:37 - Applying PostFilter expression org.springframework.expression.spel.standard.SpelExpression@13a6ab0d
DEBUG DefaultMethodSecurityExpressionHandler:78 - Filtering with expression: hasPermission(filterObject, 'READ')
DEBUG DefaultMethodSecurityExpressionHandler:86 - Filtering collection with 5 elements
WARN  DenyAllPermissionEvaluator:25 - Denying user michal permission 'READ' on object com.app.cloud.hibernate.Customer@7a963c4c
WARN  DenyAllPermissionEvaluator:25 - Denying user michal permission 'READ' on object com.app.cloud.hibernate.Customer@1d50e074
WARN  DenyAllPermissionEvaluator:25 - Denying user michal permission 'READ' on object com.app.cloud.hibernate.Customer@28bfeeb5
WARN  DenyAllPermissionEvaluator:25 - Denying user michal permission 'READ' on object com.app.cloud.hibernate.Customer@50d0c1f9
WARN  DenyAllPermissionEvaluator:25 - Denying user michal permission 'READ' on object com.app.cloud.hibernate.Customer@396eebe2
DEBUG DefaultMethodSecurityExpressionHandler:102 - Retaining elements: []

When ACL works on controller, I note that my configuration will be correctly set. I absolutelly don't know where to find a problem. Is this issue of configuration, or placing of annotation in a code, or ...

Customer class haven't primare key with name 'id' but 'customerId'. Can it cause the problems?

Roled Based Access Control Model

$
0
0
Hi there,
I'm a fresher in building security problems.Now I am developing a project based on RBAC model,and I choose Spring Security 3 to implement it.
It's known that every role has its permissions in RBAC,and the way to judge whether a user has right to execute the operation is to obtain his roles first, and then fetch every permissions that the role has.I think permissions decide the right to operate the service layer(J2EE).
Spring Security provides annotations or Aspect to protect the service layer.But ther're all based on role-leveled such as "hasRole".It seems this cut the relationship between the role and the permission so that it's not flexiable to let the administer to distribute the permission.
What is the common way to solve this problem?Does Spring Security enable permission-protected implementation?
Many thanks!

How to access Spring Security port mappings from java

$
0
0
I have custom http/https port mappings in my Spring Security config.xml, typically we use different ports on different environments, 8080/8443 on localhost and pretty much anything else on QA or production.

e.g.
Code:

<http...>

    <port-mappings>
        <port-mapping http="8080" https="8443" />
        <port-mapping http="8081" https="8443" />
        <port-mapping http="9980" https="9443" />
        <port-mapping http="9880" https="9543" /> etc.
    </port-mappings>
</http>

Is there a way to access this configuration from java code?

How to change ObjectIdentity naming policy?

$
0
0
I want to integrate ACL to my Spring MVC application based on a database. Everything works fine but I would like to change org.springframework.security.acls.domain.ObjectIde ntityImpl policies for naming of getter. Default name of getter for identifier is getId(). But I have convention for class (e.g. Customer) - getIdCustomer(). Is there any way?

So it throws me following exception

Code:

org.springframework.security.acls.domain.IdentityUnavailableException: Could not extract identity from object Customer

Spring security and RSA secureID

$
0
0
Hello guys, I am looking for some information about how to integrate Spring security and RSA secureId.
Is it currently supported? could you point me some link to the documentation?
Thanks in advance
Viewing all 284 articles
Browse latest View live