Spring Security Ajax login - ajax

I have implemented this security proccess in my project:
Spring Security 3 - MVC Integration Tutorial (Part 2).
My problem is that I need to turn it into an Ajax-based login.
What do I need to do in order to make this XML suitable with just returning string/JSON to the client?
I understand that the problem might be in the form-login tag.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<!-- This is where we configure Spring-Security -->
<http auto-config="true" use-expressions="true" access-denied-page="/Management/auth/denied" >
<intercept-url pattern="/Management/auth/login" access="permitAll"/>
<intercept-url pattern="/Management/main/admin" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/Management/main/common" access="hasRole('ROLE_USER')"/>
<form-login
login-page="/Management/auth/login"
authentication-failure-url="/Management/auth/login?error=true"
default-target-url="/Management/main/common"/>
<logout
invalidate-session="true"
logout-success-url="/Management/auth/login"
logout-url="/Management/auth/logout"/>
</http>
<!-- Declare an authentication-manager to use a custom userDetailsService -->
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder ref="passwordEncoder"/>
</authentication-provider>
</authentication-manager>
<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
<beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>
<!-- A custom service where Spring will retrieve users and their corresponding access levels -->
<beans:bean id="customUserDetailsService" class="com.affiliates.service.CustomUserDetailsService"/>
</beans:beans>

This is an old post, but it still comes up as one of the top results for "spring security ajax login," so I figured I'd share my solution. It follows Spring Security standards and is pretty simple to setup, the trick is to have 2 <http> elements in your security configuration, one for REST/Ajax and one for the rest of the app (regular HTML pages). The order in which <http>'s appear is important, it has to go from more specific to more generic URLs, just like <url-intercept> elements inside of a <http>.
Step 1: Setup Two Separate <http>'s
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!-- a shared request cache is required for multiple http elements -->
<beans:bean id="requestCache" class="org.springframework.security.web.savedrequest.HttpSessionRequestCache" />
<!-- remove security from static resources to avoid going through the security filter chain -->
<http pattern="/resources/**" security="none" />
<!-- http config for REST services (AJAX interface)
=================================================== -->
<http auto-config="true" use-expressions="true" pattern="/rest/**">
<!-- login configuration
login-processing-url="/rest/security/login-processing" front-end AJAX requests for authentication POST to this URL
login-page="/rest/security/login-page" means "authentication is required"
authentication-failure-url="/rest/security/authentication-failure" means "authentication failed, bad credentials or other security exception"
default-target-url="/rest/security/default-target" front-end AJAX requests are redirected here after success authentication
-->
<form-login
login-processing-url="/rest/security/login-processing"
login-page="/rest/security/login-page"
authentication-failure-url="/rest/security/authentication-failure"
default-target-url="/rest/security/default-target"
always-use-default-target="true" />
<logout logout-url="/rest/security/logout-url" />
<!-- REST services can be secured here, will respond with JSON instead of HTML -->
<intercept-url pattern="/rest/calendar/**" access="hasRole('ROLE_USER')" />
<!-- other REST intercept-urls go here -->
<!-- end it with a catch all -->
<intercept-url pattern="/rest/**" access="isAuthenticated()" />
<!-- reference to the shared request cache -->
<request-cache ref="requestCache"/>
</http>
<!-- http config for regular HTML pages
=================================================== -->
<http auto-config="true" use-expressions="true">
<form-login
login-processing-url="/security/j_spring_security_check"
login-page="/login"
authentication-failure-url="/login?login_error=t" />
<logout logout-url="/security/j_spring_security_logout" />
<intercept-url pattern="/calendar/**" access="hasRole('ROLE_USER')" />
<!-- other intercept-urls go here -->
<!-- in my app's case, the HTML config ends with permitting all users and requiring HTTPS
it is always a good idea to send sensitive information like passwords over HTTPS -->
<intercept-url pattern="/**" access="permitAll" requires-channel="https" />
<!-- reference to the shared request cache -->
<request-cache ref="requestCache"/>
</http>
<!-- authentication manager and other configuration go below -->
</beans:beans>
Step 2: REST Authentication Controller
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import flexjson.JSONSerializer;
#Controller
#RequestMapping(value = "/rest/security")
public class RestAuthenticationController {
public HttpHeaders getJsonHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
return headers;
}
#RequestMapping(value="/login-page", method = RequestMethod.GET)
public ResponseEntity<String> apiLoginPage() {
return new ResponseEntity<String>(getJsonHeaders(), HttpStatus.UNAUTHORIZED);
}
#RequestMapping(value="/authentication-failure", method = RequestMethod.GET)
public ResponseEntity<String> apiAuthenticationFailure() {
// return HttpStatus.OK to let your front-end know the request completed (no 401, it will cause you to go back to login again, loops, not good)
// include some message code to indicate unsuccessful login
return new ResponseEntity<String>("{\"success\" : false, \"message\" : \"authentication-failure\"}", getJsonHeaders(), HttpStatus.OK);
}
#RequestMapping(value="/default-target", method = RequestMethod.GET)
public ResponseEntity<String> apiDefaultTarget() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// exclude/include whatever fields you need
String userJson = new JSONSerializer().exclude("*.class", "*.password").serialize(authentication);
return new ResponseEntity<String>(userJson, getJsonHeaders(), HttpStatus.OK);
}
}
Step 3: Submit AJAX form and process the response, required jQuery's ajaxForm library
<form action="/rest/security/login-processing" method="POST">
...
</form>
$('form').ajaxForm({
success: function(response, statusText, xhr, $form) {
console.log(response);
if(response == null || response.username == null) {
alert("authentication failure");
} else {
// response is JSON version of the Spring's Authentication
alert("authentication success");
}
},
error: function(response, statusText, error, $form) {
if(response != null && response.message == "authentication-failure") {
alert("authentication failure");
}
}
});

