Skip to main content

Spring Security OAuth2 + Spring Boot, minimalist working, extendable configuration - Part 1

Hi

been a while again..

today i'm back to write on how to write the simplest possible spring boot app protected with spring security oauth2, but i'll also make the project as a library jar that can be reused for any new projects to kick off faster.

 and it will be a simple ready to override functions that will let you focus on configuring only things that you need to worry about without having to worry about annotations or other spring security stuff.


Overview

Spring security oauth 2 has three main components :

a- Authorization server: to handle tokens/authroization codes and user approve/deny
b- Resource server: protects the actual apis that we want to be protected by oauth2
c- spring web security configs to manage users authentication

and as simple as it sounds to get these three in one simple hello world example required hours and hours of searching and debugging dont ask me why..


Pre Requests :
1- you know spring security & spring web security concepts and how to configure it like basic auth or form login


so without further due here are the three classes you will need to get oauth2 up and running :

1- Spring security:

https://github.com/blabadi/oauth2lw-parent/blob/master/oauth2lw-core/src/main/java/com/bashar/oauth2lw/core/SecurityConfig.java

this class extends the Spring web security configurer to allow us to set how we want to protect our authorization server, and to set up our users (Resource owners) store. here it's in memory but in your application you will need jdbc so you can just extend and override this.
by default this protects /oauth/authroize api with the default spring web security login form

when you need to override that form you should override this method :

protected void configure(HttpSecurity http)

and set the url of the login page of your choice using the usual spring web security configs.

2- Authroization server:

https://github.com/blabadi/oauth2lw-parent/blob/master/oauth2lw-core/src/main/java/com/bashar/oauth2lw/core/AuthorizationServer.java

here this configuration server has two main parts :

A-  configure(ClientDetailsServiceConfigurer clients)
this method configures the clients of our oauth2 resource, and clients in 90% of the cases in the world of oauth2 represents the 3rd party apps that want to access the resource owner data on his behalf (as example of that is when you allow a web or mobile application to access your instagram photos or facebook friends list)

B- configure(AuthorizationServerEndpointsConfigurer endpoints)
this method let you configure the oauth2 endpoints settings as: where to store the tokens, codes, and many other customizations that are usually not needed (the most important one is setting the token store)

3- Resource Server.java

here we can configure 2 important things

https://github.com/blabadi/oauth2lw-parent/blob/master/oauth2lw-core/src/main/java/com/bashar/oauth2lw/core/ResourceServer.java


1- configure(ResourceServerSecurityConfigurer resources)
this can allow us to configure the id of this resource server (becomes handy if we have multiple resource servers and we have access rules for different clients on each of them) and the more important config is the token store, i.e. where to verify the tokens that we receive in the requests and make sure they are authentic and created by our Authorization server.

2- configure(HttpSecurity http)
this is important and allows us to configure the urls that we want to protect under the oauth2 protocl in this resource, anything we specify here will require a valid token that can access this resource propery and in my default configuration i protected any api under the path /protected to be fully authenticated, now this is app specific configs because each app has its own apis and roles and security rules, so make sure you understand how to use the HttpSecurity builder

it worths mentioning the oauth2 spring libraries provide some exprissions like hasScope() and other security functions related to oauth2 security.


now how to use these classes?

you just have to add this jar in your deps in maven or gradle or whatever and import these 3 classes to your spring configurations, I have made an example in this client project:


https://github.com/blabadi/oauth2lw-parent/blob/master/oauth2lw-client/src/main/java/com/bashar/oauth2lw/client/Oauth2lwClientApplication.java

this is simple spring boot application and in it, just for practicing i overrode the method that configures clients in Authorization server and added my own client.. this can be converted to jdbc or whatever you want

and for the other 2 classes I haven't changed anything so I just imported them as is, if I haven't changed anything in Authorization server I would have also just imported it, but it will be scanned automatically since we extended it and annotated it with @Configration


and when we run the application and as for a protected (although non existing) url like :



so to get a token there are many flows but the more complex and more typical that we would use oauth2 for is authorization code flow, so to obtaina  token go to the browser and type in :

http://localhost:8080/oauth/authorize?response_type=code&client_id=trusted1&redirect_uri=http://localhost:9090/redirect

this will redirect us to login page where this is similar to when you are redirected to facebook by a third party app to login and approve its permissions to get some of your data

so we login with our dummy in memory user setup in the spring security configs:


then you get the approval of scopes page


and if the user approves, then the server will issue an authorization code and return it to the 3rd party app on the redirect uri provided 


the 3rd party server now should exchange that code with our server to an access token




after getting the token it can now use it to access the protected resoruce that we couldn't access before




Simple and clean and ready to be used out of the box just get the jar of the oauth2lw-core and drop it in your project and you will have oauth2 security ready.

note that the core lib pom already have the required deps:

org.springframework.cloud spring-cloud-starter-oauth2

so no need for you to worry about it..


Comments

Post a Comment

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…

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.


Steps:

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)

https://gist.github.com/anonymous/d33a31ddc3ba84375cf3

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…