Newsletter

Spring Boot + Spring Security – RESTful Web Service with basic Authentication

Spring-Boot-Tutorials » on May 8, 2018 { 5 Comments } By Sivateja

In this article, I am going to explain you how to implement basic authentication for RESTful web services using Spring Boot and Spring Security. We will need to create a java file with spring security configurations in it, that’s it 🙂

Required Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Final pom.xml

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.java4s</groupId>
    <artifactId>SpringBootSpringSecurityBasicAuth</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>
    <properties>
        <java.version>1.8</java.version>
    </properties>
</project>

SpringBootApp.java

package com.java4s.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }
}

SpringSecurityConfig.java

package com.java4s.app.configs;


import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    // Authentication : set user/password details and mention the role
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance())
            .withUser("user").password("pass").roles("USER")
            .and()
            .withUser("admin").password("pass").roles("USER", "ADMIN");
    }

    // Authorization : mention which role can access which URL
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests()
            .antMatchers("/userlogin").hasRole("USER")
            .antMatchers("/adminlogin").hasRole("ADMIN")
            .and()
            .csrf().disable().headers().frameOptions().disable();
    }
}

SpringJava4sController.java

package com.java4s.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringJava4sController {

    @RequestMapping("/userlogin")
    public String userValidation() {
        return "User: Successfully logged in!";

    }

    @RequestMapping("/adminlogin")
    public String adminValidation() {
        return "Admin: Successfully logged in!";

    }

}

Now run the application, if you hit /springbootwithsecurity/userlogin you should provide user/pass as credentials and for /springbootwithsecurity/adminlogin admin/pass, give a try 😉 I am not going to explain the SpringSecurityConfig.java as its easily understandable.

Output

In the next article, I will explain how to implement the Authentication using database.

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

5 Responses to “Spring Boot + Spring Security – RESTful Web Service with basic Authentication”
  1. indra reddy says:

    Hi, please explain SpringSecurityConfig class also. most of the people like me don't know about Security's.
    if you explain that it's very helpful tu us

  2. springboot says:

    Please add few lines lines of explanations to below each block of code. Example: explaining WebSecurityConfigurerAdapter in one or two lines.

  3. Apparao says:

    For me application not working means it's not showing login to enter username and password directly showing output help me in that

  4. vamsi says:

    I have tried this logic, it works for the first time but if my springboot application is restarted, it is not showing login dialog box. Could you please advice me how to fix it. I want this logic to run each time I start the application

  5. Padma says:

    So whenever there is spring-boot-starter-security dependency , how the Spring's dispatcher servlet will route the request for authentication and authorization since after authentication only the requests will be routed back to the controller. Could you elaborate on this please. Thanks!.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2019 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.