Spring Rest service security with OAUTH – XML


Lets discuss Spring Rest service security with OAuth using XML configuration


We have learned about securing Rest services and consuming secured Rest services using Spring Security in spring security rest service article.

In this article, we will learn about the same using OAuth instead of Spring security.

If you are completely new to OAuth then I would strongly recommend reading OAUTH overview article before going through this article.


Lets implement the same step by step

Create a new Maven Web project in eclipse (Refer Spring MVC Hello World project for the same)

Project structure


oauth_xml_config_proj_structure

Step 1

Update pom.xml with below dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.     <groupId>SpringRestServiceSecurityOauth</groupId>
  5.     <artifactId>SpringRestServiceSecurityOauth</artifactId>
  6.     <packaging>war</packaging>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <name>SpringRestServiceSecurityOauth Maven Webapp</name>
  9.     <url>http://maven.apache.org</url>
  10.     <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.         <spring-security.version>3.2.7.RELEASE</spring-security.version>
  13.     </properties>
  14.     <dependencies>
  15.         <dependency>
  16.             <groupId>junit</groupId>
  17.             <artifactId>junit</artifactId>
  18.             <version>3.8.1</version>
  19.             <scope>test</scope>
  20.         </dependency>
  21.         <dependency>
  22.             <groupId>org.springframework</groupId>
  23.             <artifactId>spring-core</artifactId>
  24.             <version>${org.springframework.version}</version>
  25.         </dependency>
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-web</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.  
  32.         <dependency>
  33.             <groupId>org.springframework</groupId>
  34.             <artifactId>spring-webmvc</artifactId>
  35.             <version>${org.springframework.version}</version>
  36.         </dependency>
  37.         <!-- Jackson JSON -->
  38.         <dependency>
  39.             <groupId>com.fasterxml.jackson.core</groupId>
  40.             <artifactId>jackson-databind</artifactId>
  41.             <version>2.8.5</version>
  42.         </dependency>
  43.  
  44.         <dependency>
  45.             <groupId>org.springframework.security</groupId>
  46.             <artifactId>spring-security-core</artifactId>
  47.             <version>${spring-security.version}</version>
  48.         </dependency>
  49.         <dependency>
  50.             <groupId>org.springframework.security</groupId>
  51.             <artifactId>spring-security-web</artifactId>
  52.             <version>${spring-security.version}</version>
  53.         </dependency>
  54.         <dependency>
  55.             <groupId>org.springframework.security</groupId>
  56.             <artifactId>spring-security-config</artifactId>
  57.             <version>${spring-security.version}</version>
  58.         </dependency>
  59.         <!--  Spring OAUTH dependency -->
  60.         <dependency>
  61.             <groupId>org.springframework.security.oauth</groupId>
  62.             <artifactId>spring-security-oauth2</artifactId>
  63.             <version>2.0.12.RELEASE</version>
  64.         </dependency>
  65.  
  66. <dependency>
  67.     <groupId>mysql</groupId>
  68.     <artifactId>mysql-connector-java</artifactId>
  69.     <version>5.1.6</version>
  70. </dependency>
  71.  
  72. <dependency>
  73.     <groupId>org.springframework</groupId>
  74.     <artifactId>spring-jdbc</artifactId>
  75.     <version>4.3.5.RELEASE</version>
  76. </dependency>
  77.  
  78.     </dependencies>
  79.     <build>
  80.         <finalName>SpringRestServiceSecurityOauth</finalName>
  81.     </build>
  82. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>SpringRestServiceSecurityOauth</groupId>
	<artifactId>SpringRestServiceSecurityOauth</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringRestServiceSecurityOauth Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
		<spring-security.version>3.2.7.RELEASE</spring-security.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<!-- Jackson JSON -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.5</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<version>${spring-security.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${spring-security.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring-security.version}</version>
		</dependency>
		<!--  Spring OAUTH dependency -->
		<dependency>
			<groupId>org.springframework.security.oauth</groupId>
			<artifactId>spring-security-oauth2</artifactId>
			<version>2.0.12.RELEASE</version>
		</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.5.RELEASE</version>
</dependency>

	</dependencies>
	<build>
		<finalName>SpringRestServiceSecurityOauth</finalName>
	</build>
</project>


We have added dependencies for Spring mvc ,spring security ,mysql,spring jdbc, Jackson and Junit in the above pom file.

Step 2

Update web.xml file with Dispatcher servlet and spring security filter

we have defined a dispatcher servlet in web.xml and mapped it by the URL pattern “/”

So just like any other servlet in web application,any request matching with the given pattern i.e “/” will be redirected to “Dispatcher servlet”.

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.   <display-name>Archetype Created Web Application</display-name>
  5.  
  6.    <servlet>
  7.         <servlet-name>mvc-dispatcher</servlet-name>
  8.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  9.         <init-param>
  10.             <param-name>contextConfigLocation</param-name>
  11.             <param-value>
  12.             /WEB-INF/spring-beans.xml,
  13.             /WEB-INF/spring-security.xml
  14.         </param-value>
  15.         </init-param>
  16.         <load-on-startup>1</load-on-startup>
  17.     </servlet>
  18.     <servlet-mapping>
  19.         <servlet-name>mvc-dispatcher</servlet-name>
  20.         <url-pattern>/</url-pattern>
  21.     </servlet-mapping>
  22.  
  23.     <listener>
  24.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  25.     </listener>
  26.  
  27.     <!-- Loads Spring Security configuration file -->
  28.     <context-param>
  29.         <param-name>contextConfigLocation</param-name>
  30.         <param-value>
  31.             /WEB-INF/spring-beans.xml,
  32.             /WEB-INF/spring-security.xml
  33.         </param-value>
  34.     </context-param>
  35.  
  36.     <!-- Spring Security filter -->
  37.     <filter>
  38.         <filter-name>springSecurityFilterChain</filter-name>
  39.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  40.     </filter>
  41.  
  42.     <filter-mapping>
  43.         <filter-name>springSecurityFilterChain</filter-name>
  44.         <url-pattern>/*</url-pattern>
  45.     </filter-mapping>
  46.    
  47. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  
   <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
            /WEB-INF/spring-beans.xml,
            /WEB-INF/spring-security.xml
        </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- Loads Spring Security configuration file -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-beans.xml,
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>
 
    <!-- Spring Security filter -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
 
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
</web-app>


We have provided the spring configuration file name to create and load the spring beans while starting the server.

Also we have provided Spring security config file to load the security related configuration.

we have also added filter for spring security which will delegate the request for authentication before processing the request.

Step 3

Create a Spring beans config file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb" />
  14.     <mvc:annotation-driven />
  15.      
  16. </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
    <context:component-scan base-package="com.kb" />
    <mvc:annotation-driven />
     
</beans>

Step 4

Create the spring security config file

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
  4.  xmlns:context="http://www.springframework.org/schema/context"
  5.  xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.  xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
  7.  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  8.  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
  9.  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  10.  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd ">
  11.  
  12.  <!-- This is default url provided by spring to get the tokens(access and refresh) from OAuth -->
  13.  <http pattern="/oauth/token" create-session="stateless"
  14.   authentication-manager-ref="clientAuthenticationManager"
  15.   xmlns="http://www.springframework.org/schema/security">
  16.   <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
  17.   <anonymous enabled="false" />
  18.   <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
  19.  
  20.   <!-- include this only if you need to authenticate clients via request
  21.    parameters -->
  22.    
  23.   <custom-filter ref="clientCredentialsTokenEndpointFilter"
  24.    after="BASIC_AUTH_FILTER" />
  25.   <access-denied-handler ref="oauthAccessDeniedHandler" />
  26.  </http>
  27.  
  28.  <!-- This is where we tells spring security what URL should be protected
  29.   and what roles have access to them -->
  30.  
  31.  <http pattern="/rest/api/**" create-session="never"
  32.   entry-point-ref="oauthAuthenticationEntryPoint"
  33.   access-decision-manager-ref="accessDecisionManager"
  34.   xmlns="http://www.springframework.org/schema/security">
  35.   <anonymous enabled="false" />
  36.   <intercept-url pattern="/rest/api/**" access="ROLE_OAUTH_CLIENT" />
  37.   <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
  38.   <access-denied-handler ref="oauthAccessDeniedHandler" />
  39.  </http>
  40.  
  41.  
  42.  <bean id="oauthAuthenticationEntryPoint"
  43.   class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
  44.   <property name="realmName" value="sample" />
  45.  </bean>
  46.  
  47.  <bean id="clientAuthenticationEntryPoint"
  48.   class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
  49.   <property name="realmName" value="sample/oauthClient" />
  50.   <property name="typeName" value="Basic" />
  51.  </bean>
  52.  
  53.  <bean id="oauthAccessDeniedHandler"
  54.   class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
  55.  
  56.  <bean id="clientCredentialsTokenEndpointFilter"
  57.   class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
  58.   <property name="authenticationManager" ref="clientAuthenticationManager" />
  59.  </bean>
  60.  
  61.  <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
  62.   xmlns="http://www.springframework.org/schema/beans">
  63.   <constructor-arg>
  64.    <list>
  65.     <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
  66.     <bean class="org.springframework.security.access.vote.RoleVoter" />
  67.     <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
  68.    </list>
  69.   </constructor-arg>
  70.  </bean>
  71.  
  72.  <authentication-manager id="clientAuthenticationManager"
  73.   xmlns="http://www.springframework.org/schema/security">
  74.   <authentication-provider user-service-ref="clientDetailsUserService" />
  75.  </authentication-manager>
  76.  
  77.  
  78.  <!-- Here we have hard-coded user name and password details. We can replace this with a user defined service to get users
  79.   credentials from DB -->
  80.  <authentication-manager alias="authenticationManager"
  81.   xmlns="http://www.springframework.org/schema/security">
  82.   <authentication-provider>
  83.    <user-service id="userDetailsService">
  84.     <user name="kb" password="kb@1234" authorities="ROLE_OAUTH_CLIENT" />
  85.     <user name="raj" password="raj@1234" authorities="ROLE_OAUTH_CLIENT" />
  86.    </user-service>
  87.   </authentication-provider>
  88.  </authentication-manager>
  89.  
  90.  <bean id="clientDetailsUserService"
  91.   class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
  92.   <constructor-arg ref="clientDetails" />
  93.  </bean>
  94.  
  95.  
  96.  <!--We have used JDBC tokenstore to store the tokens, we can use In Memory token store for development purpose -->
  97.  <bean id="tokenStore"
  98.   class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
  99.   <constructor-arg ref="jdbcTemplate" />
  100.   </bean>
  101.  
  102.   <bean id="jdbcTemplate"
  103.      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  104.       <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  105.       <property name="url" value="jdbc:mysql://localhost:3306/oauthdb"/>
  106.    <property name="username" value="root"/>
  107.    <property name="password" value="root"/>
  108.   </bean>
  109.  
  110.  <!-- tokenServices bean for defining token based configurations, token validity etc -->
  111.  <bean id="tokenServices"
  112.   class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
  113.   <property name="tokenStore" ref="tokenStore" />
  114.   <property name="supportRefreshToken" value="true" />
  115.   <property name="accessTokenValiditySeconds" value="120" />
  116.   <property name="clientDetailsService" ref="clientDetails" />
  117.  </bean>
  118.  
  119. <bean id="requestFactory"
  120.         class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
  121.         <constructor-arg name="clientDetailsService" ref="clientDetails" />
  122.     </bean>
  123.  
  124. <bean id="userApprovalHandler" class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
  125.     <property name="tokenStore" ref="tokenStore"/>
  126.     <property name="requestFactory" ref="requestFactory" />
  127. </bean>
  128.  
  129.  <oauth:authorization-server
  130.   client-details-service-ref="clientDetails" token-services-ref="tokenServices"
  131.   user-approval-handler-ref="userApprovalHandler">
  132.   <oauth:authorization-code />
  133.   <oauth:implicit />
  134.   <oauth:refresh-token />
  135.   <oauth:client-credentials />
  136.   <oauth:password />
  137.  </oauth:authorization-server>
  138.  
  139.  <oauth:resource-server id="resourceServerFilter"
  140.   resource-id="sample" token-services-ref="tokenServices" />
  141.  
  142.  <oauth:client-details-service id="clientDetails">
  143.   <!-- client -->
  144.   <oauth:client client-id="trusted client"
  145.    authorized-grant-types="password,refresh_token,client_credentials"
  146.    authorities="ROLE_OAUTH_CLIENT" scope="read,write,trust" secret="secret" />
  147.  
  148.   <oauth:client client-id="trusted client with secret"
  149.    authorized-grant-types="password,authorization_code,refresh_token,implicit"
  150.    secret="somesecret" authorities="ROLE_OAUTH_CLIENT" />
  151.  
  152.  </oauth:client-details-service>
  153.  
  154.  <sec:global-method-security
  155.   pre-post-annotations="enabled" proxy-target-class="true">
  156.  
  157.   <sec:expression-handler ref="oauthExpressionHandler" />
  158.  </sec:global-method-security>
  159.  
  160.  <oauth:expression-handler id="oauthExpressionHandler" />
  161.  <oauth:web-expression-handler id="oauthWebExpressionHandler" />
  162. </beans>
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  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.1.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd ">

 <!-- This is default url provided by spring to get the tokens(access and refresh) from OAuth -->
 <http pattern="/oauth/token" create-session="stateless"
  authentication-manager-ref="clientAuthenticationManager"
  xmlns="http://www.springframework.org/schema/security">
  <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
  <anonymous enabled="false" />
  <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
  
  <!-- include this only if you need to authenticate clients via request 
   parameters -->
   
  <custom-filter ref="clientCredentialsTokenEndpointFilter"
   after="BASIC_AUTH_FILTER" />
  <access-denied-handler ref="oauthAccessDeniedHandler" />
 </http>

 <!-- This is where we tells spring security what URL should be protected 
  and what roles have access to them -->
  
 <http pattern="/rest/api/**" create-session="never"
  entry-point-ref="oauthAuthenticationEntryPoint"
  access-decision-manager-ref="accessDecisionManager"
  xmlns="http://www.springframework.org/schema/security">
  <anonymous enabled="false" />
  <intercept-url pattern="/rest/api/**" access="ROLE_OAUTH_CLIENT" />
  <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
  <access-denied-handler ref="oauthAccessDeniedHandler" />
 </http>


 <bean id="oauthAuthenticationEntryPoint"
  class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
  <property name="realmName" value="sample" />
 </bean>

 <bean id="clientAuthenticationEntryPoint"
  class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
  <property name="realmName" value="sample/oauthClient" />
  <property name="typeName" value="Basic" />
 </bean>

 <bean id="oauthAccessDeniedHandler"
  class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

 <bean id="clientCredentialsTokenEndpointFilter"
  class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
  <property name="authenticationManager" ref="clientAuthenticationManager" />
 </bean>

 <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
  xmlns="http://www.springframework.org/schema/beans">
  <constructor-arg>
   <list>
    <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
    <bean class="org.springframework.security.access.vote.RoleVoter" />
    <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
   </list>
  </constructor-arg>
 </bean>

 <authentication-manager id="clientAuthenticationManager"
  xmlns="http://www.springframework.org/schema/security">
  <authentication-provider user-service-ref="clientDetailsUserService" />
 </authentication-manager>


 <!-- Here we have hard-coded user name and password details. We can replace this with a user defined service to get users
  credentials from DB -->
 <authentication-manager alias="authenticationManager"
  xmlns="http://www.springframework.org/schema/security">
  <authentication-provider>
   <user-service id="userDetailsService">
    <user name="kb" password="kb@1234" authorities="ROLE_OAUTH_CLIENT" />
    <user name="raj" password="raj@1234" authorities="ROLE_OAUTH_CLIENT" />
   </user-service>
  </authentication-provider>
 </authentication-manager>

 <bean id="clientDetailsUserService"
  class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
  <constructor-arg ref="clientDetails" />
 </bean>


 <!--We have used JDBC tokenstore to store the tokens, we can use In Memory token store for development purpose -->
 <bean id="tokenStore"
  class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
  <constructor-arg ref="jdbcTemplate" />
  </bean>
  
  <bean id="jdbcTemplate"
     class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/oauthdb"/>
   <property name="username" value="root"/>
   <property name="password" value="root"/>
  </bean>

 <!-- tokenServices bean for defining token based configurations, token validity etc -->
 <bean id="tokenServices"
  class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
  <property name="tokenStore" ref="tokenStore" />
  <property name="supportRefreshToken" value="true" />
  <property name="accessTokenValiditySeconds" value="120" />
  <property name="clientDetailsService" ref="clientDetails" />
 </bean>

<bean id="requestFactory"
		class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
		<constructor-arg name="clientDetailsService" ref="clientDetails" />
	</bean>

<bean id="userApprovalHandler" class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
    <property name="tokenStore" ref="tokenStore"/>
    <property name="requestFactory" ref="requestFactory" />
</bean>

 <oauth:authorization-server
  client-details-service-ref="clientDetails" token-services-ref="tokenServices"
  user-approval-handler-ref="userApprovalHandler">
  <oauth:authorization-code />
  <oauth:implicit />
  <oauth:refresh-token />
  <oauth:client-credentials />
  <oauth:password />
 </oauth:authorization-server>

 <oauth:resource-server id="resourceServerFilter"
  resource-id="sample" token-services-ref="tokenServices" />

 <oauth:client-details-service id="clientDetails">
  <!-- client -->
  <oauth:client client-id="trusted client"
   authorized-grant-types="password,refresh_token,client_credentials"
   authorities="ROLE_OAUTH_CLIENT" scope="read,write,trust" secret="secret" />

  <oauth:client client-id="trusted client with secret"
   authorized-grant-types="password,authorization_code,refresh_token,implicit"
   secret="somesecret" authorities="ROLE_OAUTH_CLIENT" />

 </oauth:client-details-service>

 <sec:global-method-security
  pre-post-annotations="enabled" proxy-target-class="true">
  
  <sec:expression-handler ref="oauthExpressionHandler" />
 </sec:global-method-security>

 <oauth:expression-handler id="oauthExpressionHandler" />
 <oauth:web-expression-handler id="oauthWebExpressionHandler" />
</beans>

In the above spring security xml file we have defined OAuth related configuration.

We have configured /oauth/token url for retrieving access and refresh token and configured authentication manager as clientAuthenticationManager

clientAuthenticationManager is defined as below

  1.  <authentication-manager id="clientAuthenticationManager"
  2.   xmlns="http://www.springframework.org/schema/security">
  3.   <authentication-provider user-service-ref="clientDetailsUserService" />
  4.  </authentication-manager>
 <authentication-manager id="clientAuthenticationManager"
  xmlns="http://www.springframework.org/schema/security">
  <authentication-provider user-service-ref="clientDetailsUserService" />
 </authentication-manager>


This is pointing to clientDetailsUserService bean which is defined as below

  1. <bean id="clientDetailsUserService"
  2.   class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
  3.   <constructor-arg ref="clientDetails" />
  4.  </bean>
<bean id="clientDetailsUserService"
  class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
  <constructor-arg ref="clientDetails" />
 </bean>


This is pointing to the actual client details service which is defined as below

  1.  <oauth:authorization-server
  2.   client-details-service-ref="clientDetails" token-services-ref="tokenServices"
  3.   user-approval-handler-ref="userApprovalHandler">
  4.   <oauth:authorization-code />
  5.   <oauth:implicit />
  6.   <oauth:refresh-token />
  7.   <oauth:client-credentials />
  8.   <oauth:password />
  9.  </oauth:authorization-server>
 <oauth:authorization-server
  client-details-service-ref="clientDetails" token-services-ref="tokenServices"
  user-approval-handler-ref="userApprovalHandler">
  <oauth:authorization-code />
  <oauth:implicit />
  <oauth:refresh-token />
  <oauth:client-credentials />
  <oauth:password />
 </oauth:authorization-server>


Here we have injected the token service to manage the refresh and access tokens.
Also defined possible Grant types in it.

we have defined token service bean with token details as below

  1. <bean id="tokenServices"
  2.   class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
  3.   <property name="tokenStore" ref="tokenStore" />
  4.   <property name="supportRefreshToken" value="true" />
  5.   <property name="accessTokenValiditySeconds" value="120" />
  6.   <property name="clientDetailsService" ref="clientDetails" />
  7.  </bean>
<bean id="tokenServices"
  class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
  <property name="tokenStore" ref="tokenStore" />
  <property name="supportRefreshToken" value="true" />
  <property name="accessTokenValiditySeconds" value="120" />
  <property name="clientDetailsService" ref="clientDetails" />
 </bean>

we have specified access token to be valid for 2 minutes.
We have also injected a tokenstore which will take care of storing the tokens.

we have defined tokenstore as JDBC token store as below

  1. <bean id="tokenStore"
  2.   class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
  3.   <constructor-arg ref="jdbcTemplate" />
  4.   </bean>
<bean id="tokenStore"
  class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
  <constructor-arg ref="jdbcTemplate" />
  </bean>

This will store the tokens in DB using JDBC and configuration for the JDBC is defined using JDBC template bean.

we have configured our rest service to be considered by OAuth using below tag

  1. <intercept-url pattern="/rest/api/**" access="ROLE_OAUTH_CLIENT" />
<intercept-url pattern="/rest/api/**" access="ROLE_OAUTH_CLIENT" />

This specifies that any URL with the pattern preceded by /rest/api will be intercepted by OAuth and Client should have the Role called ROLE_OAUTH_CLIENT to proceed further.

we have also defined authentication provider as user service with set of users along with their credentials and roles defined in it.

  1.  <authentication-provider>
  2.    <user-service id="userDetailsService">
  3.     <user name="kb" password="kb@1234" authorities="ROLE_OAUTH_CLIENT" />
  4.     <user name="raj" password="raj@1234" authorities="ROLE_OAUTH_CLIENT" />
  5.    </user-service>
  6.   </authentication-provider>
 <authentication-provider>
   <user-service id="userDetailsService">
    <user name="kb" password="kb@1234" authorities="ROLE_OAUTH_CLIENT" />
    <user name="raj" password="raj@1234" authorities="ROLE_OAUTH_CLIENT" />
   </user-service>
  </authentication-provider>

we are granting access to Rest services only for those users whose Role is ROLE_OAUTH_CLIENT as configured above.

Step 5

Execute below sql scripts(executed in MYSQL) to support JDBC Token store

  1. create table oauth_client_details (
  2.   client_id VARCHAR(256) PRIMARY KEY,
  3.   resource_ids VARCHAR(256),
  4.   client_secret VARCHAR(256),
  5.   scope VARCHAR(256),
  6.   authorized_grant_types VARCHAR(256),
  7.   web_server_redirect_uri VARCHAR(256),
  8.   authorities VARCHAR(256),
  9.   access_token_validity INTEGER,
  10.   refresh_token_validity INTEGER,
  11.   additional_information VARCHAR(4096),
  12.   autoapprove VARCHAR(256)
  13. );
  14.  
  15.  
  16. create table oauth_client_token (
  17.   token_id VARCHAR(256),
  18.   token BLOB,
  19.   authentication_id VARCHAR(256) PRIMARY KEY,
  20.   user_name VARCHAR(256),
  21.   client_id VARCHAR(256)
  22. );
  23.  
  24.  
  25. create table oauth_access_token (
  26.   token_id VARCHAR(256),
  27.   token BLOB,
  28.   authentication_id VARCHAR(256),
  29.   user_name VARCHAR(256),
  30.   client_id VARCHAR(256),
  31.   authentication BLOB,
  32.   refresh_token VARCHAR(256)
  33. );
  34.  
  35. create table oauth_refresh_token (
  36.   token_id VARCHAR(256),
  37.   token BLOB,
  38.   authentication BLOB
  39. );
  40.  
  41. create table oauth_code (
  42.   code VARCHAR(256), authentication BLOB
  43. );
  44.  
  45. create table oauth_approvals (
  46.     userId VARCHAR(256),
  47.     clientId VARCHAR(256),
  48.     scope VARCHAR(256),
  49.     status VARCHAR(10),
  50.     expiresAt TIMESTAMP,
  51.     lastModifiedAt TIMESTAMP
  52. );
  53.  
  54.  
  55. -- customized oauth_client_details table
  56. create table ClientDetails (
  57.   appId VARCHAR(256) PRIMARY KEY,
  58.   resourceIds VARCHAR(256),
  59.   appSecret VARCHAR(256),
  60.   scope VARCHAR(256),
  61.   grantTypes VARCHAR(256),
  62.   redirectUrl VARCHAR(256),
  63.   authorities VARCHAR(256),
  64.   access_token_validity INTEGER,
  65.   refresh_token_validity INTEGER,
  66.   additionalInformation VARCHAR(4096),
  67.   autoApproveScopes VARCHAR(256)
  68. );
create table oauth_client_details (
  client_id VARCHAR(256) PRIMARY KEY,
  resource_ids VARCHAR(256),
  client_secret VARCHAR(256),
  scope VARCHAR(256),
  authorized_grant_types VARCHAR(256),
  web_server_redirect_uri VARCHAR(256),
  authorities VARCHAR(256),
  access_token_validity INTEGER,
  refresh_token_validity INTEGER,
  additional_information VARCHAR(4096),
  autoapprove VARCHAR(256)
);


create table oauth_client_token (
  token_id VARCHAR(256),
  token BLOB,
  authentication_id VARCHAR(256) PRIMARY KEY,
  user_name VARCHAR(256),
  client_id VARCHAR(256)
);


create table oauth_access_token (
  token_id VARCHAR(256),
  token BLOB,
  authentication_id VARCHAR(256),
  user_name VARCHAR(256),
  client_id VARCHAR(256),
  authentication BLOB,
  refresh_token VARCHAR(256)
);

create table oauth_refresh_token (
  token_id VARCHAR(256),
  token BLOB,
  authentication BLOB
);

create table oauth_code (
  code VARCHAR(256), authentication BLOB
);

create table oauth_approvals (
	userId VARCHAR(256),
	clientId VARCHAR(256),
	scope VARCHAR(256),
	status VARCHAR(10),
	expiresAt TIMESTAMP,
	lastModifiedAt TIMESTAMP
);


-- customized oauth_client_details table
create table ClientDetails (
  appId VARCHAR(256) PRIMARY KEY,
  resourceIds VARCHAR(256),
  appSecret VARCHAR(256),
  scope VARCHAR(256),
  grantTypes VARCHAR(256),
  redirectUrl VARCHAR(256),
  authorities VARCHAR(256),
  access_token_validity INTEGER,
  refresh_token_validity INTEGER,
  additionalInformation VARCHAR(4096),
  autoApproveScopes VARCHAR(256)
);

Step 6

Create rest service which we want to secure

  1. package com.kb.rest.controllers;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8.  
  9. import com.kb.rest.model.User;
  10.  
  11. @Controller
  12. @RequestMapping("/rest/api")
  13. public class RestController {
  14.  
  15.     @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
  16.     public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
  17.         User user = new User();
  18.         user.setId(id);
  19.         user.setName("John");
  20.         user.setAge(45);
  21.         return user;
  22.     }
  23. }
package com.kb.rest.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kb.rest.model.User;

@Controller
@RequestMapping("/rest/api")
public class RestController {

	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
	public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
		User user = new User();
		user.setId(id);
		user.setName("John");
		user.setAge(45);
		return user;
	}
}


we have exposed one method for retrieving the user based on id.

Step 7

Build and deploy the project

Step 8

Let’s access the rest service using Postman client

Access rest service without authentication info using below url

http://localhost:8080/SpringRestServiceSecurityOauth/rest/api/user/1

oauth_xml_config_no_auth_error

Select GET method

We can see that access is denied due to unauthorization as we are accessing the secured service without access token.

Let’s get the access token using below url

http://localhost:8080/SpringRestServiceSecurityOauth/oauth/token?grant_type=client_credentials

add user name and password in the header as shown below
Authrorization will be added to the header automatically

oauth_xml_config_get_access_token

We can see that access_token will expire in 119 seconds.

Now access the rest service using access token before it gets expired.

http://localhost:8080/SpringRestServiceSecurityOauth/rest/api/user/1?access_token=9409a4a0-0887-46f5-a36e-9b1de71699df

oauth_get_response_with_access_token

Note:
We will not get refresh token if the grant type is client_credentials and hence we are not getting refresh_token from OAuth.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on