Java-Based Spring Security Configuration: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * Spring Security Concepts")
 
 
(41 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
* [https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html WebSecurityConfigurerAdapter javadoc]
=Internal=
=Internal=


* [[Spring_Security_Concepts#Security_Configuration|Spring Security Concepts]]
* [[Spring_Security_Concepts#Security_Configuration|Spring Security Concepts]]
=Overview=
This article describes [[Spring_Dependency_Injection_and_Inversion_of_Control_Container_Concepts#Java-based_Configuration|Java-based]] Spring Security configuration. This method can be used to configure the following security aspects:
* one of the available [[Spring_Security_Concepts#User_Store|user stores]], such as the [[Spring_Security_Concepts#In-Memory_User_Store|in-memory user store]], [[Spring_Security_Concepts#JDBC-based_User_Store|JDBC user store]] or [[Spring_Security_Concepts#LDAP-Backed_User_Store|LDAP-backed user store]], or alternatively, a [[Spring_Security_Concepts#Custom_User_Detail_Service|custom user details service]].
* [[#Securing_Web_Requests|what web requests should be secured]].
=Configuration Class=
<syntaxhighlight lang='java'>
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    ...
  }
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    ...
  }
}
</syntaxhighlight>
=Security Configuration=
[https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html WebSecurityConfigurerAdapter] and  [https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/builders/HttpSecurity.html HttpSecurity] can be used to configure security aspects such as [[#Securing_Requests|what security conditions should be met before allowing a request to be served]], [[#Custom_Login_Page|custom login page]], how to [[#Logging_Out|log out]], [[#Configure_Cross-Site_Request_Forgery_Protection|cross-site request forgery protection]]:
<syntaxhighlight lang='java'>
@Override
protected void configure(HttpSecurity http) throws Exception {
  ...
}
</syntaxhighlight>
==Securing Requests==
<syntaxhighlight lang='java'>
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().
  antMatchers("/design", "/orders").hasRole("ROLE_USER").
  antMatchers("/", "/**").permitAll(); 
}
</syntaxhighlight>
The call to <tt>authorizeRequests()</tt> returns an [https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry.html ExpressionInterceptUrlRegistry] instance that can be used to specify URL paths and patterns and the security requirements for those paths. The order of the rule declaration is important: security rules declared first take precedence over those declared lower down. Methods to declare security requirements:
* <tt>access(String)</tt> allows access if the given SpEL expression evaluates to true.
* <tt>anonymous()</tt> allows access to anonymous users.
* <tt>authenticated()</tt> allows access to authenticated users.
* <tt>denyAll()</tt> denies access unconditionally.
* <tt>fullyAuthenticated()</tt> allows access if the. user is fully authenticated (not remembered).
* <tt>hasAnyAuthority(String ...)</tt> allows access if the user has any of the given authorities.
* <tt>hasAnyRole(String ...)</tt> allows access if the user has any of the given roles.
* <tt>hasAuthority(String)</tt> allows access if the user has the given authority.
* <tt>hasIpAddress(String)</tt> allows access if the request comes from the given IP address.
* <tt>hasRole(String)</tt> allows access if the user has the given role.
* <tt>not()</tt> negates the access of any of the other access methods.
* <tt>permitAll()</tt> allows access unconditionally.
* <tt>rememberMe()</tt> allows access for users who are authenticated via remember-me.
==Custom Login Page==
<syntaxhighlight lang='java'>
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
  ...
  and().formLogin().
      loginPage("/login").
      loginProcessingUrl("/authenticate").
      usernameParameter("user").
      passwordParameter("password");
}
</syntaxhighlight>
The <tt>and()</tt> method signifies that you're finished with the authorization configuration and are ready to apply some additional configuration. In this case, the path to the login page is installed. When Spring Security determines that the user is unauthenticated and needs to log in, it will redirect the user to this path.
A successful login will take the user directly to the page they were navigating when Spring Security determined that they need to log in. This cam be changed with <tt>defaultSuccessUrl("/...")</tt>.
==Logging Out==
<syntaxhighlight lang='java'>
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
  ...
  and().logout().
      logoutSuccessUrl("/");
}
</syntaxhighlight>
This sets up a security filter that intercepts POST requests to "/logout". A logout form is needed to trigger that POST request:
<syntaxhighlight lang='html'>
<form method="POST" th:action="@{/logout}">
  <input type="submit" value="Logout"/>
</form>
</syntaxhighlight>
==Configure Cross-Site Request Forgery Protection==
{{Internal|Cross-Origin Resource Sharing|Cross-Origin Resource Sharing}}
{{Internal|Spring and Cross-Site Request Forgery|Cross-Site Request Forgery}}

Latest revision as of 01:44, 18 November 2018

External

Internal

Overview

This article describes Java-based Spring Security configuration. This method can be used to configure the following security aspects:

Configuration Class

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    ...
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    ...
  }
}

Security Configuration

WebSecurityConfigurerAdapter and HttpSecurity can be used to configure security aspects such as what security conditions should be met before allowing a request to be served, custom login page, how to log out, cross-site request forgery protection:

@Override
protected void configure(HttpSecurity http) throws Exception {
  ...
}

Securing Requests

@Override
protected void configure(HttpSecurity http) throws Exception {
 http.authorizeRequests().
   antMatchers("/design", "/orders").hasRole("ROLE_USER").
   antMatchers("/", "/**").permitAll();  
}

The call to authorizeRequests() returns an ExpressionInterceptUrlRegistry instance that can be used to specify URL paths and patterns and the security requirements for those paths. The order of the rule declaration is important: security rules declared first take precedence over those declared lower down. Methods to declare security requirements:

  • access(String) allows access if the given SpEL expression evaluates to true.
  • anonymous() allows access to anonymous users.
  • authenticated() allows access to authenticated users.
  • denyAll() denies access unconditionally.
  • fullyAuthenticated() allows access if the. user is fully authenticated (not remembered).
  • hasAnyAuthority(String ...) allows access if the user has any of the given authorities.
  • hasAnyRole(String ...) allows access if the user has any of the given roles.
  • hasAuthority(String) allows access if the user has the given authority.
  • hasIpAddress(String) allows access if the request comes from the given IP address.
  • hasRole(String) allows access if the user has the given role.
  • not() negates the access of any of the other access methods.
  • permitAll() allows access unconditionally.
  • rememberMe() allows access for users who are authenticated via remember-me.

Custom Login Page

@Override
protected void configure(HttpSecurity http) throws Exception {
 http.
   ...
   and().formLogin().
      loginPage("/login").
      loginProcessingUrl("/authenticate").
      usernameParameter("user").
      passwordParameter("password");
}

The and() method signifies that you're finished with the authorization configuration and are ready to apply some additional configuration. In this case, the path to the login page is installed. When Spring Security determines that the user is unauthenticated and needs to log in, it will redirect the user to this path.

A successful login will take the user directly to the page they were navigating when Spring Security determined that they need to log in. This cam be changed with defaultSuccessUrl("/...").

Logging Out

@Override
protected void configure(HttpSecurity http) throws Exception {
 http.
   ...
   and().logout().
      logoutSuccessUrl("/");
}

This sets up a security filter that intercepts POST requests to "/logout". A logout form is needed to trigger that POST request:

<form method="POST" th:action="@{/logout}">
  <input type="submit" value="Logout"/>
</form>

Configure Cross-Site Request Forgery Protection

Cross-Origin Resource Sharing
Cross-Site Request Forgery