Skip to main content

Creating your own OAuth2 server and clients using spring security - part 2

so we continue our OAuth2 journey, in this part I plan to explain the entries we have in spring-security.xml

lets start..

first part in the xml file is this:
<oauth:resource-server id="resourceServerFilter"
resource-id="custom_app" token-services-ref="tokenServices" />
this defines that this is a resource server (secured information source) for OAuth2, which means this server will be accessed by OAuth2 clients to get infromation/data from.

client-details-service-ref="clientDetails" token-services-ref="tokenServices"
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
 this part means that we want to create an authorization server that supports the listed OAuth2 flows:
1- authorization code
2- implicit
3- referesh token

OAuth2 is designed to support multiple use cases that clients may need, for example a 3rd party application may want to access data on our server about some user, we don't want our user to give his password to that 3rd party app, we want our user to login on our web interface and then we will give that application a temporary access to the user data [authorization-code flow]

but if we want the user to login to one of our trusted applications we can simply ask him for his user name and password once then generate a token to use it when we need [password flow]

I don't know about all flows but adding them here won't harm us for now.

let's continue on the other xml entries:

<!-- clients service -->
<oauth:client-details-service id="clientDetails">
<oauth:client client-id="mobile_iphone"
authorized-grant-types="password,refresh_token,implicit" secret="custom_app_iphone"
authorities="ROLE_CLIENT" />
<oauth:client client-id="mobile_android"
authorized-grant-types="password,refresh_token,implicit" secret="custom_android"
authorities="ROLE_CLIENT" />
<oauth:client client-id="web_liferay"
authorized-grant-types="password,refresh_token,implicit" secret="custom_liferay"
authorities="ROLE_CLIENT" />
 the above segment defines the list of clients that are recognized by our oauth2 server to request access on our users data, in large scale applications where there are many 3rd party clients it's better to use db to store these, but for our case it's enough to hard code them in our xml file.
here we have 3 applications : iphone app, web app, android app that will communicate with our server.

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

 the above are handlers to parse expressions used in the configuration here and in the application ( security annotation as we will see later)

Token configurations
<bean id="tokenStore" class="" />
<bean id="jdbcTokenStore"
<constructor-arg ref="secDataSource" />
<bean id="tokenServices"
<property name="tokenStore" ref="jdbcTokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetails" />

In this part we configure the token storage to use our db and configure the token service to use our store.

<!-- token obtaining URL configurations -->
<http pattern="/oauth/token/**" create-session="stateless"
<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"
<access-denied-handler ref="oauthAccessDeniedHandler" />

this part configures the URL the clients will  call to obtain a token and it's security conditions such as only authenticated clients are allowed to request tokens, this is required to protect the token endpoint since it's not implicitly protected by spring security oauth

<!-- OAuth 2 related beans -->
<bean id="oauthAccessDeniedHandler"
class="" />
<bean id="clientCredentialsTokenEndpointFilter"
<property name="authenticationManager" ref="clientAuthenticationManager" />

The above two beans are required for other beans, the access denied handler will send status 403 in case a user tries to access a resource that he can't access

the second bean is responsible to authenticate clients using request parameters.

<bean id="accessDecisionManager" class=""
<bean class="" />
<bean class="" />
<!-- required to use ACL expressions like : hasRole('..') -->
<bean class="" />
<bean class="" />

this bean is responsible to decide, based on the listed voters to allow or disallow user to access the requested resource based on the result of each voter.

<!-- Entry points -->
<bean id="oauthAuthenticationEntryPoint"
<property name="realmName" value="custom_app" />
<bean id="clientAuthenticationEntryPoint"
<property name="realmName" value="custom_app/client" />
<property name="typeName" value="Basic" />
<!-- User approval handler -->
<bean id="userApprovalHandler"
<property name="tokenServices" ref="tokenServices" />
the above beans are piping beans required by spring security