Spring is shifting away from XML based configurations and towards Java #Configuration classes. Below is #Configuration version of the setup explained in the post above (Spring Security Ajax login). Steps 2 & 3 remain the same, replace Step 1 with this code. The order is once again important, more specific definitions needs to be loaded before more generic ones, use #Order(1) and #Order(2) to control that.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
#Configuration
#EnableWebSecurity
public class WebMvcSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Bean(name = "requestCache")
public RequestCache getRequestCache() {
return new HttpSessionRequestCache();
}
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Autowired private RequestCache requestCache;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.regexMatcher("/rest.*")
.authorizeRequests()
.antMatchers("/rest/calendar/**")
.hasAuthority("ROLE_USER")
.antMatchers("/rest/**")
.permitAll()
.and()
.headers()
.xssProtection()
.and()
.logout()
.logoutUrl("/rest/security/logout-url")
.and()
.requestCache()
.requestCache(requestCache)
.and()
.formLogin()
.loginProcessingUrl("/rest/security/login-processing")
.loginPage("/rest/security/login-page")
.failureUrl("/rest/security/authentication-failure")
.defaultSuccessUrl("/rest/security/default-target", false)
.and()
.httpBasic();
}
}
#Configuration
#Order(2)
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Autowired private RequestCache requestCache;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.regexMatchers("/calendar/.*")
.hasAuthority("ROLE_USER")
.regexMatchers("/.*")
.permitAll()
.and()
.logout()
.logoutUrl("/security/j_spring_security_logout")
.and()
.requestCache()
.requestCache(requestCache)
.and()
.formLogin()
.loginProcessingUrl("/security/j_spring_security_check")
.loginPage("/login")
.failureUrl("/login?login_error=t" )
.and()
.httpBasic();
}
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**")
.antMatchers("/sitemap.xml");
}
}

It depends on the implementation of your ajax-login. In any case, I guess you need to implement a custom filter. There are two good tutorials for using Spring Security with ExtJs:
Integrating Spring Security 3 with Extjs
Integrating Spring Security with ExtJS Login Page
It should work very similar for other Ajax login-forms.

