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.

<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:



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 istio.io) I would like to share with you a sample repo to start and help you continue your jou...