springboot-basic-security

Create a project with dependency web along with”security” in it

In the main application enable the security dependency using annotation @EnableWebSecurity

Now create a package with a name “springconfig” and inside that create a class “SpringConfiguration”. Annotate it as a @Configuration

Extent the WebSecuriyConfigurationAdaptor and override two methods with the same name (configure) but with different parameters,  the one is with AuthenticationManagerBuilder and the other is HttpSecurity.

AuthenticationManagerBuilder based configure method let us create a user with password and role.

HttpSecurity based configure let us restrict the access of the api’s and also enables role based access or fully authentication based access.

We also need bcryt to perform encryption on plain text passwords though here we are using decrypted method NoOpPasswordEncoder.

Output

In case we need different kind of configuration for different controller, where we require a security check only for specific url’s. We can use url based security pattern.

Create another controller with root url “/noAuth”

The authentication will happen only for url with root “rest” and not for “noAuth”

Now in this example we need only Admin to have access to the getMsg Method and not the users. In this case we can configure role based security.

Lets test it by trying to login through normal user.

Now lets try with admin

Git repo: https://github.com/AdarshKvT/spring-basic-security.git

Leave a comment