You can use HttpServletRequest.login(username,password) to login, just like:
#Controller
#RequestMapping("/login")
public class AjaxLoginController {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String performLogin(
#RequestParam("username") String username,
#RequestParam("password") String password,
HttpServletRequest request, HttpServletResponse response) {
try {
request.login(username,password);
return "{\"status\": true}";
} catch (Exception e) {
return "{\"status\": false, \"error\": \"Bad Credentials\"}";
}
}

Related

Spring Boot, Spring Security - XML based configuration

Spring Boot 2.3.4, Spring Security, securing REST controllers (endpoints).
I have a solution with a Java configuration class, but now I have the task to do it with XML.
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public static final String USER = "USER";
public static final String ADMIN = "ADMIN";
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("{noop}" + "user123")
.roles(USER)
.and()
.withUser("admin")
.password("{noop}" + "admin456")
.roles(ADMIN, USER);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/", "/login").permitAll()
.antMatchers("/path1/**").hasRole(ADMIN)
.antMatchers("/path2/**").hasRole(USER)
.antMatchers(HttpMethod.DELETE, "/path3/{name}").hasRole(ADMIN)
.antMatchers(HttpMethod.GET, "/path3/{name}").hasRole(USER)
// more antMatchers...
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.formLogin().disable();
}
}
Never did a XML based configuration before, this must be something done a lot back in the days. Anyways, got the task to do it in XML.
Have no clue how.
What pieces will be needed, just the XML file, or still a Java configuration file (like WebSecurityConfig.java)?
I tried the following
WebSecurityConfig.java
#Configuration
#ImportResource({ "classpath:webSecurityConfig.xml" })
public class WebSecurityConfig {
public WebSecurityConfig() {
super();
}
}
webSecurityConfig.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"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<http create-session="stateless" use-expressions="true">
<intercept-url pattern="/" access="permitAll()"/>
<intercept-url pattern="/login" access="permitAll()"/>
<intercept-url pattern="/path1/**" access="hasAuthority('ROLE_ADMIN')"/>
<intercept-url pattern="/path2/**" access="hasAuthority('ROLE_USER')"/>
<intercept-url method="DELETE" pattern="/path3/{name}" access="hasAuthority('ROLE_ADMIN')"/>
<intercept-url method="GET" pattern="/path3/{name}" access="hasAuthority('ROLE_USER')"/>
<http-basic/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="{noop}user123" authorities="ROLE_USER"/>
<user name="admin" password="{noop}admin456" authorities="ROLE_USER,ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
But on startup the following error is shown
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method setObjectPostProcessor in org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter required a bean of type 'org.springframework.security.config.annotation.ObjectPostProcessor' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.config.annotation.ObjectPostProcessor' in your configuration.
Not sure what's wrong or missing. So far Google wasn't very helpful.

Spring Security Login Processing url not available

