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.

<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>
 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
etc..

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" />
</oauth:client-details-service>
 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="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />
-->
<bean id="jdbcTokenStore"
class="org.springframework.security.oauth2.provider.token.JdbcTokenStore">
<constructor-arg ref="secDataSource" />
</bean>
<bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="jdbcTokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetails" />
</bean>

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"
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 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="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
</bean>

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="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" />
<!-- required to use ACL expressions like : hasRole('..') -->
<bean class="org.springframework.security.web.access.expression.WebExpressionVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>

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"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="custom_app" />
</bean>
<bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="custom_app/client" />
<property name="typeName" value="Basic" />
</bean>
<!-- User approval handler -->
<bean id="userApprovalHandler"
class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
<property name="tokenServices" ref="tokenServices" />
</bean>
the above beans are piping beans required by spring security

<!-- ========================= OAuth protected urls config ============================== -->
<http pattern="/ws/(.*)" request-matcher="regex"
authentication-manager-ref="clientAuthenticationManager"
create-session="never" use-expressions="true" entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
xmlns="http://www.springframework.org/schema/security">
<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>
<http pattern="/rest/eidentity/**" security="none"
xmlns="http://www.springframework.org/schema/security" />
<http pattern="/rest/**" authentication-manager-ref="clientAuthenticationManager"
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/**" access="ROLE_USER" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

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"
class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<authentication-manager id="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>
<authentication-manager alias="authenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider ref="customAuthenticationProvider"></authentication-provider>
<!-- TODO: FOR TEST ONLY !! REMOVE IN PRODUCTION ENVIRONMENT -->
<authentication-provider>
<user-service id="userDetailsService">
<user name="user" password="password" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<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
====================================== -->
<sec:global-method-security
pre-post-annotations="enabled"
proxy-target-class="true">
<!--you could also wire in the expression handler up at the layer of the
http filters. See https://jira.springsource.org/browse/SEC-1452 -->
<sec:expression-handler ref="oauthExpressionHandler"  />
</sec:global-method-security> 
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:



Comments

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:

https://developer.android.com/training/material/lists-cards.html

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(R.id.mylist_empty_view);
ListView  myList = ....
myList.setEmptyView(emptyView);

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.



Enjoy.

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
            res/values…

Microservices 101, Docker & spring boot sample [Windows 10, home]

This is a very simplistic article :) if you are looking for a deep dive in microservices, see my state-of-the-art microservices full archeticture here:http://dev.basharallabadi.com/2019/03/part-1-spring-state-of-art.html What are micro services? It's an architectural model for web services that basically requires each service** to be completely independent and loosely coupled from other consumer services, or services that it depends on. and it's not a new idea but it's catching pace in today large scale web applications.


**(by service we mean a component that controls and implements the business logic in a self contained manner, like orders service, products catalog service, accounts management service, all of these have their domain and can be clearly separated) 

 Why micro services emerged ?
1- Easy to scale services: if you have a single application and all the services share the same code base and war (package) then if you receive high demand on one of the services…