diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java index 3d0b551dcc..c0c9f00959 100644 --- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java +++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java @@ -28,25 +28,43 @@ import org.junit.Test; import org.w3c.dom.Document; public class ApacheFOPHeroldTest { - private String[] inputUrls = { "http://inprogress.baeldung.com/?p=1430","http://www.baeldung.com/spring-events" }; + private String[] inputUrls = {// @formatter:off + // "http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/", + // "http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/", + "http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/", + // "http://www.baeldung.com/spring-security-basic-authentication", + // "http://www.baeldung.com/spring-security-digest-authentication", + //"http://www.baeldung.com/2011/11/20/basic-and-digest-authentication-for-a-restful-service-with-spring-security-3-1/", + //"http://www.baeldung.com/spring-httpmessageconverter-rest", + //"http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/", + //"http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/", + //"http://www.baeldung.com/2013/01/11/etags-for-rest-with-spring/", + //"http://www.baeldung.com/2012/01/18/rest-pagination-in-spring/", + //"http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/", + //"http://www.baeldung.com/rest-versioning", + //"http://www.baeldung.com/2013/01/18/testing-rest-with-multiple-mime-types/" + }; // @formatter:on + private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl"; private String output_prefix = "src/test/resources/"; private String xmlFile = "src/test/resources/input.xml"; @Test - public void whenTransformFromHeroldToPDF_thenCorrect() throws Exception{ - int len = inputUrls.length; - for (int i = 0; i < len; i++) { - fromHTMLTOXMLUsingHerold(inputUrls[i]); - final Document fo = fromXMLFileToFO(); - fromFODocumentToPDF(fo, output_prefix + i + ".pdf"); - } + public void whenTransformFromHeroldToPDF_thenCorrect() throws Exception { + final int len = inputUrls.length; + for (int i = 0; i < len; i++) { + fromHTMLTOXMLUsingHerold(inputUrls[i]); + final Document fo = fromXMLFileToFO(); + fromFODocumentToPDF(fo, output_prefix + i + ".pdf"); + } } - private void fromHTMLTOXMLUsingHerold(String input) throws Exception { + // UTIL + + private void fromHTMLTOXMLUsingHerold(final String input) throws Exception { Script script; - TrafoScriptManager mgr = new TrafoScriptManager(); - File profileFile = new File("src/test/resources/default.her"); + final TrafoScriptManager mgr = new TrafoScriptManager(); + final File profileFile = new File("src/test/resources/default.her"); script = mgr.parseScript(profileFile); final DocBookTransformer transformer = new DocBookTransformer(); transformer.setScript(script); @@ -83,10 +101,9 @@ public class ApacheFOPHeroldTest { return transformer; } - private InputStream getInputStream(String input) throws IOException { - URL url = new URL(input); + private InputStream getInputStream(final String input) throws IOException { + final URL url = new URL(input); return url.openStream(); } } - diff --git a/apache-fop/src/test/resources/input.xml b/apache-fop/src/test/resources/input.xml index 4760c7968f..1a71e1aaec 100644 --- a/apache-fop/src/test/resources/input.xml +++ b/apache-fop/src/test/resources/input.xml @@ -1,33 +1,53 @@
- Registration – Activate a New Account by Email | Technical Articles + Spring Security for a REST API - 1. Overview This article continues our ongoing Registration with Spring Security series by finishing the missing piece of the registration process - verifying + How to Secure a REST API with Spring Security 3 - the XML Configuration, the web.xml, the HTTP status codes for authentication, etc. - - - + + + + + + + + + + + + + + + + + + -
- <link linkend="navigation">Navigation</link> - - Technical Articles - Home - - - Home - - - - - - - - - - - Return to Content - - - - - Registration – Activate a New Account by Email - By - Elena - on - October 23, 2014 - in - Spring Security - + + Contents + + + Table of Contents + + + 1. Overview + + + 2. Spring Security in the web.xml + + + 3. The Security Configuration + + + 4. Maven and other trouble + + + 5. Conclusion + + + If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! + + +
+ <emphasis role="bold">I usually post about Security on Google+ - you can follow me there: </emphasis> +
- <emphasis role="bold">1. Overview</emphasis> - This article continues our ongoing Registration with Spring Security series by finishing the missing piece of the registration process – verifying the email to confirm the user registration. - The registration confirmation mechanism forces the user to respond to a “Confirm Registration” email sent after successful registration to verify his email address and activate his account. The user does this by clicking a unique account activation link sent to him as part of the email message. - Following this logic, a newly registered user will not be able to log in until email/registration verification is completed. -
-
- <emphasis role="bold">2. A Verification Token</emphasis> - We will make use of a simple verification token as the key artifact through which a user is verified. -
- <emphasis role="bold">2.1. Adding a VerificationToken Entity to Our Model</emphasis> - The VerificationToken entity must meet the following criteria: - - There will be one VerificationToken associated to a User. So, we need a one-to-one unidirectional association between the VerificationToken and the User. - - - It will be created after the user registration data is persisted. - - - It will expire in 24 hours following initial registration. - - - Its value should be unique and randomly generated. - - - Requirements 2 and 3 are part of the registration logic. The other two are implemented in a simple VerificationToken entity like the one in Example 2.1.: - Example 2.1. - @Entity -@Table -public class VerificationToken { - private static final int EXPIRATION = 60 * 24; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Column(name = "token") - private String token; - - @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER) - @JoinColumn(name = "user_id") - private User user; - - @Column(name = "expiry_date") - private Date expiryDate; - - public VerificationToken() { - super(); - } - public VerificationToken(String token, User user) { - super(); - this.token = token; - this.user = user; - this.expiryDate = calculateExpiryDate(EXPIRATION); - this.verified = false; - } - private Date calculateExpiryDate(int expiryTimeInMinutes) { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Timestamp(cal.getTime().getTime())); - cal.add(Calendar.MINUTE, expiryTimeInMinutes); - return new Date(cal.getTime().getTime()); - } - - // standard getters and setters -} -
-
- <emphasis role="bold">2.2. Add an Enabled Flag to the User Entity</emphasis> - We will set the value of this flag depending on the result of the registration confirmation use case. Lets jus add the following field to our User entity for now: - @Column(name = "enabled") -private boolean enabled; -
-
-
- <emphasis role="bold">3. The Account Registration Phase</emphasis> - Lets add two additional pieces of business logic to the user registration use case: - - Generating a VerificationToken for the user and persisting it. - - - Sending the account confirmation email message which includes a confirmation link with the VerificationToken’s valueas a parameter. - - -
- <emphasis role="bold">3.1. Using Spring Event Handling to Create the Token and Send the Verification Email</emphasis> - These two additional pieces of logic should not be performed by the controller directly because they are “collateral” back-end tasks. The controller will publish a Spring ApplicationEvent to trigger the execution of these tasks. This is as simple as injecting an ApplicationEventPublisher in the controller, and then using it to publish the registration completion. Example 3.1. shows this simple logic: - Example 3.1. - @Autowired -ApplicationEventPublisher -@RequestMapping(value = "/user/registration", method = RequestMethod.POST) -public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserDto accountDto, - BindingResult result, WebRequest request, Errors errors) { - User registered = new User(); - String appUrl = request.getContextPath(); - if (result.hasErrors()) { - return new ModelAndView("registration", "user", accountDto); - } - registered = createUserAccount(accountDto); - if (registered == null) { - result.rejectValue("email", "message.regError"); - } - eventPublisher.publishEvent(new OnRegistrationCompleteEvent(registered, - request.getLocale(), appUrl)); - return new ModelAndView("successRegister", "user", accountDto); -} -
-
- <emphasis role="bold">3.2. Spring Event Handler Implementation</emphasis> - The controller is using an ApplicationEventPublisher to start the RegistrationListener that will handle the verification token creation and confirmation email sending. So it needs to have access to the implementation of the following interfaces: - - An AplicationEvent representing the completion of the user registration. - - - An ApplicationListener bean which will listen to the published event and proceed to do all the work. - - - The beans we will create are the OnRegistrationCompleteEvent , and the RegistrationListener shown Examples 3.2.1 – 3.2.2. - Example 3.2.1. – The OnRegistrationCompleteEvent - @SuppressWarnings("serial") -public class OnRegistrationCompleteEvent extends ApplicationEvent { - private final String appUrl; - private final Locale locale; - private final User user; - - public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) { - super(user); - this.user = user; - this.locale = locale; - this.appUrl = appUrl; - } - - // standard getters and setters -} - Example 3.2.2. - The RegistrationListener Responds to the OnRegistrationCompleteEvent - @Component -public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> { - @Autowired - private IUserService service; - - @Autowired - private MessageSource messages; - - @Autowired - private JavaMailSender mailSender; - - @Override - public void onApplicationEvent(OnRegistrationCompleteEvent event) { - this.confirmRegistration(event); - } - - private void confirmRegistration(OnRegistrationCompleteEvent event) { - User user = event.getUser(); - String token = UUID.randomUUID().toString(); - service.addVerificationToken(user, token); - String recipientAddress = user.getEmail(); - String subject = "Registration Confirmation"; - String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token; - String message = messages.getMessage("message.regSucc", null, event.getLocale()); - SimpleMailMessage email = new SimpleMailMessage(); - email.setTo(recipientAddress); - email.setSubject(subject); - email.setText(message + " \r\n" + "http://localhost:8080" + confirmationUrl); - mailSender.send(email); - } -} - Here, the confirmRegistration method will receive the OnRegistrationCompleteEvent, extract all the necessary User information from it, create the verification token, persist it, and then send it as a parameter in the “Confirm Registration” link sent to the user. -
-
- <emphasis role="bold">3.3. Processing the Verification Token Parameter</emphasis> - When the user receives the “Confirm Registration” email, he will click on the attached link and fire a GET request. The controller will extract the value of the token parameter in the GET request and will use it to verify the user. Lets see this logic in Example 3.3.1. - Example 3.3.1. – RegistrationController Processing the Registration Confirmation Link - private IUserService service; - -@Autowired -public RegistrationController(IUserService service){ - this.service = service -} -@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET) -public String confirmRegistration(WebRequest request, Model model, - @RequestParam("token") String token) { - VerificationToken verificationToken = service.getVerificationToken(token); - if (verificationToken == null) { - model.addAttribute("message", messages.getMessage("auth.message.invalidToken", - null, request.getLocale())); - return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage(); - } - User user = verificationToken.getUser(); - Calendar cal = Calendar.getInstance(); - if (user == null) { - model.addAttribute("message", messages.getMessage("auth.message.invalidUser", - null, request.getLocale())); - return "redirect:/badUser.html?lang=" + request.getLocale().getLanguage(); - } - if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) { - user.setEnabled(false); - } else { - user.setEnabled(true); - } - service.saveRegisteredUser(user); - return "redirect:/login.html?lang=" + request.getLocale().getLanguage(); -} - Notice that if there is no user associated with the VerificationToken or if the VerificationToken does not exist, the controller will return a badUser.html page with the corresponding error message (See Example 3.3.2.). - Example 3.3.2. – The badUser.html - <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> -<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> -<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> -<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> -<fmt:setBundle basename="messages" /> -<%@ page session="true"%> -<html> -<head> - <link href="<c:url value="/resources/bootstrap.css" />" rel="stylesheet"> - <title>Expired</title> -</head> -<body> - <h1>${message}</h1> - <br> - <a href="<c:url value="/user/registration" />"> - <spring:message code="label.form.loginSignUp"></spring:message> - </a> -</body> -</html> - If the token and user exist, the controller then proceeds to set the User‘s enabled field after checking if the VerificationToken has expired. -
-
-
- <emphasis role="bold">4. Adding Account Activation Checking to the Login Process</emphasis> - We need to add the following verification logic to MyUserDetailsService’s loadUserByUsername method: + <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - Make sure that the user is enabled before letting him log in. + 1. Overview + + + 2. Introducing Spring Security in the web.xml + + + 3. The Security Configuration + + +     3.1. The basics + + +     3.2. The Entry Point + + +     3.3. The Login + + +     3.4. Authentication should return 200 instead of 301 + + +     3.5. Failed Authentication should return 401 instead of 302 + + +     3.6. The Authentication Manager and Provider + + +     3.7. Finally – Authentication against the running REST Service + + + 4. Maven and other trouble + + + 5. Conclusion - Example 4.1. shows the simple isEnabled() check. - Example 4.1. – Checking the VerificationToken in MyUserDetailsService - private UserRepository userRepository; -@Autowired -private IUserService service; -@Autowired -private MessageSource messages; - -@Autowired -public MyUserDetailsService(UserRepository repository) { - this.userRepository = repository; -} - -public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { - boolean enabled = true; - boolean accountNonExpired = true; - boolean credentialsNonExpired = true; - boolean accountNonLocked = true; - try { - User user = userRepository.findByEmail(email); - if (user == null) { - return new org.springframework.security.core.userdetails.User(" ", " ", enabled, - true, true, true, getAuthorities(new Integer(1))); - } - if (!user.isEnabled()) { - accountNonExpired = false; - service.deleteUser(user); - return new org.springframework.security.core.userdetails.User(" ", " ", enabled, - accountNonExpired, true, true, getAuthorities(new Integer(1))); - } - return new org.springframework.security.core.userdetails.User(user.getEmail(), - user.getPassword().toLowerCase(), - enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, - getAuthorities(user.getRole().getRole())); - } catch (Exception e) { - throw new RuntimeException(e); - } -} - Notice that if the user is not enabled, the account is deleted and the method returns an org.springframework.security.core.userdetails.User with the accountNonExpired flag set to false. This will trigger a SPRING_SECURITY_LAST_EXCEPTION in the login process. This exception’s String value is: ‘User Account Has Expired‘. - Now, we need to modify our login.html page to show this and any other exception messages resulting from en email verification error. The error checking code we added to login.html is shown in Example 4.2.: - Example 4.2. – Adding Account Activation Error Checking to login.html - <c:if test="${param.error != null}"> - <c:choose> - <c:when test="${SPRING_SECURITY_LAST_EXCEPTION.message == 'User is disabled'}"> - <div class="alert alert-error"> - <spring:message code="auth.message.disabled"></spring:message> - </div> - </c:when> - <c:when test="${SPRING_SECURITY_LAST_EXCEPTION.message == 'User account has expired'}"> - <div class="alert alert-error"> - <spring:message code="auth.message.expired"></spring:message> - </div> - </c:when> - <c:otherwise> - <div class="alert alert-error"> - <spring:message code="message.badCredentials"></spring:message> - </div> - </c:otherwise> - </c:choose> -</c:if>
-
- 5. Adapting the Persistence Layer - We need to modify the API of the persistence layer by: - - Creating a VerificationTokenRepository. For User and VerificationToken access. - - - Adding methods to the IUserInterface and its implementation for new CRUD operations needed. - - - Examples 5.1 – 5.3. show the new interfaces and implementation: - Example 5.1. – The VerificationTokenRepository - public interface VerificationTokenRepository extends JpaRepository<VerificationToken, Long> { - - VerificationToken findByToken(String token); - - VerificationToken findByUser(User user); -} - Example 5.2. – The IUserService Interface - public interface IUserService { - - User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; - - User getUser(String verificationToken); - - void saveRegisteredUser(User user); - - void addVerificationToken(User user, String token); - - VerificationToken getVerificationToken(String VerificationToken); - - void deleteUser(User user); -} - Example 5.3. The UserService - @Service -public class UserService implements IUserService { - @Autowired - private UserRepository repository; - - @Autowired - private VerificationTokenRepository tokenRepository; - - @Transactional - @Override - public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException { - if (emailExist(accountDto.getEmail())) { - throw new EmailExistsException("There is an account with that email adress: " + - accountDto.getEmail()); - } - User user = new User(); - user.setFirstName(accountDto.getFirstName()); - user.setLastName(accountDto.getLastName()); - user.setPassword(accountDto.getPassword()); - user.setEmail(accountDto.getEmail()); - user.setRole(new Role(Integer.valueOf(1), user)); - return repository.save(user); - } - - private boolean emailExist(String email) { - User user = repository.findByEmail(email); - if (user != null) { - return true; - } - return false; - } - - @Override - public User getUser(String verificationToken) { - User user = tokenRepository.findByToken(verificationToken).getUser(); - return user; - } - - @Override - public VerificationToken getVerificationToken(String VerificationToken) { - return tokenRepository.findByToken(VerificationToken); - } - - @Transactional - @Override - public void saveRegisteredUser(User user) { - repository.save(user); - } - - @Transactional - @Override - public void deleteUser(User user) { - repository.delete(user); - } - - @Transactional - @Override - public void addVerificationToken(User user, String token) { - VerificationToken myToken = new VerificationToken(token, user); - tokenRepository.save(myToken); - } -} +
+ <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> + This tutorial shows how to Secure a REST Service using Spring and Spring Security 3.1 with Java based configuration. The article will focus on how to set up the Security Configuration specifically for the REST API using a Login and Cookie approach.
-
- 6. Conclusion - We have expanded our Spring registration process to include an email based account activation procedure. The account activation logic requires sending a verification token to the user via email, so that he can send it back to the controller to verify his identity. A Spring event handler layer takes care of the back-end work needed to send the confirmation email after the controller persists a registered. - - - +
+ <anchor xml:id="dbdoclet.2_Spring_Security_in_the_webxml"/><emphasis role="bold">2. Spring Security in the web.xml</emphasis> + The architecture of Spring Security is based entirely on Servlet Filters and, as such, comes before Spring MVC in regards to the processing of HTTP requests. Keeping this in mind, to begin with, a filter needs to be declared in the web.xml of the application: + <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> + The filter must necessarily be named ‘springSecurityFilterChain’  to match the default bean created by Spring Security in the container. + Note that the defined filter is not the actual class implementing the security logic but a DelegatingFilterProxy with the purpose of delegating the Filter’s methods to an internal bean. This is done so that the target bean can still benefit from the Spring context lifecycle and flexibility. + The URL pattern used to configure the Filter is /* even though the entire web service is mapped to /api/* so that the security configuration has the option to secure other possible mappings as well, if required. +
+
+ <anchor xml:id="dbdoclet.3_The_Security_Configuration"/><emphasis role="bold">3. The Security Configuration</emphasis> + <?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.2.xsd + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> + + <http entry-point-ref="restAuthenticationEntryPoint"> + <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN"/> + + <form-login + authentication-success-handler-ref="mySuccessHandler" + authentication-failure-handler-ref="myFailureHandler" + /> + + <logout /> + </http> + + <beans:bean id="mySuccessHandler" + class="org.rest.security.MySavedRequestAwareAuthenticationSuccessHandler"/> + <beans:bean id="myFailureHandler" + class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/> + + <authentication-manager alias="authenticationManager"> + <authentication-provider> + <user-service> + <user name="temporary" password="temporary" authorities="ROLE_ADMIN"/> + <user name="user" password="user" authorities="ROLE_USER"/> + </user-service> + </authentication-provider> + </authentication-manager> + +</beans:beans> + Most of the configuration is done using the security namespace – for this to be enabled, the schema locations must be defined and pointed to the correct 3.1 or 3.2 XSD versions. The namespace is designed so that it expresses the common uses of Spring Security while still providing hooks raw beans to accommodate more advanced scenarios. >> Signup for my upcoming Video Course on Building a REST API with Spring 4 +
+ <emphasis role="bold">3.1. The <http> element</emphasis> + The <http> element is the main container element for HTTP security configuration. In the current implementation, it only secured a single mapping: /api/admin/**. Note that the mapping is relative to the root context of the web application, not to the rest Servlet; this is because the entire security configuration lives in the root Spring context and not in the child context of the Servlet. +
+
+ <emphasis role="bold">3.2. The Entry Point</emphasis> + In a standard web application, the authentication process may be automatically triggered when the client tries to access a secured resource without being authenticated – this is usually done by redirecting to a login page so that the user can enter credentials. However, for a REST Web Service this behavior doesn’t make much sense – Authentication should only be done by a request to the correct URI and all other requests should simply fail with a 401 UNAUTHORIZED status code if the user is not authenticated. + Spring Security handles this automatic triggering of the authentication process with the concept of an Entry Point – this is a required part of the configuration, and can be injected via the entry-point-ref attribute of the <http> element. Keeping in mind that this functionality doesn’t make sense in the context of the REST Service, the new custom entry point is defined to simply return 401 whenever it is triggered: + @Component( "restAuthenticationEntryPoint" ) +public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{ + + @Override + public void commence( HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException ) throws IOException{ + response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); + } +} + A quick sidenote here is that the 401 is sent without the WWW-Authenticate header, as required by the HTTP Spec – we can of course set the value manually if we need to. +
+
+ <emphasis role="bold">3.3. The Login Form for REST</emphasis> + There are multiple ways to do Authentication for a REST API – one of the default Spring Security provides is Form Login – which uses an authentication processing filter – org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter. + The <form-login> element will create this filter and will also allow us to set our custom authentication success handler on it. This can also be done manually by using the <custom-filter> element to register a filter at the position FORM_LOGIN_FILTER – but the namespace support is flexible enough. + Note that for a standard web application, the auto-config attribute of the <http> element is shorthand syntax for some useful security configuration. While this may be appropriate for some very simple configurations, it doesn’t fit and should not be used for a REST API. +
+
+ <emphasis role="bold">3.4. Authentication should return 200 instead of 301</emphasis> + By default, form login will answer a successful authentication request with a 301 MOVED PERMANENTLY status code; this makes sense in the context of an actual login form which needs to redirect after login. For a RESTful web service however, the desired response for a successful authentication should be 200 OK. + This is done by injecting a custom authentication success handler in the form login filter, to replace the default one. The new handler implements the exact same login as the default org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler with one notable difference – the redirect logic is removed: + public class MySavedRequestAwareAuthenticationSuccessHandler + extends SimpleUrlAuthenticationSuccessHandler { + + private RequestCache requestCache = new HttpSessionRequestCache(); + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) throws ServletException, IOException { + SavedRequest savedRequest = requestCache.getRequest(request, response); + + if (savedRequest == null) { + clearAuthenticationAttributes(request); + return; + } + String targetUrlParam = getTargetUrlParameter(); + if (isAlwaysUseDefaultTargetUrl() || + (targetUrlParam != null && + StringUtils.hasText(request.getParameter(targetUrlParam)))) { + requestCache.removeRequest(request, response); + clearAuthenticationAttributes(request); + return; + } + + clearAuthenticationAttributes(request); + } + + public void setRequestCache(RequestCache requestCache) { + this.requestCache = requestCache; + } +} +
+
+ <emphasis role="bold">3.5. Failed Authentication should return 401 instead of 302</emphasis> + Similarly – we configured the authentication failure handler – same way we did with the success handler. + Luckily – in this case, we don’t need to actually define a new class for this handler – the standard implementation – SimpleUrlAuthenticationFailureHandler – does just fine. + The only difference is that – now that we’re defining this explicitly in our XML config – it’s not going to get a default defaultFailureUrl from Spring – and so it won’t redirect. +
+
+ <emphasis role="bold">3.6. The Authentication Manager and Provider</emphasis> + The authentication process uses an in-memory provider to perform authentication – this is meant to simplify the configuration as a production implementation of these artifacts is outside the scope of this post. +
+
+ <emphasis role="bold">3.7 Finally – Authentication against the running REST Service</emphasis> + Now let’s see how we can authenticate against the REST API – the URL for login is /j_spring_security_check – and a simple curl command performing login would be: + curl -i -X POST -d j_username=user -d j_password=userPass +http://localhost:8080/spring-security-rest/j_spring_security_check + This request will return the Cookie which will then be used by any subsequent request against the REST Service. + We can use curl to authentication and store the cookie it receives in a file: + curl -i -X POST -d j_username=user -d j_password=userPass -c /opt/cookies.txt +http://localhost:8080/spring-security-rest/j_spring_security_check + Then we can use the cookie from the file to do further authenticated requests: + curl -i --header "Accept:application/json" -X GET -b /opt/cookies.txt +http://localhost:8080/spring-security-rest/api/foos + This authenticated request will correctly result in a 200 OK: + HTTP/1.1 200 OK +Server: Apache-Coyote/1.1 +Content-Type: application/json;charset=UTF-8 +Transfer-Encoding: chunked +Date: Wed, 24 Jul 2013 20:31:13 GMT + +[{"id":0,"name":"JbidXc"}] +
+
+
+ <anchor xml:id="dbdoclet.4_Maven_and_other_trouble"/><emphasis role="bold">4. Maven and other trouble</emphasis> + The Spring core dependencies necessary for a web application and for the REST Service have been discussed in detail. For security, we’ll need to add: spring-security-web and spring-security-config – all of these have also been covered in the Maven for Spring Security tutorial. + It’s worth paying close attention to the way Maven will resolve the older Spring dependencies – the resolution strategy will start causing problems once the security artifacts are added to the pom. To address this problem, some of the core dependencies will need to be overridden in order to keep them at the right version. +
+
+ <anchor xml:id="dbdoclet.5_Conclusion"/><emphasis role="bold">5. Conclusion</emphasis> + This post covered the basic security configuration and implementation for a RESTful Service using Spring Security 3.1, discussing the web.xml, the security configuration, the HTTP status codes for the authentication process and the Maven resolution of the security artifacts. + The implementation of this Spring Security REST Tutorial can be downloaded as a working sample project.This is an Eclipse based project, so it should be easy to import and run as it is.
- Subscribe - Subscribe to our e-mail newsletter to receive updates. - + <emphasis role="bold">I usually post about Security on Google+ - you can follow me there: </emphasis> + + + + + + + + REST, security, Spring - (published) Handling Static Resources With Spring - Convert HTML to PDF using Apache FOP - -
- No comments yet. - -
-
-
- Leave a Reply <link xl:href="/?p=1092#respond">Click here to cancel reply.</link> - - Logged in as odeskAuthor8. Log out? - Comment - - + + Ben The issue for me is having users inside my xml. How would you redirect the user auth to an external resource. Would you overwrite authenticationManager? + + + + Eugen As it is mentioned in the article, the in memory authentication provider is only used because using a real provider is outside the scope of this post. Thanks for the feedback. + + + + Sigmund Lundgren Hmm successful auth still redirects for my, done in the spring base class. Had to comment this line in the successhandler: + //super.onAuthenticationSuccess(request, response, authentication); + + + René Fleischhauer Hi Sigmund, all, + I have the same problem… + super.onAuthenticationSuccess(request, response, authentication) calls SimpleUrlAuthenticationSuccessHandler#handle which contains the following line + redirectStrategy.sendRedirect(request, response, targetUrl); + Seems to be pretty non-sense to call the super method and therefore, I also removed it. Additionally I added a response.setStatus(200) for safety purposes… + Best, + René + + + + + + + + fadi Hi, + Am having a problem in understanding one thing, how the actual login will be done. I added the configuration and when trying to access a rest method/url I get 401 error, but am unable to figure out how and where to login. can help me pleas? + + + http://www.baeldung.com/ Eugen Paraschiv The article is now updated with the exact process of how to perform the login and how to use the cookie in further requests. + + + + + + + + Naama Great article! + + + + http://profile.yahoo.com/DULVM64SMPX6Q74MRXYD4TFHPA Marc de Verdelhan Your article was just what I needed. But I tested your solution and it always returned a “401 Unauthorized”. + Finally I used the following config: + Now it’s simpler and it works fine. Could you explain why? + Thank you. + + + http://www.baeldung.com/ Eugen Paraschiv Hey – thanks for the feedback – I updated the article and explained how exactly to authentication and then how to use the resulting cookie in further requests against the REST API – hope it helps. + + + + + + + + René Fleischhauer Hi all, + thanks for the tutorial. Great stuff! I have a minor question: + I added within the element in order to customize the login url. After starting the application again the following exception occurs: + org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Filter beans ” and ” have the same ‘order’ value. When using custom filters, please make sure the positions do not conflict with default filters. Alternatively you can disable the default filters by removing the corresponding child elements from and avoiding the use of . + The problem is clear, however I’m not sure how I can avoid the use of j_spring_security_check. I’d highly appreciate any hint. + Best, + René + + + http://www.baeldung.com/ Eugen Paraschiv Hi – yes, using the element is a good alternative as it does keep the configuration simple – please check out the updated configuration section and the new github project for a working implementation. Thanks. + + + + + + + + glz Great article, however every time I get 401 Unauthorized, regardless sending or not valid username and password (temporary/temporary) in username or j_username and password or j_password. Tried to figure it out looking at your git project, but there seems to be a lot of other stuff, and the only authentication used in this project is Digest authentication. Did I miss something important here? + + + http://www.baeldung.com/ Eugen Paraschiv Hi – I updated the article to better explain how to perform login and how to interact with the service; I also added a specific github project to only cover this article – should be simpler to understand. Thanks. + + + + + + + + bhecht This was very helpful. + I as well got an 401 Unauthorized. + After dubugging i found out the problem is at UsernamePasswordAuthenticationFilter.requiresAuthentication() which returns true only if the URI ends with /j_spring_security_check. + I had to override this class and return true in the requiresAuthentication(), so it will work. + + + http://www.baeldung.com/ Eugen Paraschiv Hi – the article is now updated to better explain how to interact with the REST Service – in short, yes, the first request is to /j_spring_security_check – this will return the Cookie which will be used in any further requests against the service. + + + + + + + + Stephane Hi, + I already have in place a working form based authentication for non-REST requests with a custom provider against a legacy database table of existing administrator credentials. + Now, I’m trying to add an authentication, for the REST requests this time. + I wish to use the same authentication provider if possible. + My existing setup is: + I added another http element: + before the previous one but it still gives me a: A universal match pattern (‘/**’) is defined before other patterns in the filter chain… + I wonder what to do at this point. + You’d have some tips on how to have two authentication setups, one for browser web page authentication and one for REST based ? + Thanks for the cool article ! + + + http://www.baeldung.com/ Eugen Paraschiv I suggest using two different patterns for the 2 http elements – map the rest one on /rest or something similar and the standard one to /mvc or similar. This should keep things nice and separate. + + + + + + + + Stephane Hello, + I was trying to use a as you suggested. But it kept doing a redirect if no user credentials were given. This issue is explained and solved (thank you Rob Winch at http://forum.springsource.org/showthread.php?139586-Two-lt-http-gt-container-elements-with-one-for-the-browser-and-one-for-REST + + + + Franklin Antony “Authentication should return 200 instead of 301″ portion doesn’t work as expected. In “MySavedRequestAwareAuthenticationSuccessHandler” the super.onAuthenticationSuccess(request, response, authentication) actually triggers a redirectStrategy.sendRedirect(request, response, targetUrl) from the parent AbstractAuthenticationTargetUrlRequestHandler. Just commenting out works, but am not sure if that is expected. Any suggestions ? + + + http://www.baeldung.com/ Eugen Paraschiv Actually, the sending of the redirect should already be commented + out: MySavedRequestAwareAuthenticationSuccessHandler. + Please let me know if it still doesn’t work. + Thanks. Eugen. + + + Franklin Antony The sending of redirect is commented out as required but the problem lies in the parent class “AbstractAuthenticationTargetUrlRequestHandler” which “SimpleUrlAuthenticationSuccessHandler” extends from. When the “super.onAuthenticationSuccess(request, response, authentication) ” is called from “MySavedRequestAwareAuthenticationSuccessHandler” it triggers “redirectStrategy.sendRedirect(request, response, targetUrl);” in the “AbstractAuthenticationTargetUrlRequestHandler”. + I have seen in this article “http://www.petrikainulainen.net/programming/spring-framework/integration-testing-of-spring-mvc-applications-security” that the author is not calling the “super.onAuthenticationSuccess(request, response, authentication) ” and is just calling “response.setStatus(HttpServletResponse.SC_OK);” + Regards, + Franklin + + + http://www.baeldung.com/ Eugen Paraschiv Nice spot on the redirect still possibly occurring in this example – I have updated the example by preserving the exact functionality from the parent classes and just removing the redirect. + Thanks. Eugen. + + + Franklin Antony Cool. Looks fine now. Any idea why “clearAuthenticationAttributes(request)” is being reported as a compilation error “The method clearAuthenticationAttributes(HttpServletRequest) is undefined for the type” ? + Its supposed to be a protected method in + http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandler.html#clearAuthenticationAttributes(javax.servlet.http.HttpServletRequest) + I am using Spring Security 3.0.2 but somehow its not there in my parent class . Aaarg!! + + + + http://www.baeldung.com/ Eugen Paraschiv I’m compiling against 3.1.4, so the implementation has probably been opened up a bit. + + + + Franklin Antony Ok. Thanks. Should be fine. + + + + + + + + + + + + + + + + + + + + kiran This is very helpful.But when ever login fails with bad credentials it’s returing 302 . + And for logout too it’s returning 302. + Shouln’t that be changed ? + + + + Sebastian I am using a combination of form-based login and basic authentication. So the REST endpoints can be used with the users session if he has one but falls back to basic auth if no session exists. So I like your approach with the “restAuthenticationEntryPoint”. The problem however is, that according to the HTTP documentation, a HTTP 401 response must include a WWW-Authenticate header, which you are not sending. On the other hand, this is good, because it means the browser will not display a basic authentication login dialog as it would if the WWW-Authenticate header was present. While my solution now works I am thinking if there is a better solution that allows me to use basic authentication fallback but does not violate the HTTP specification. + Update: I have now found a better solution. Instead of calling response.setError(…) I set the Header and Status code individually: + response.setHeader(“WWW-Authenticate”, “FormBased”); + response.setStatus( HttpServletResponse.SC_UNAUTHORIZED ); + Setting WWW-Authenticate to “FormBased” still prevents the browser from showing the login screen. + + + Abhishek Amte Hello Sebastian, + How did you configure your basic authentication to use the credentials from the form-based? + + + Sebastian Hello Abhishek, + I did not. Sending WWW-Authenticate to “FormBased” is only a means to prevent the browser from showing the basic authentication login dialog, so I can implement it in HTML. You could also set it to “Foobar” or “Custom”, it just has to be different than “Basic”. + I now have the following in my spring security: + authenticationFailureHandler is just an instance of SimpleUrlAuthenticationFailureHandler (without any properties set). + This allows me to login in two ways: + 1. By HTTP Basic Auth, sending a HTTP header: + Authorization: Basic + 2. With a POST to /session: + method: ‘POST’, + url: ‘../rest/session’, + data: “j_username=” + username + “&j_password=” + password, + headers: {‘Content-Type': ‘application/x-www-form-urlencoded’ } + + + Abhishek Amte Thanks a lot Sebastian + + + + + + + + + + + + http://www.baeldung.com/ Eugen Paraschiv Yes, the WWW-Authenticate header is not included as the spec requires. This is because the current solution is a hybrid between a REST API secured with Basic/Digest authentication (for example) and a form-based authentication mechanism. + Now – setting your own custom value for WWW-Authenticate is defninitly an option but what may be better – and what I’ve been doing – is to separate the two responsibilities – the API and the UI. + What I mean is – the REST API is secured with Basic Auth (for this example – in practice I would suggest Digest) – and that’s it. No fallback and no complexity. Now – the UI is a form-based web application – again, no additional complexity. The bridget between them is a proxy for all of the requests from the UI to the API. + Hope that makes sense. + Cheers, + Eugen. + + + + + + + + Pingback: Spring MVC Token Based Authentication to a REST Service – Part 2 | notesofguclu() + + + + Himalay Whenever login fails with bad credentials it’s returing 302, shouldn’t it return 401? + + + http://www.baeldung.com/ Eugen Paraschiv You’re right – for correct semantics, it would have to return the 401 – I updated the article and the github project – thanks for the suggestion. + Cheers, + Eugen. + + + + + + + + Alessandro Scuderetti Very useful article. I’m also interesting in => How to use the “login rest” with restful @Controller that accept and response in json format? + This: http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2002229 according to you, is ti good? + + + http://www.baeldung.com/ Eugen Paraschiv Hey Alessandro – a few notes on that particular article: + – first, it doesn’t really handle authentication for a RESTful API – but instead for a more standard webapp; a REST API will have additional architectural constraints which will impact what you’ll be able to do with Spring Security + – next – Spring Security already has all the elements necessary for authentication in place – so adding a custom controller to replace these elements is not really necessary; what’s more – using the framework will help you deal with all of the corner cases and potential vulnerabilities that you will need to keep in mind when rolling your own controller – so, without a solid reason to do so, I would stay away from doing that + – and finally, both the framework as well as AJAX are powerful/flexible enough to do this without a custom auth controller; what I mean is – from AJAX – you can definitely handle the default (non-json) response of Spring Security if you need to; also, from Spring Security, you can hook into the authentication process and only override the success handler if you really need to return json to the client + Hope that helps. + Cheers, + Eugen. + + + + + + + + Richard Have you tried to implement this in spring security 3.2 with the java config? I’ve put most of it together, but the form does not render on accessing /login as a GET request. I wonder if anyone has had the same experience? (Or have I missed the point and you can’t get to the login form with this configuration?) + + + http://www.baeldung.com/ Eugen Paraschiv Hey Richard – everything should work fine, but just to be on the safe side, I’m going to go through the implementation again and will get back to you. Cheers, + Eugen. + + + elysch Hi. + How did you register the restAuthenticationEntryPoint using only java config? + Thanks + + + http://www.baeldung.com/ Eugen Paraschiv I didn’t – there’s some XML configuration for security in the project. That being said, if you do want to only use Java config, that’s possible now with the new release. Cheers, + Eugen. + + + + + + + + + + + + http://www.baeldung.com/ Eugen Paraschiv Hey Richard – I checked and everything works well. The project is indeed using Spring 3.2, and some java config. However, note that the security configuration is still XML, so if that is what you meant by java config – that support is still very new and I have not integrated it into these tutorials yet. Hope this helps. Cheers, + Eugen. + + + + elysch Hi Richard. + I asked this to Eugen by mistake, but it was intended for you: + How did you register the restAuthenticationEntryPoint using only java config? + Thanks + + + Richard http.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint()) + + + + + + + + http://www.baeldung.com/ Eugen Paraschiv I haven’t yet, no. I’ll use the java config variant at some point, but I didn’t have the chance yet. Cheers, + Eugen. + + + + + + + + ohadr dev what about logout? + + + http://www.baeldung.com/ Eugen Paraschiv Hey Ohadr – logout is indeed enabled in the Spring Security config – notice the – so you’ll be able to log out at /j_spring_security_logout. Hope this helps. Cheers, + Eugen. + + + OhadR thanks for your reply! the regular logout redirects to a default target URL. it needs a special treatment… + + + + ohadr dev i solved it. you can see here… http://www.codeproject.com/Tips/521847/Logout-Spring-s-LogoutFilter. thanks! + + + + + + + + + + + + Kaan Can someone give an example how to use restTemplate instead of ‘curl -i -X POST -d j_username=user -d j_password=userPass -c /opt/cookies.txt’ . I am able to do it without cookie file but other requests gives me 401 unauthorized response. Or does anyone know how i can handle the problem? Thanks + + + http://www.baeldung.com/ Eugen Paraschiv Hey Kann – sending the cookie with RestTemplate is nothing special – just a matter of adding the cookie header with the cookie value – that should allow you to correctly send the cookie in the request. Cheers, + Eugen. + + + + + + + + http://justincalleja.com/ Justin Hi Eugen, + This post is really helpful – thanks a bunch + I would love to hear your opinion regarding the following: I have a login page which I would like to use in a “normal” fashion – i.e. I want spring security to redirect sending back a 301 on success and have the browser take care of storing the session. + The idea is that the page which the browser is redirected to is an SPA in which I’ll be making use of Javascript to get the JSESSIONID out of the the cookie and basically replicate the same kind of request a browser would make but using Javascript to access the protected endpoints. + The thing that’s annoying me is that I only want this behaviour when hitting security/session (a re-map of j_spring_security_check) from a browser (say login.html). I would love to have the behaviour you illustrated in this post when I’m trying to get the JSESSIONID from a non-browser environment i.e. 200 or 401. + What do you think about this situation? Personally, I don’t think I’ll be going down the 2 servers route, one maintaing session state and proxying for the “real” REST server. + I was thinking maybe Spring Security can be configured to have 2 or something of the sort. Note that the endpoints they affect would be the same, it’s just that it would be awesome if I could have something like security/session for the browser and api/security/session for REST clients (with different behaviours). I’m not familiar enough with Spring Security to know if this is possible. Is it? Or perhaps you would tackle it differently? + Regards, + Justin + Edit: + Note, I am just exploring options. I am currently thinking I will ditch the whole browser shortcut and just store it in a cookie or local storage using Javascript. But I was just curious about the two endpoint for security approach. + + + http://www.baeldung.com/ Eugen Paraschiv Hey Justin, + Two notes about your usecase. First thing is that – since you’re basically replicating some of the browser behavior in js – why do you need the server response to be a 301? You could simply do a redirect, or hide the login popup regardless of the status code. + Second – you probably don’t need 2 services, but yes – you can have 2 authentication paths if you really need to – one for the standard login and the other that’s more focused on the API. Keep in mind that now (since 3.1) you can have multiple elements. If that’s not an option you can always do it manually (but your intuition is right – it would be quite low level and would require a solid understanding of the framework). Hope it helps. Cheers, + Eugen. + + + http://justincalleja.com/ Justin Cheers Eugen + True, I was leaning towards sticking to the more REST-like behaviour and doing the rest with Javascript. I was thinking that maybe it would be a shortcut to let the browser handle that part – was considering using a normal for the login. Also, the thought “I could have 2 endpoints for session management one of which is easier to work with in a browser – maybe that would be useful to other people building apps against the REST API. So that’s why I asked. + I will continue with the Javascript approach. Maybe later I’ll do some research on the 2 endpoint approach. + Thanks a lot! + Regards, + Justin + + + http://www.baeldung.com/ Eugen Paraschiv Sounds good Justin. Also – it’s probably the kind of thing that will help someone else, so you can always write about it as well. Cheers, + Eugen. + + + http://justincalleja.com/ Justin hehe yes I have been meaning to set up a blog for quite some time. It will happen eventually (even if just to keep track of things). + Thanks for the suggestion + Regards, + Justin + + + + http://justincalleja.com/ Justin btw, as an update – I ended up going for the page for login and page for SPA approach using a normal no JS for the login page. I came up against problems with server sending back HttpOnly with cookies so couldn’t access from JS. I figured it would be more work (and code) than I liked to change the behaviour on the server side (overriding Spring Security classes – maybe haven’t actually done it). + The 2 page approach is working for now and I can keep a simple Spring Security config. + Regards, + Justin + + + + http://www.baeldung.com/ Eugen Paraschiv Glad it worked out – I’m getting these kinds of questions a lot lately, so I’m thinking of covering the various options in a series. Cheers, + Eugen. + + + + http://justincalleja.com/ Justin +1 to that + Regards, + Justin + + + + + + + + + + + + + + + + + + + + fadi Thank you for the response, but am using FF plugin and I added the Authorization header to the url, the only place fired in my code is the EntryPoint and it never enters my AuthenticationProvider. which makes wounder if am doing something wrong! + Thanks + + + + DropDeadFred If you are using the REST service through AJAX from a browser can you had the necessary Authentication headers? For example, if you are using form based authentication to your website and want to retrieve data from your REST service. I guess I must just be missing something here. + + + + Branislav Vidovic This is the most interesting part in my opinion…. I am interested which other additional component of spring security you have extended to read request headers and build a required authentication object. Besides i had a look into your git project but in there you did not do it totally like in this post.. + + + + http://www.baeldung.com/ Eugen Paraschiv You can take a look at: http://code.google.com/p/crypto-js/ + + + + http://www.baeldung.com/ Eugen Paraschiv Not sure how you can add the header to the URL – do you mean you added the header to the request? Also, to follow some working examples, you can always clone the project from github and run the tests. + + + + + + + + - © 2014 Technical Articles. All Rights Reserved. + © 2014 Baeldung. All Rights Reserved. + + + + +