I have a project where Spring is used with JSF (using PrimeFaces). Up until now we have used xml configuration for Spring Security, but I have been tasked with porting it to java based configuration.
I have now went from the xml config in applicationContext.xml :
<!-- Security Config -->
<security:http security="none" pattern="/javax.faces.resource/**"/>
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/login.xhtml" access="permitAll"/>
<security:intercept-url pattern="/**" access="permitAll"/>
<security:form-login login-page="/login.xhtml"
login-processing-url="/do_login"
authentication-failure-url="/login.xhtml"
authentication-success-handler-ref="authSuccessHandler"
username-parameter="email"
password-parameter="password"/>
<security:logout logout-success-url="/login.xhtml"
logout-url="/do_logout"
delete-cookies="JSESSIONID"/>
</security:http>
<bean id="userDetails" class="com.madmob.madmoney.security.UserDetailsServiceImpl"></bean>
<bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<constructor-arg name="strength" value="10" />
</bean>
<bean id="authSuccessHandler" class="com.madmob.madmoney.security.UserAuthenticationSuccessHandler"></bean>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userDetails">
<security:password-encoder ref="encoder" />
</security:authentication-provider>
</security:authentication-manager>
and the following from web.xml :
<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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
To the following java based configuration :
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserAuthenticationSuccessHandler authSuccessHandler;
#Autowired
DataSource dataSource;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.jdbcAuthentication().usersByUsernameQuery("SELECT email, passowrd, enabled FROM app_user WHERE email = ?")
.authoritiesByUsernameQuery("SELECT role_name FROM role WHERE role_id = (SELECT role_id FROM user_role WHERE email = ?)")
.dataSource(dataSource).passwordEncoder(new BCryptPasswordEncoder(10));
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/javax.faces.resource/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated()
.and()
.formLogin().loginPage("/login.xhtml").loginProcessingUrl("/do_login")
.failureUrl("/login.xhtml").successHandler(authSuccessHandler)
.usernameParameter("email").passwordParameter("password").permitAll()
.and()
.logout().logoutSuccessUrl("/login.xhtml").logoutUrl("/do_logout")
.deleteCookies("JSESSIONID");
// temp user add form
// TODO remove
http.antMatcher("/userForm.xhtml").authorizeRequests().anyRequest().permitAll();
}
}
and
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC, DispatcherType.FORWARD);
}
}
Login worked fine on the xml based configuration, but since switching if I try to login Tomcat returns 404 with : The requested resource is not available.
All pages are also accessible regardless of logged in or not.
Below is my login form :
<h:form id="loginForm" prependId="false" styleClass="panel-body">
<div>
<p:inputText id="email" required="true" label="email"
value="#{loginBean.email}" styleClass="form-control f-75"
placeholder="Email Address"></p:inputText>
<h:message for="email" styleClass="validationMsg"/>
</div>
<div class="spacer"/>
<div>
<p:password id="password" required="true" label="password"
value="#{loginBean.password}" placeholder="Password"></p:password>
<h:message for="password" styleClass="validationMsg"/>
<h:messages globalOnly="true" styleClass="validationMsg" />
</div>
<div class="spacer"/>
<p:commandButton id="login" value="Log in"
actionListener="#{loginBean.login}" ajax="false"/>
</h:form>
and the login method in my backing bean :
/**
* Forwards login parameters to Spring Security
*/
public void login(ActionEvent loginEvt){
// setup external context
logger.info("Starting login");
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
// setup dispatcher for spring security
logger.info("Setup dispatcher");
RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
.getRequestDispatcher("/do_login");
try {
// forward request
logger.info("Forwarding request to spring security");
dispatcher.forward((ServletRequest) context.getRequest(),
(ServletResponse) context.getResponse());
} catch (ServletException sEx) {
logger.error("The servlet has encountered a problem", sEx);
} catch (IOException ioEx) {
logger.error("An I/O error has occured", ioEx);
} catch (Exception ex) {
logger.error("An error has occured", ex);
}
// finish response
FacesContext.getCurrentInstance().responseComplete();
}
This is running on Java 1.8, Tomcat 7, Spring and Spring Security 3.2.5, JSF 2.1, Primefaces 5
Things I have tried since encountering the problem :
Added the SpringSecurityInitializer since initially I only used SecurityConfig.
Tried using default Spring Security url(j_spring_security_check), by not specifying the processing url and forwarding to that instead.
Disabled csrf
Added getSecurityDispatcherTypes method to SpringSecurityInitializer to match the config from web.xml
Various other smaller things while searching for a solution
I found the issue. The problem lies with :
http.antMatcher("/userForm.xhtml").authorizeRequests().anyRequest().permitAll();
This was just purely incorrect chaining of the methods on my part by the looks of it. I don't really understand why it caused the issue with login processing url not being found instead of just unexpected access behavior, but I changed that entire snippet of the method to look as follows :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers("/userForm.xhtml").permitAll() //TODO remove temp user add form
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login.xhtml").loginProcessingUrl("/do_login")
.failureUrl("/login.xhtml").successHandler(authSuccessHandler)
.usernameParameter("email").passwordParameter("password").permitAll()
.and()
.logout().logoutSuccessUrl("/login.xhtml").logoutUrl("/do_logout")
.deleteCookies("JSESSIONID");
}
This of course also makes a lot more sense, but I primarily separated them initially because as the comment specifies, the userForm.xhtml is temporary.

Spring Security: Migrating Self Closing Authentication Manager xml Tag to Java Config

I have a fairly out-of-the-box Spring Security 3.2 J2EE xml config that I have almost finished converting to Java config.
The Before xml file:
<sec:global-method-security pre-post-annotations="enabled" />
<sec:authentication-manager />
<sec:http pattern="/css/**" security="none" />
<sec:http pattern="/js/**" security="none" />
....
<sec:http auto-config="true" create-session="never" use-expressions="true>
<sec:session-management session-fixation-protection="none" />
<sec:jee mappable-roles="admin,user" />
<sec:intercept-url pattern="/operations/admin/**" access="hasRole('ROLE_admin')" />
<sec:intercept-url pattern="/**" access="permitAll" />
</sec:http>
The self closing authentication-manager tag is my issue. It's picking up the PreAuthenticatedAuthenticationProvider created by the jee tag. I'm not quite sure how to replicate it in the Java Config:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
#ImportResource("classpath:security-context.xml")
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
#Override
public void configure(WebSecurity web) throws Exception{
web
.ignoring.antMatchers("/css/**")
.and()
.ignoring.antMatchers("/js/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.sessionManagement()
.sessionFixation().none()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.csrf().disable()
.jee()
.mappableAuthorities("admin","user")
.and()
.authorizeRequests()
.antMatchers("/operations/admin/**").hasAuthority("admin")
.anyRequest.permitAll();
}
}
This is working now only because I am importing my old security-context.xml which has nothing in it except the authentication-manager tag.
I have playing around with declaring an AuthenticationManagerBuilder bean, but it seems like everything requires a specific reference to an AuthenticationProvider or UserDetailsService to work. The ProviderManager default constructor is deprecated.
I know that the jee() entry adds the PreAuthenticatedAuthenticationProvider to the sharedObjects inside HttpSecurity, so I could go through the trouble of getting the PreAuthenticatedAuthenticationProvider out of the sharedObjects to create an AuthenticationManager if necessary, but it seems like there ought to be a simple Java config counterpart to the self-closing xml tag that I am just missing.
Can you try this on your SpringSecurityConfig class :-
#Autowired
public void registerGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new AuthenticationManagerBeanDefinitionParser.NullAuthenticationProvider());
}