<!-- ========================= OAuth protected urls config ============================== -->
<http pattern="/ws/(.*)" request-matcher="regex"
create-session="never" use-expressions="true" entry-point-ref="oauthAuthenticationEntryPoint"
<sec:anonymous enabled="true" />
<intercept-url pattern="/ws/(.*)\?(wsdl|xsd)(.*)"
access="permitAll" />
<!--<intercept-url pattern="/ws/(.*)" access="hasRole('ROLE_USER')" /> -->
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
<http pattern="/rest/eidentity/**" security="none"
xmlns="" />
<http pattern="/rest/**" authentication-manager-ref="clientAuthenticationManager"
create-session="never" entry-point-ref="oauthAuthenticationEntryPoint"
<anonymous enabled="false" />
<intercept-url pattern="/rest/**" access="ROLE_USER" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />

this part is where you list your protected URLs and what is the security requirements for each of them, for example here we have set a security on our web services API to allow unauthenticated users to access the wsdl/xsd documents 

In webservices unlike rest, each web method doesn't have a single url, which prevents us from specifying security here and to workaround that we can use the security annotations above each method

for rest resources (in this example I have an identity API responsible for login, registration, change password etc..) we allowed all APIs in this service to be accessible by any user

while we protected all other 'rest/**' services URLs to have at least ROLE_USER
note: the patterns are validated against from top to bottom

<bean id="clientDetailsUserService"
<constructor-arg ref="clientDetails" />
<authentication-manager id="clientAuthenticationManager"
<authentication-provider user-service-ref="clientDetailsUserService" />
<authentication-manager alias="authenticationManager"
<authentication-provider ref="customAuthenticationProvider"></authentication-provider>
<user-service id="userDetailsService">
<user name="user" password="password" authorities="ROLE_USER" />
<bean id="customAuthenticationProvider"
class="com.blabadi.sec.oauth.provider.CustomAuthenticationProvider" />
this part is related to spring security, we define our authentication beans for both: clients (3rd party applications) and users (resource owners)

each one of these parties has it's own users service and authentication manager and authentication provider

Note you can have multiple authentication providers for same authentication managers and they will all be called in sequence until the first one to success or all fail.

Enable Standard Pre/Post annotations
====================================== -->
<!--you could also wire in the expression handler up at the layer of the
http filters. See -->
<sec:expression-handler ref="oauthExpressionHandler"  />
the last part is to allow us to use the Pre & Post annotations in security, we will need these in case we want to annotate specific methods, in our case they will be web services methods since we can't specify the URLs, example:


Popular posts from this blog

Android RecyclerView - Adding Empty View

So RecyclerView was introduced to replace List view and it's optimized to reuse existing views and so it's faster and more efficient as stated in the documentation:

While using it, I faced the issue of missing a useful functionality that is implemented in ListView.
that feature is setting an empty view in case there was no records.

In ListView it was as simple as this

View emptyView = findViewById(;
ListView  myList = ....

but this method doesn't exist for recycler view so we need a work around until android team fixes this.

and here are the screen shots of both list view and recycler view fix

List view :

Recycler view :

here is how I fixed it:

here is the content of empty_view, it can be anything.


Android - Multiple themes for one application

Sometimes you want to have multiple themes for your app
one strong example is having the ability to switch between dark and light themes because during night, a white bright screen can really be annoying for users eyes

Android will do most of the work for you but it may be required to change icons between themes to fit colors
In this blog I'll show a simple app with both dark and light themes and how to change icons without having to do that from code and keep things clean and centralized.
first of all let's create our activity, it will look something like this :

In /rest/values/styles.xml, we inherit Theme.AppCompat
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    <style name="AppBaseTheme" parent="Theme.AppCompat">
            Theme customizations available in newer API levels can go in

Creating your own OAuth2 server and clients using spring security - part 1

In this series of posts, I'll try to put together a simple working example on how to create your own OAuth2 server.

if you want to know more on OAuth2 and when to use it as authentication and authorization protocol then you can search about it on google and i'll put some URLs later.

Now I assume you are familiar with java web applications using Spring and maven.

to get started we need to create the server side with all dependencies required and i'll list them here, i'll use maven 2 to ease downloading dependencies for us.


1- Create new maven project with arch type webapp:

2- Add the required depenedencies for spring, spring security, spring-oauth2, hibernate & other libraries (required for this tutorial only you can use other libraries if you like)

3- I used hibernate to automate the creation of the schema required by spring OAuth2 to manage tokens (it's required to have schema created in db if you a…