Elvis Miranda

Elvis Miranda


Built Secure API with Spring Boot Angular 6

1.Spring Boot Angular 6 Example

Today web security is very important, creating and using any services without security is very risky nowadays. If you are transmitting very sensitive data, you must like to use a very nice secure layer to protect your confidential data, Isn’t it?.

It’s all about securing our systems.

So, Whenever we are using API call or anything we must have to first consider the security of our sensitive data. There are so many types of security methods available to secure our data. In this post, We comprehensive example on Spring security, Spring boot and angular to demonstrate how we can secure your angular application using Basic Authentication via Spring Security. You will learn to use Spring Boot for quickly building web API, in short, a java backend layer and then adding Spring Security maven dependency for making it secure. We will use Angular platform that makes it easy to build the application with the web and use our own database.

Before beginning developing the application here is the showcase of the application that we are going to build in the next sections.

Angular Application Preview

Above is an example of my heroes that displays a list of hero names. Initially, we will keep the endpoint non-secure so that the Angular is able to display the list of names. Then, we will add a secure REST endpoint and make the necessary changes to our Angular app for accessing the data using Basic Authentication.

2. Technologies Used

  • Angular 6
  • Spring Boot 2.0.6
  • Java 1.8.0
  • Apache Maven 3.5.3
  • Visual Studio Code 1.28.2
  • Spring Tool Suite 3.9.5
  • Mysql 5.7.19

3. Build Java back-end using Spring Boot

There are many ways we can create a Spring Boot project. The following is a list of ways:

We will not go deeper into each and everyone will just use Spring Tool Suite to create a project.

3.1 Create a starter project

Go to File->New->Spring Starter Project and enter necessary details and select dependencies as per the following screenshots

spring boot angular 7 crud example

angular 6 spring boot login example

You will have to select these dependencies in order to add in maven POM.xml file, then just hit the finish button and project will be created with required libraries

3.2 Create a database

Create a table into your database then feeds with data, here is the query for creating and inserting records into the table.

