Karim Aya

Karim Aya


Spring Security in Action

Spring Security in Action - Spring Security is a highly customizable authentication and access-control framework for Java applications, especially for Spring-based applications. This framework is also widely used in Java development.

Why Do We Need Spring Security?

Spring Security is integrated with the most popular framework, Spring Boot. It supports both authentication and authorization, which are the most popular approaches to dealing with security issues between the server and client-end. Like all Spring-based projects, the real power of Spring Security is found in how easily it can be extended to meet customer requirements.

Spring Security in Action

In this example, we will go through a very basic Spring Security application. There are four important classes to be introduced — HttpSecurity, WebSecurityConfigurer, UserDetailsService, and AuthenticationManager. The final application will cover the following features:

  1. Username and password verification
  2. Role control
  3. Token distribution, using JWT
  4. Token verification
  5. Password crypto

Through the process of implementation, we will cover some fundamental principles of Spring Security.

Include Spring Security Dependencies

compile "org.springframework.boot:spring-boot-starter-security"

Token Distribution

The first thing to do is define a way to grant tokens. There are several grant types to accomplish this, including “password,” " authorization<em>code," " implicit," and " client</em>credentials." In our example, we used " password" as the grant type.


public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {






.scopes("read", "write")



Normally, we don’t use in-memory client id and secret. In production, we can configure to read all clients from the database, as shown below:


After that, we need to configure token settings, including:

  1. Token store
  2. Token converter
  3. Token manager
  4. Enhancer chain

In this example, we are using JWT to manage our tokens. JWT provides convenient APIs that closely integrate with Spring Security. There is a converter used to convert and decode tokens. All you need to do is to set a signing key and then set them in the config(AuthorizationServerEndpointsConfigurer endpoints) function.


public JwtAccessTokenConverter accessTokenConverter() {

JwtAccessTokenConverter converter = new JwtAccessTokenConverter();


return converter;



public TokenStore tokenStore() {

return new JwtTokenStore(accessTokenConverter());



public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

TokenEnhancerChain enhancerChain = new TokenEnhancerChain();







Remember that the tokenService and authenticationManager must be the same one in token verification so that the token can be decoded properly.

Token Verification

Now, you are able to implement your own security policy. A popular way is to extend WebSecurityConfigurerAdapter and rewrite security control functions based on your customer’s requirements. Listed below are the important functions:

  1. The passwordEncoder() function defines the way to encode and compare the passwords.
  2. The configure(HttpSecurity http) function sets the resource strategy.

public void configure(HttpSecurity http) throws Exception {






.antMatchers("/public/**").permitAll() //no authorization required here

.antMatchers("/demo/**").authenticated(); //need authorization



  1. The configure(ResourceServerSecurityConfigurer resources) function defines the security strategy.

In this config() function, we need to assign a token service to explain tokens. A typical token service is defined below.



public DefaultTokenServices tokenServices() {

DefaultTokenServices defaultTokenServices = new DefaultTokenServices();



return defaultTokenServices;


  1. The authenticationManager() function defines the token verification logic. This class will be used to check user authentication when a token is refreshed.

Optional: Custom Token Authorization Verification Logic

If the default token manager does not meet your requirements, which is happening all the time, you could use your own authenticationProvider by using the code below:


protected void configure(AuthenticationManagerBuilder auth) throws Exception {



And the provider can look like this:


public Authentication authenticate(Authentication authentication) throws 

AuthenticationException {

DecodedJWT jwt = ((JwtAuthenticationToken) authentication).getToken();

//I want a token never expired.

//if (jwt.getExpiresAt().before(Calendar.getInstance().getTime()))

//throw new NonceExpiredException("Token expires");

String clientId = jwt.getSubject();

UserDetails user = userService.loadUserByUsername(clientId);

if (user == null || user.getPassword() == null)

throw new NonceExpiredException("Token expires");

Algorithm algorithm = Algorithm.HMAC256(user.getPassword());

JWTVerifier verifier = JWT.require(algorithm)



try {


} catch (Exception e) {

throw new BadCredentialsException("JWT token verify fail", e);


return new JwtAuthenticationToken(user, jwt, user.getAuthorities());


Optional: Custom Verification Chain

If the authenticate() function throws an exception, we may handle it or just record it in the database. To implement it, we can just set tokenValidSuccessHandler and tokenValidFailureHandler. In the handler, you can rewrite onAuthenticationSuccess and onAuthenticationFailure with your own logic.



.apply(new MyValidateConfigure<>())




public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {


public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponseresponse,

AuthenticationException exception) {





UserDetailServiceis the core interface that loads user-specific data. We must realize the loadUserByUsername() function to locate the user and the user’s role.


Once all the authorization configurations have been finished, you can start to enjoy developing your project. To control your role and access, you can simply add @PreAuthorize("hasAuthority('ADMIN_USER')") in your REST API declaration.

@RequestMapping(value = "/users", method = RequestMethod.GET)

@PreAuthorize("hasAuthority('ADMIN_USER')") //user with ADMIN_USER role have this access.

public ResponseEntity<List<User>> getUsers() {

return new ResponseEntity<>(userService.findAllUsers(), HttpStatus.OK);



1. Apply for a Token

Client-end can either use postman or curl to get a token.

curl client-id:client-password@localhost:8080/oauth/token -d grant_type=password -d username=admin.admin -d password=Test!123

You will get:

{"access_token":"eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsic3ByaW5nLXNlY3VyaXR5LWRlbW8tcmVzb3VyY2UtaWQiXSwidXNlcl9uYW1lIjoiYWRtaW4uYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNTU0ODQ0NTQxLCJhdXRob3JpdGllcyI6WyJTVEFOREFSRF9VU0VSIiwiQURNSU5fVVNFUiJdLCJqdGkiOiI4MTM3Y2Q4OS0wMWMyLTRkMTgtYjA4YS05MjNkOTcxYjNhYzQiLCJjbGllbnRfaWQiOiJjbGllbnQtaWQifQ.1t_4xVT8xaAtisHaNT_nMRBLKfpiI0SZQ2bbEGxu6mk","token_type":"bearer","expires_in":43199,"scope":"read write","jti":"8137cd89-01c2-4d18-b08a-923d971b3ac4"}

2. Use the Token in Role Control

Then use the token above to post a request which needs authorization.

curl http://localhost:8080/demo/users -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsic3ByaW5nLXNlY3VyaXR5LWRlbW8tcmVzb3VyY2UtaWQiXSwidXNlcl9uYW1lIjoiYWRtaW4uYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNTU0ODQ0NTQxLCJhdXRob3JpdGllcyI6WyJTVEFOREFSRF9VU0VSIiwiQURNSU5fVVNFUiJdLCJqdGkiOiI4MTM3Y2Q4OS0wMWMyLTRkMTgtYjA4YS05MjNkOTcxYjNhYzQiLCJjbGllbnRfaWQiOiJjbGllbnQtaWQifQ.1t_4xVT8xaAtisHaNT_nMRBLKfpiI0SZQ2bbEGxu6mk"

It will return:

[{"id":1,"username":"jakob.he","firstName":"Jakob","lastName":"He","roles":[{"id":1,"roleName":"STANDARD_USER","description":"Standard User"}]},{"id":2,"username":"admin.admin","firstName":"Admin","lastName":"Admin","roles":[{"id":1,"roleName":"STANDARD_USER","description":"Standard User"},{"id":2,"roleName":"ADMIN_USER","description":"Admin User"}]}]

3. Verify the Token With JWT

Put your token and signing key in jwt.io; you will get the following result.

Let’s quickly go over what we have done: We have introduced Spring Security and why we need to use it. We have also implemented a complete Spring Security application that included token management, token distribution, and REST APIs that are required for web authorization.

I hope this article is helpful!

#spring-boot #security

What is GEEK

Buddha Community

Spring Security in Action
Wilford  Pagac

Wilford Pagac


Best Custom Web & Mobile App Development Company

Everything around us has become smart, like smart infrastructures, smart cities, autonomous vehicles, to name a few. The innovation of smart devices makes it possible to achieve these heights in science and technology. But, data is vulnerable, there is a risk of attack by cybercriminals. To get started, let’s know about IoT devices.

What are IoT devices?

The Internet Of Things(IoT) is a system that interrelates computer devices like sensors, software, and actuators, digital machines, etc. They are linked together with particular objects that work through the internet and transfer data over devices without humans interference.

Famous examples are Amazon Alexa, Apple SIRI, Interconnected baby monitors, video doorbells, and smart thermostats.

How could your IoT devices be vulnerable?

When technologies grow and evolve, risks are also on the high stakes. Ransomware attacks are on the continuous increase; securing data has become the top priority.

When you think your smart home won’t fudge a thing against cybercriminals, you should also know that they are vulnerable. When cybercriminals access our smart voice speakers like Amazon Alexa or Apple Siri, it becomes easy for them to steal your data.

Cybersecurity report 2020 says popular hacking forums expose 770 million email addresses and 21 million unique passwords, 620 million accounts have been compromised from 16 hacked websites.

The attacks are likely to increase every year. To help you secure your data of IoT devices, here are some best tips you can implement.

Tips to secure your IoT devices

1. Change Default Router Name

Your router has the default name of make and model. When we stick with the manufacturer name, attackers can quickly identify our make and model. So give the router name different from your addresses, without giving away personal information.

2. Know your connected network and connected devices

If your devices are connected to the internet, these connections are vulnerable to cyber attacks when your devices don’t have the proper security. Almost every web interface is equipped with multiple devices, so it’s hard to track the device. But, it’s crucial to stay aware of them.

3. Change default usernames and passwords

When we use the default usernames and passwords, it is attackable. Because the cybercriminals possibly know the default passwords come with IoT devices. So use strong passwords to access our IoT devices.

4. Manage strong, Unique passwords for your IoT devices and accounts

Use strong or unique passwords that are easily assumed, such as ‘123456’ or ‘password1234’ to protect your accounts. Give strong and complex passwords formed by combinations of alphabets, numeric, and not easily bypassed symbols.

Also, change passwords for multiple accounts and change them regularly to avoid attacks. We can also set several attempts to wrong passwords to set locking the account to safeguard from the hackers.

5. Do not use Public WI-FI Networks

Are you try to keep an eye on your IoT devices through your mobile devices in different locations. I recommend you not to use the public WI-FI network to access them. Because they are easily accessible through for everyone, you are still in a hurry to access, use VPN that gives them protection against cyber-attacks, giving them privacy and security features, for example, using Express VPN.

6. Establish firewalls to discover the vulnerabilities

There are software and firewalls like intrusion detection system/intrusion prevention system in the market. This will be useful to screen and analyze the wire traffic of a network. You can identify the security weakness by the firewall scanners within the network structure. Use these firewalls to get rid of unwanted security issues and vulnerabilities.

7. Reconfigure your device settings

Every smart device comes with the insecure default settings, and sometimes we are not able to change these default settings configurations. These conditions need to be assessed and need to reconfigure the default settings.

8. Authenticate the IoT applications

Nowadays, every smart app offers authentication to secure the accounts. There are many types of authentication methods like single-factor authentication, two-step authentication, and multi-factor authentication. Use any one of these to send a one time password (OTP) to verify the user who logs in the smart device to keep our accounts from falling into the wrong hands.

9. Update the device software up to date

Every smart device manufacturer releases updates to fix bugs in their software. These security patches help us to improve our protection of the device. Also, update the software on the smartphone, which we are used to monitoring the IoT devices to avoid vulnerabilities.

10. Track the smartphones and keep them safe

When we connect the smart home to the smartphone and control them via smartphone, you need to keep them safe. If you miss the phone almost, every personal information is at risk to the cybercriminals. But sometimes it happens by accident, makes sure that you can clear all the data remotely.

However, securing smart devices is essential in the world of data. There are still cybercriminals bypassing the securities. So make sure to do the safety measures to avoid our accounts falling out into the wrong hands. I hope these steps will help you all to secure your IoT devices.

If you have any, feel free to share them in the comments! I’d love to know them.

Are you looking for more? Subscribe to weekly newsletters that can help your stay updated IoT application developments.

#iot #enterprise iot security #how iot can be used to enhance security #how to improve iot security #how to protect iot devices from hackers #how to secure iot devices #iot security #iot security devices #iot security offerings #iot security technologies iot security plus #iot vulnerable devices #risk based iot security program

Sigrid  Farrell

Sigrid Farrell


Spring Security Overview

In this article, we will take a bird’s eye view of Spring Security to understand what it is used for and what it has to offer us. Anything on the web is a potential victim of an attack. Unfortunately, securing a web application and implementing features like authorization and authentication are no walk in the park in a world where even the richest, most innovative technology companies get hacked. So when our boss gives us a task to secure the application, should we sit and wait, scared, not knowing what to do? Of course not.

Whether or not you are going to use Auth0 to secure your Spring app, you will need to know the basics of Spring Security to secure your application rapidly, and this makes it a must-know framework for any Spring developer. The thing with Spring Security is: It is difficult. Not because it is poorly designed or could be easier to use, but because of the complexity of its domain: Application security. Complex problems require technically sophisticated solutions, and security is one of them.

If you have ever taken a glance at a Spring Security-related documentation or tutorial, you might be scared of how complicated it looks. I mean, take a look at this picture from Wikipedia:

Acegi Security Basic Auth Flow

It is very natural to feel overwhelmed, especially if you are also new to Spring. Spring Security is a huge framework, but once you get the basics down, you can easily get the task of securing your app done by integrating it with an IDaaS service like Auth0 without the hassle of implementing everything yourself.

#spring security overview #spring #spring security #security

Were  Joyce

Were Joyce


Angular 12 + Spring Boot: JWT Authentication example | Spring Security

In this tutorial, I will show you how to build a full stack Angular 12 + Spring Boot JWT Authentication example. The back-end server uses Spring Boot with Spring Security for JWT Authentication & Role based Authorization, Spring Data JPA for interacting with database. The front-end will be built using Angular 12 with HttpInterceptor & Form validation.

Related Posts:

– Angular 12 + Spring Boot: CRUD example

– Angular 12 + Spring Boot: File upload example

– Spring Boot, MongoDB: JWT Authentication with Spring Security

Contents [hide]

#angular #full stack #spring #angular #angular 12 #authentication #authorization #jwt #login #registration #security #spring boot #spring security #token based authentication

Sigrid  Farrell

Sigrid Farrell


Spring Security Authentication Process : Authentication Flow Behind the Scenes

In every application, Authentication is the first layer of protection. Thus, Authentication is a major part of Application Security and in this post we will dive deep into the architecture used by **Spring Security **for Authentication.

What is Authentication?_ Authentication is proving who you are. For example, your Identity Card is used to “authenticate” you in your School/College/Office campus._

Spring Security provides excellent support for Authentication by default. Kind of in a plug-in-and-play fashion. A simple Authentication workflow is really easy to setup. However, if you wanna go for a complete custom implementation then you need to understand the authentication flow and comprehend what happens behind the scenes when an authentication request is received by the server.

#spring-security #spring #authentication #rest-api #spring-boot #spring security authentication process : authentication flow behind the scenes

Selina  O'Hara

Selina O'Hara


Adding Spring Security to Spring Boot | Exploring Spring Security Auto Configuration

In this video, we will learn how to add Spring Security to the Spring boot application and we will explore Spring security auto-configuration in the Spring boot application.

The complete course at https://courses.javaguides.net/p/building-rest-api-with-spring-boot

#spring #security #spring-boot #java