How to apply spring security on specific urls and leave some others using java config?

I am using java config to apply spring security and i am able to apply security on particular urls but i want the default login page of spring security whenever anyone hits urls other than url which is not secured.
Here is my code of SecurityConfig:
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
//import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.bind.annotation.RequestMethod;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/myproject/userCont/user").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/myproject/login/form")
.loginProcessingUrl("/login")
.failureUrl("/login/form?error")
.permitAll();
}
so when i hit /myproject/userCont/user with GET method it works correctly but when I hit the same url with POST method or other urls spring security do not shows default login page.
Can any one help me?
doGet and doPost in Servlets
You should go through the above link to get a clear idea about GET and POST methods.
To remove spring security for /myproject/userCont/user url ur code should look like:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/myproject/login/form")
.loginProcessingUrl("/login")
.failureUrl("/login/form?error")
.permitAll();
}
Further more, You should not convert your urls into POST method as this will change the entire behaviour of your web page.
When we are in xml file
Inside the configuration element, you can restrict access to particular URLs with
one or more elements. Each element specifies a URL pattern
and a set of access attributes required to access the URLs. Remember that you must
always include a wildcard at the end of a URL pattern. Failing to do so will make the URL pattern
unable to match a URL that has request parameters.
<security:http auto-config="true" >
<security:intercept-url pattern="/index*" access="ROLE_USER" />
<security:intercept-url pattern="/Transit*" access="ROLE_USER" />
<security:form-login login-page="/login.htm" default-target-url="/index.htm"
authentication-failure-url="/loginerror.htm" />
<security:logout logout-success-url="/logout.htm" />
</security:http>
When ever we are going to describe a url without any security, Then we should remove the particular url from the above lines of code under security configured xml file.
for example if we dont need any security for index page then the above coding should look like this.
<security:http auto-config="true" >
<security:intercept-url pattern="/Transit*" access="ROLE_USER" />
<security:form-login login-page="/login.htm" default-target-url="/index.htm"
authentication-failure-url="/loginerror.htm" />
<security:logout logout-success-url="/logout.htm" />
</security:http>

Spring Security 3.2 CSRF disable for specific URLs

