EzDevInfo.com

spring-security interview questions

Top spring-security frequently asked interview questions

Spring Security 3 database authentication with Hibernate

I need to authenticate users from database, Spring Security documents don't tell how to authenticate with hibernate. Is that possible and how can I do that?


Source: (StackOverflow)

What's the difference between @Secured and @PreAuthorize in spring security 3?

It's not clear for me what is the difference in spring security between :

 @PreAuthorize("hasRole('ROLE_USER')")
 public void create(Contact contact)

And

@Secured("ROLE_USER")
public void create(Contact contact)

I understand PreAuthorize can work with spring el but in my sample, is there a real difference ?


Source: (StackOverflow)

Advertisements

JAAS for human beings

I am having a hard time understanding JAAS. It all seems more complicated than it should be (especially the Sun tutorials). I need a simple tutorial or example on how to implement security (authentication + authorization) in java application based on Struts + Spring + Hibernate with custom user repository. Can be implemented using ACEGI.


Source: (StackOverflow)

Unit testing with Spring Security

My company has been evaluating Spring MVC to determine if we should use it in one of our next projects. So far I love what I've seen, and right now I'm taking a look at the Spring Security module to determine if it's something we can/should use.

Our security requirements are pretty basic; a user just needs to be able to provide a username and password to be able to access certain parts of the site (such as to get info about their account); and there are a handful of pages on the site (FAQs, Support, etc) where an anonymous user should be given access.

In the prototype I've been creating, I have been storing a "LoginCredentials" object (which just contains username and password) in Session for an authenticated user; some of the controllers check to see if this object is in session to get a reference to the logged-in username, for example. I'm looking to replace this home-grown logic with Spring Security instead, which would have the nice benefit of removing any sort of "how do we track logged in users?" and "how do we authenticate users?" from my controller/business code.

It seems like Spring Security provides a (per-thread) "context" object to be able to access the username/principal info from anywhere in your app...

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

... which seems very un-Spring like as this object is a (global) singleton, in a way.

My question is this: if this is the standard way to access information about the authenticated user in Spring Security, what is the accepted way to inject an Authentication object into the SecurityContext so that it is available for my unit tests when the unit tests require an authenticated user?

Do I need to wire this up in the initialization method of each test case?

protected void setUp() throws Exception {
    ...
    SecurityContextHolder.getContext().setAuthentication(
		new UsernamePasswordAuthenticationToken(testUser.getLogin(), testUser.getPassword()));
    ...
}

This seems overly verbose. Is there an easier way?

The SecurityContextHolder object itself seems very un-Spring-like...


Source: (StackOverflow)

How to check "hasRole" in Java Code with Spring Security?

How to check user authority or permission in Java Code ? For example - I want to show or hide button for user depending on role. There are annotations like:

@PreAuthorize("hasRole('ROLE_USER')")

How to make it in Java code? Something like :

if(somethingHere.hasRole("ROLE_MANAGER")) {
   layout.addComponent(new Button("Edit users"));
}

Source: (StackOverflow)

What's the point of Spring MVC's DelegatingFilterProxy?

I see this in my Spring MVC app's web.xml:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

I'm trying to figure out why it's there and whether it's actually needed.

I found this explanation in the Spring docs but it doesn't help me make sense of it:

It seems to suggest that this component is the "glue" between the servlets defined in web.xml and the components defined in the Spring applicationContext.xml.

7.1 DelegatingFilterProxy

When using servlet filters, you obviously need to declare them in your web.xml, or they will be ignored by the servlet container. In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring's rich dependency-injection facilities and lifecycle interfaces. Spring's DelegatingFilterProxy provides the link between web.xml and the application context.

When using DelegatingFilterProxy, you will see something like this in the web.xml file:

<filter>
  <filter-name>myFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>myFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Notice that the filter is actually a DelegatingFilterProxy, and not the class that will actually implement the logic of the filter. What DelegatingFilterProxy does is delegate the Filter's methods through to a bean which is obtained from the Spring application context. This enables the bean to benefit from the Spring web application context lifecycle support and configuration flexibility. The bean must implement javax.servlet.Filter and it must have the same name as that in the filter-name element. Read the Javadoc for DelegatingFilterProxy for more information

So, if I take this out of my web.xml, what will happen? My servlets won't be able to communicate with the Spring container?**


Source: (StackOverflow)

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

Any ideas what could be the cause of this?

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

org.springframework.web.context.ContextLoader initWebApplicationContext: Context initialization failed
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]
Offending resource: ServletContext resource [/WEB-INF/applicationContext.xml]

This is my applicationContext.xml:

<?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: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.0.xsd">
...
</beans:beans>

In my pom.xml I have:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>      
    <version>3.0.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-openid</artifactId>
    <version>3.0.1.RELEASE</version>
</dependency>

Source: (StackOverflow)

How to get active user's UserDetails

In my controllers, when I need the active (logged in) user, I am doing the following to get my UserDetails implementation:

User activeUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.debug(activeUser.getSomeCustomField());

It works fine, but I would think Spring could make life easier in a case like this. Is there a way to have the UserDetails autowired into either the controller or the method?