CREATE TABLE `heroes` (
`name` varchar(20) DEFAULT NULL,
KEY `id` (`id`)
insert  into `heroes`(`id`,`name`) values (1,'Aung San Suu Kyi'),(2,'Nelson Mandela'),(3,'Tony Blair'),(4,'Dr. Abdul Kalam'),(5,'Srinivas Ramanujan'),(6,'Stephen Hawking'),(7,'Bob Geldof'),(8,'Margaret Thatcher'),(9,'Winston Churchill'),(10,'Bob Dylan'),(11,'Bill Gates'),(12,'Steve Jobs'),(13,'Dalai Lama'),(14,'David Attenborough'),(15,'Mary Robinson'),(16,'Tim Berners-Lee');

3.3 Add an insecure REST endpoint

Just add the following code as shown below to each file :

1. Application.properties :


2. SecureRestServiceApplication.java :

package com.example.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EntityScan(basePackages = "com.example.model")
@EnableJpaRepositories(basePackages = {"com.example.repository"})
@ComponentScan(basePackages = "com.example.controller")
public class SecureRestServiceApplication {
public static void main(String[] args) {
SpringApplication.run(SecureRestServiceApplication.class, args);

3. HeroesController.java

package com.example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.Heroes;
import com.example.repository.HeroesRepository;

public class HeroesController {
	HeroesRepository heroesRepository;
	public List getHeroes(){
		return heroesRepository.findAll();

4. Heroes.java

package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "heroes")
public class Heroes {
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
public Heroes() {}
public Heroes(int id, String name) {
this.name = name;
public int getId() {
return id;
public void setId(int id) {
this.id = id;
public String getName() {
return name;
public void setName(String name) {
this.name = name;

5. HeroesRepository.java

package com.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.example.model.Heroes;
public interface HeroesRepository extends JpaRepository {}

6. Execute in postman or any browser

Now, restart the application, open browser or use postman to hit this URL http://localhost:7070/api/heroes. You should see the information of heroes in JSON format see below :)

JSON output in postman

4. Build front-end application using Angular

Let’s build a front-end, we will use Angular CLI to create an Angular app. Execute the following command in your command prompt.

ng new secure-hero-app

The command might take few minutes for creating configuration files and bringing in all the dependencies. It will also create a very simple application for you. Once the command completes, execute

ng serve --open

This command will start and will open your default browser automatically with the http://localhost:4200 URL and you will see default angular page.

4.1 Create required artifacts

We now need to create some components, services and routing modules to our angular app. We will create 1 component, 1 routing module and 1 service using these following command

1. Create a service

ng generate service hero
  • Hero.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

  providedIn: 'root'
export class HeroService {

  constructor(private http: HttpClient) { }

  getHeroes() {
    const url = 'http://localhost:7070/api/heroes';    
    return this.http.get(url);

2. Create a routing module

ng generate module app-routing --flat --module=app

In the app-routing module add the following code.

  • App-routing.module.ts
import { HeroesComponent } from './heroes/heroes.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

const routes: Routes = [
  { path: 'heroes', component: HeroesComponent}

  imports: [
  exports: [ RouterModule]
export class AppRoutingModule { }

3. Create a component

ng generate component heroes

Update your component files as shown below :

/* HeroesComponent's private CSS styles */
  .heroes {
    margin: 0 0 2em 0;
    list-style-type: none;
    padding: 0;
    width: 15em;
  .heroes li {
    cursor: pointer;
    position: relative;
    left: 0;
    background-color: #EEE;
    margin: .5em;
    padding: .3em 0;
    height: 1.6em;
    border-radius: 4px;
  .heroes li.selected:hover {
    background-color: #BBD8DC !important;
    color: white;
  .heroes li:hover {
    color: #607D8B;
    background-color: #DDD;
    left: .1em;
  .heroes .text {
    position: relative;
    top: -3px;
  .heroes .badge {
    display: inline-block;
    font-size: small;
    color: white;
    padding: 0.8em 0.7em 0 0.7em;
    background-color: #607D8B;
    line-height: 1em;
    position: relative;
    left: -1px;
    top: -4px;
    height: 1.8em;
    margin-right: .8em;
    border-radius: 4px 0 0 4px;


## My Heroes

{{hero.id}} {{hero.name}} 
 --> {{hero.id}} {{hero.name}} 

**heroes.component.html **

import { HeroService } from './../hero.service';
import { Component, OnInit } from '@angular/core';

  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
export class HeroesComponent implements OnInit {

  heroes$: Object;
  constructor(private data: HeroService) { }

  ngOnInit() {
      data => this.heroes$ = data



4. A glance at the App module

For using HTTP service in our service class, we need to import HttpClientModule as shown below :

  • App.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';
import { AppRoutingModule } from './/app-routing.module';
import { HttpClientModule } from '@angular/common/http';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

4.2 Access the application

After going through the above steps, you should be able to see the list of heroes by accessing http://localhost:4200/heroes in the browser.

5. Secure your REST endpoint using Spring Security

To enable spring security in your app, simply add the following dependency to the pom.xml


Now, try accessing http://localhost:7070/api/heroes . You should see a browser dialogue asking for the credentials as shown below

Spring security login page

The default username is user and you can get the password from your STS console as shown Below

Eclipse console output

In order to use your own username and password instead of generating one, you need to specify the following properties in the application.properties file as shown below.


6. Update your angular endpoint for accessing secure REST endpoint

If you try to access http://localhost:4200/heroes in the browser or postman it will throw 401 status code that means unauthorized access to the URL. We need to send basic authorization headers in our HTTP request. So let’s update our hero service, specifying the method getHeroes()

getHeroes() {
const url = 'http://localhost:7070/api/heroes';
const headers = new HttpHeaders({Authorization: 'Basic ' + btoa('test:test123')});
return this.http.get(url, { headers });

Now try again by verifying http://localhost:7070/api/heroes browser. Does it work?.

No, and the reason for this is we need to add support of CORS protocol at our REST back-end, It is explained in the next section.

7. Cross-origin resource sharing (CORS)

We need to support the CORS protocol for our Angular service to be able to invoke an endpoint on a different domain. By different domain, we mean that our front-end application running on http://localhost:4200 is requesting a resource on another domain i.e. http://localhost:7070. Hence, on the server, we need to configure the CORS. This is done by providing the support for CORS protocol.

We need to create Configuration class for web security, this class will signal the Spring security to allow pre-flight check from the browser. This is done by overriding the configure method of WebSecurityConfigurerAdapter.

We need to create two files CustomFilter.java and SecurityConfiguration.java as shown below :

package com.example.config;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class CustomFilter extends OncePerRequestFilter {

	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
				"authorization, content-type, xsrf-token, Cache-Control, remember-me, WWW-Authenticate");
		response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
		chain.doFilter(request, response);


Now Verify again http://localhost:4200 in the browser and you should be able to see the listing of heroes again.


8. Short Summary

In this post, we have created a simple REST API using Spring Boot. We secured this using Spring Security Using Basic Authentication type. At last, we used the popular front-end platform Angular for accessing the secure API.

spring boot + angular 4 example, integrate angular 6 with spring boot,

#angular #angular-js #javascript

What is GEEK

Buddha Community

Built Secure API with Spring Boot Angular 6
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

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Were  Joyce

Were Joyce


Spring Boot Authorization Tutorial: Secure an API (Java)

Learn how to use Spring Boot, Java, and Auth0 to secure a feature-complete API. Learn how to use Auth0 to implement authorization in Spring Boot.

Learn how to secure an API with the world’s most popular Java framework and Auth0.

So far, you’ve built an API that allows anyone to read and write data. It’s time to tighten the security, so only users with the menu-admin role can create, update, and delete menu items.

Authentication vs. Authorization

To know what a user can do, you first need to know who the user is. This is known as authentication. It is often done by asking for a set of credentials, such as username & password. Once verified, the client gets information about the identity and access of the user.

To implement these Identity and Access Management (IAM) tasks easily, you can use OAuth 2.0, an authorization framework, and OpenID Connect (OIDC), a simple identity layer on top of it.

OAuth encapsulates access information in an access token. In turn, OpenID Connect encapsulates identity information in an ID token. The authentication server can send these two tokens to the client application initiating the process. When the user requests a protected API endpoint, it must send the access token along with the request.

You won’t have to worry about implementing OAuth, OpenID Connect, or an authentication server. Instead, you’ll use Auth0.

Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications. Your team and organization can avoid the cost, time, and risk that comes with building your own solution. Also, there are tons of docs and SDKs for you to get started and integrate Auth0 in your stack easily.

#spring boot authorization tutorial: secure an api (java) #spring boot #api (java) #authorization #spring boot authorization tutorial #api

Sigrid  Farrell

Sigrid Farrell


Angular 12 + Spring Boot: CRUD example

In this tutorial, we will learn how to build a full stack Spring Boot + Angular 12 example with a CRUD App. The back-end server uses Spring Boot with Spring Web MVC for REST Controller and Spring Data JPA for interacting with embedded database (H2 database). Front-end side is made with Angular 12, HttpClient, Router and Bootstrap 4.

Run both Project on same server/port:

How to Integrate Angular with Spring Boot Rest API

Contents [hide]

#angular #full stack #spring #angular #angular 12 #crud #h2 database #mysql #postgresql #rest api #spring boot #spring data jpa

Sigrid  Farrell

Sigrid Farrell


Angular 12 + Spring Boot + PostgreSQL example: Build CRUD App

In this tutorial, we will learn how to build a full stack Angular 12 + Spring Boot + PostgreSQL example with a CRUD App. The back-end server uses Spring Boot with Spring Web MVC for REST Controller and Spring Data JPA for interacting with PostgreSQL database. Front-end side is made with Angular 12, HTTPClient, Router and Bootstrap 4.

Older versions:

– Angular 10 + Spring Boot + PostgreSQL example: CRUD App

– Angular 11 + Spring Boot + PostgreSQL example: CRUD App

Contents [hide]

#angular #full stack #spring #angular #angular 12 #crud #postgresql #rest api #spring boot #spring data jpa