Enabled CSRF in my Spring MVC application using Spring security 3.2.
My spring-security.xml
<http>
<intercept-url pattern="/**/verify" requires-channel="https"/>
<intercept-url pattern="/**/login*" requires-channel="http"/>
...
...
<csrf />
</http>
Trying to disable CSRF for requests that contain 'verify' in request URL.
MySecurityConfig.java
#Configuration
#EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
private CsrfMatcher csrfRequestMatcher = new CsrfMatcher();
#Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher);
}
class CsrfMatcher implements RequestMatcher {
#Override
public boolean matches(HttpServletRequest request) {
if (request.getRequestURL().indexOf("verify") != -1)
return false;
else if (request.getRequestURL().indexOf("homePage") != -1)
return false;
return true;
}
}
}
Csrf filter validates CSRF token that is submitted from 'verify' and Invalid token exception (403) is thrown as I'm submitting request to https from http. How can I disable csrf token authentication in such a scenario ?
I know this is not a direct answer, but people (as me) usually don't specify spring's version when searching for this kinds of questions.
So, since spring security a method exists that lets ignore some routes:
The following will ensure CSRF protection ignores:
Any GET, HEAD, TRACE, OPTIONS (this is the default)
We also explicitly state to ignore any request that starts with "/sockjs/"
http
.csrf()
.ignoringAntMatchers("/sockjs/**")
.and()
...
I hope that my answer can help someone else. I found this question searching for How to disable CSFR for specfic URLs in Spring Boot.
I used the solution described here:
http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/
This is the Spring Security configuration that allow me to disable the CSFR control on some URLs:
#Configuration
#EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// Build the request matcher for CSFR protection
RequestMatcher csrfRequestMatcher = new RequestMatcher() {
// Disable CSFR protection on the following urls:
private AntPathRequestMatcher[] requestMatchers = {
new AntPathRequestMatcher("/login"),
new AntPathRequestMatcher("/logout"),
new AntPathRequestMatcher("/verify/**")
};
#Override
public boolean matches(HttpServletRequest request) {
// If the request match one url the CSFR protection will be disabled
for (AntPathRequestMatcher rm : requestMatchers) {
if (rm.matches(request)) { return false; }
}
return true;
} // method matches
}; // new RequestMatcher
// Set security configurations
http
// Disable the csrf protection on some request matches
.csrf()
.requireCsrfProtectionMatcher(csrfRequestMatcher)
.and()
// Other configurations for the http object
// ...
return;
} // method configure
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
// Authentication manager configuration
// ...
}
}
It works with Spring Boot 1.2.2 (and Spring Security 3.2.6).
I am using Spring Security v4.1. After a lot of reading and testing, I disable the CSRF security feature for specific URLs using XML configuration.
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<http pattern="/files/**" security="none" create-session="stateless"/>
<http>
<intercept-url pattern="/admin/**" access="hasAuthority('GenericUser')" />
<intercept-url pattern="/**" access="permitAll" />
<form-login
login-page="/login"
login-processing-url="/login"
authentication-failure-url="/login"
default-target-url="/admin/"
password-parameter="password"
username-parameter="username"
/>
<logout delete-cookies="JSESSIONID" logout-success-url="/login" logout-url="/admin/logout" />
<http-basic />
<csrf request-matcher-ref="csrfMatcher"/>
</http>
<beans:bean id="csrfMatcher" class="org.springframework.security.web.util.matcher.OrRequestMatcher">
<beans:constructor-arg>
<util:list value-type="org.springframework.security.web.util.matcher.RequestMatcher">
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<beans:constructor-arg name="pattern" value="/rest/**"/>
<beans:constructor-arg name="httpMethod" value="POST"/>
</beans:bean>
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<beans:constructor-arg name="pattern" value="/rest/**"/>
<beans:constructor-arg name="httpMethod" value="PUT"/>
</beans:bean>
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<beans:constructor-arg name="pattern" value="/rest/**"/>
<beans:constructor-arg name="httpMethod" value="DELETE"/>
</beans:bean>
</util:list>
</beans:constructor-arg>
</beans:bean>
//...
</beans:bean>
With the above configuration, I enable the CSRF security only for POST|PUT|DELETE requests of all URLs which start with /rest/.
Explicitly disable for specific url patterns and enable for some url patterns.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#EnableWebSecurity
public class SecurityConfig {
#Configuration
#Order
public static class GeneralWebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/rest/**").and()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/home/**","/search/**","/geo/**").authenticated().and().csrf()
.and().formLogin().loginPage("/login")
.usernameParameter("username").passwordParameter("password")
.and().exceptionHandling().accessDeniedPage("/error")
.and().sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);
}
}
}
<http ...>
<csrf request-matcher-ref="csrfMatcher"/>
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
...
</http>
<b:bean id="csrfMatcher"
class="AndRequestMatcher">
<b:constructor-arg value="#{T(org.springframework.security.web.csrf.CsrfFilter).DEFAULT_CSRF_MATCHER}"/>
<b:constructor-arg>
<b:bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
<b:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
<b:constructor-arg value="/chat/**"/>
</b:bean>
</b:bean>
</b:constructor-arg>
</b:bean>
mean of
http
.csrf()
// ignore our stomp endpoints since they are protected using Stomp headers
.ignoringAntMatchers("/chat/**")
example from :
https://docs.spring.io/spring-security/site/docs/4.1.x/reference/htmlsingle/
Use security="none".
for e.g in spring-security-config.xml
<security:intercept-url pattern="/*/verify" security="none" />

Resources