For example, something like:

public ModelAndView someRequestHandler(Principal principal) { ... }

But instead of getting the UsernamePasswordAuthenticationToken, I get a UserDetails instead?

I'm looking for an elegant solution. Any ideas?


Source: (StackOverflow)

RESTful Authentication via Spring

Problem:
We have a Spring MVC-based RESTful API which contains sensitive information. The API should be secured, however sending the user's credentials (user/pass combo) with each request is not desirable. Per REST guidelines (and internal business requirements), the server must remain stateless. The API will be consumed by another server in a mashup-style approach.

Requirements:

  • Client makes a request to .../authenticate (unprotected URL) with credentials; server returns a secure token which contains enough information for the server to validate future requests and remain stateless. This would likely consist of the same information as Spring Security's Remember-Me Token.

  • Client makes subsequent requests to various (protected) URLs, appending the previously obtained token as a query parameter (or, less desirably, an HTTP request header).

  • Client cannot be expected to store cookies.

  • Since we use Spring already, the solution should make use of Spring Security.

We've been banging our heads against the wall trying to make this work, so hopefully someone out there has already solved this problem.

Given the above scenario, how might you solve this particular need?


Source: (StackOverflow)

Spring Security on Wildfly / Undertow: error executing the filter chain

I'm working in order to integrate Spring Security SAML Extension with Spring Boot.

I developed a complete sample application, all the source code is published on GitHub:

By running the WebApp as Spring Boot application (through Spring Tool Set, by using an embedded Application Server), it works fine. Unfortunately, the auth process doesn't work on Undertow/WildFly (and I must use it as production AS).

By logging, I can see that the IdP performs the AuthN process and the instructions of my custom UserDetails implementation are correctly executed. Despite that Spring doesn't set up the privileges for the current user.

@Component
public class SAMLUserDetailsServiceImpl implements SAMLUserDetailsService {

    // Logger
    private static final Logger LOG = LoggerFactory.getLogger(SAMLUserDetailsServiceImpl.class);

    @Override
    public Object loadUserBySAML(SAMLCredential credential)
            throws UsernameNotFoundException, SSOUserAccountNotExistsException {
        String userID = credential.getNameID().getValue();
        if (userID.compareTo("jdoe@samplemail.com") != 0) {     // We're simulating the data access.
            LOG.warn("SSO User Account not found into the system");
            throw new SSOUserAccountNotExistsException("SSO User Account not found into the system", userID);
        }
        LOG.info(userID + " is logged in");
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
        authorities.add(authority);
        ExtUser userDetails = new ExtUser(userID, "password", true, true, true,
                true, authorities, "John", "Doe");
        return userDetails;
    }
}

By debugging, I checked that the problem starts from the FilterChainProxy class. When I run the webapp on WildFly, I can see that the attribute FILTER_APPLIED of ServletRequest is null, thus Spring clears the SecurityContextHolder.

private final static String FILTER_APPLIED = FilterChainProxy.class.getName().concat(".APPLIED");

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
    if (clearContext) {
        try {
            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
            doFilterInternal(request, response, chain);
        } finally {
            SecurityContextHolder.clearContext();
            request.removeAttribute(FILTER_APPLIED);
        }
    } else {
        doFilterInternal(request, response, chain);
    }
}

On VMware vFabric tc Sever and Tomcat that doesn't happen. Is there a way to resolve this issue?


Source: (StackOverflow)

Spring Security with roles and permissions

I'm trying to set up role-based Security with permissions. I'm trying to do this together with Spring-Security.

I don't want to set up ACL as it seems it's an overkill for my requirements.

I just want to have simple permissions and roles as described in this article. Unfortunately the article does not describe how to implement the given solution.

Has someone already tried this and can point me in the right direction? Maybe there is another blog entry that describes the implementation?

Thank you very much.


Source: (StackOverflow)

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I'm using the code snippet given below . Is this the accepted way?

I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO. Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?

  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView showResults(final HttpServletRequest request...) {
    final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
    ...
  }

Source: (StackOverflow)

how to conditionally show jsp content to logged in users with Spring security

I want to show content to any user that is logged in and to hide if they are not logged in. I'm using jsp's and spring security.

Obviously a home grown solution is easily done. But what's the cleanest standard way of achieving this?

Spring security tags don't seem to have nice way that will allow for the addition of new roles in the future.


Source: (StackOverflow)

Shiro vs. SpringSecurity [closed]

I have currently evaluating Java based security frameworks, I am a Spring 3.0 user so it seemed that SpringSecurity would be the right Choice, but Spring security seems to suffer from excessive complexity, it certainly does not seem like it is making security easier to implement, Shiro seems to be much more coherent and easier to understand. I am looking for lists of pros and cons between these two frameworks.


Source: (StackOverflow)

What is the meaning of Subject vs. User vs. Principal in a Security Context?

In the context of security frameworks a few terms commonly occur Subject, User, Principal I have not been able to find a clear definition of the difference between Subject and User, Subject and Principal, User and Principal. So what exactly do these terms mean and why are these distinctions of Subject and Principal needed?


Source: (StackOverflow)