Sunday, August 31, 2014

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:

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Istio —simple fast way to start

istio archeticture (source I would like to share with you a sample repo to start and help you continue your jou...